问:
How to fix the "undefined" return from my mongoose/mongodb search function
I'm attempting to get the result from mongodb and then pass it to a const, but getting return vale of "undfined" where did I go wrong?

I made sure that the code works without the return and prints to console and made sure the data set is present in my mongodb.

```<code>const mongoose = require('mongoose');

function search(query) {
  const search = db.collection('spells').find({
    "name": query
  }).then(function(cursor) {
    cursor.forEach(function(spell) {
      console.log(spell);
      return spell;
    });
  });
}

mongoose.connect('mongodb://localhost/dnd', {
  useNewUrlParser: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to DB" + "\n");

});

console.log(search("Blight"));
</code>```

when the above is ran I get the following outputs on command line

undefined

Connected to DB

Then it prints the following which is the data in Mongodb

```<code>{ _id: 5ced1ce8aa89b60a7c2e34de,
  name: 'Blight',
  level: 4,
  school: 'N',
  time: [ { number: 1, unit: 'action' } ],
  range: { type: 'point', distance: { type: 'feet', amount: 30 } },
  components: { v: true, s: true },
  duration: [ { type: 'instant' } ],
  classes:
   { fromClassList: [ [Object], [Object], [Object], [Object] ],
     fromSubclass:
      [ [Object], [Object], [Object], [Object], [Object], [Object] ] },
  source: 'PHB',
  entries:
   [ 'Necromantic energy washes over a creature of your choice that you can see within range, draining moisture and vitality from it. The target must make a Constitution saving throw. The target takes {@dice 8d8} necrotic damage on a failed save, or half as much damage on a succ
essful one. This spell has no effect on undead or constructs.',
     'If you target a plant creature or a magical plant, it makes the saving throw with disadvantage, and the spell deals maximum damage to it.',
     'If you target a nonmagical plant that isn\'t a creature, such as a tree or shrub, it doesn\'t make a saving throw, it simply withers and dies.' ],
  entriesHigherLevel:
   [ { type: 'entries', name: 'At Higher Levels', entries: [Array] } ],
  page: 219,
  damageInflict: [ 'necrotic' ],
  savingThrow: [ 'constitution' ] }
</code>```

I want to be able to get the data via the return and not inside the function.

答:
You are currently returning the data to the promise but your function is not returning anything, you can return the array object and later handle the results</p>

```<code>async function search(query) {
  try {
    const search = await db.collection('spells').find({
      "name": query
    }).toArray();
    return search;
  } catch(err) {
    throw new Error(err);
  }
}
</code>```

Body:
I'm attempting to get the result from mongodb and then pass it to a const, but getting return vale of "undfined" where did I go wrong?

I made sure that the code works without the return and prints to console and made sure the data set is present in my mongodb.

const mongoose = require('mongoose');

function search(query) {
  const search = db.collection('spells').find({
    "name": query
  }).then(function(cursor) {
    cursor.forEach(function(spell) {
      console.log(spell);
      return spell;
    });
  });
}

mongoose.connect('mongodb://localhost/dnd', {
  useNewUrlParser: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to DB" + "\n");

});

console.log(search("Blight"));

when the above is ran I get the following outputs on command line

undefined

Connected to DB

Then it prints the following which is the data in Mongodb

{ _id: 5ced1ce8aa89b60a7c2e34de,
  name: 'Blight',
  level: 4,
  school: 'N',
  time: [ { number: 1, unit: 'action' } ],
  range: { type: 'point', distance: { type: 'feet', amount: 30 } },
  components: { v: true, s: true },
  duration: [ { type: 'instant' } ],
  classes:
   { fromClassList: [ [Object], [Object], [Object], [Object] ],
     fromSubclass:
      [ [Object], [Object], [Object], [Object], [Object], [Object] ] },
  source: 'PHB',
  entries:
   [ 'Necromantic energy washes over a creature of your choice that you can see within range, draining moisture and vitality from it. The target must make a Constitution saving throw. The target takes {@dice 8d8} necrotic damage on a failed save, or half as much damage on a succ
essful one. This spell has no effect on undead or constructs.',
     'If you target a plant creature or a magical plant, it makes the saving throw with disadvantage, and the spell deals maximum damage to it.',
     'If you target a nonmagical plant that isn\'t a creature, such as a tree or shrub, it doesn\'t make a saving throw, it simply withers and dies.' ],
  entriesHigherLevel:
   [ { type: 'entries', name: 'At Higher Levels', entries: [Array] } ],
  page: 219,
  damageInflict: [ 'necrotic' ],
  savingThrow: [ 'constitution' ] }

I want to be able to get the data via the return and not inside the function.

Body:
You are currently returning the data to the promise but your function is not returning anything, you can return the array object and later handle the results

async function search(query) {
  try {
    const search = await db.collection('spells').find({
      "name": query
    }).toArray();
    return search;
  } catch(err) {
    throw new Error(err);
  }
}


来源: stackexchange

问:
How to experiment with Xcode on OS X 10.4x
I'd like to start experimenting with Cocoa, Objective-C and Xcode, but the only Apple computer I own is an old PowerBook with OS X 10.4.7 installed and as far as I can tell I would have to buy and install OS X 10.5 (Leopard I think) just to be able to install Xcode 3.2 - the currently available version. The thing is I'm a Windows developer and I don't want to have to upgrade this barely functional Mac laptop just to be able to play around with Xcode. So, I'm wondering is there any way that I can download some older 2.x version of Xcode that will run on OS X 10.4.7?</p>

答:
Does your Tiger DVD have XCode on it? I know that Leopard DVDs include the then-current version of XCode.

You can also download XCode 2.1 tools from the ADC section on developer.apple.com. ADC -> Downloads -> Mac OS X.

You'll have to create an account but it's free for basic ones.

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: gs

OwnerDisplayName: Andrew Grant

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Andrew Grant


问:
The list with most elements
I have a list with dictionary as elements. Each dictionary has an entry called type. The type field represents a list. What is the simplest/pythonic way of obtaining the list with the most elements?

```<code>programmes_by_type = []
programmes_by_type.append({'type' : [1, 2, 3]})
programmes_by_type.append({'type' : [2, 5]})
programmes_by_type.append({'type' : [3]})
programmes_by_type.append({'type' : [11, 2, 6, 7]})
</code>```

Given the previous example it should return the [11, 2, 6, 7] list.

答:
```<code>max_length = 0
type_list = None

for el in programmes_by_type:
    if len(el) > max_length:
        max_length = len(el)
        type_list = el['type']
</code>```

type_list now contains the biggest list.

Title: The list with most elements

Body:
I have a list with dictionary as elements. Each dictionary has an entry called type. The type field represents a list. What is the simplest/pythonic way of obtaining the list with the most elements?

programmes_by_type = []
programmes_by_type.append({'type' : [1, 2, 3]})
programmes_by_type.append({'type' : [2, 5]})
programmes_by_type.append({'type' : [3]})
programmes_by_type.append({'type' : [11, 2, 6, 7]})

Given the previous example it should return the [11, 2, 6, 7] list.

Body:
max_length = 0
type_list = None

for el in programmes_by_type:
    if len(el) > max_length:
        max_length = len(el)
        type_list = el['type']

type_list now contains the biggest list.


问:
Bitmap getpixel returns always a negative number
I've loaded an image as a bitmap from device storage and wanted to retrieve the pixels rgb from it , but the getPixel(x,y) method always returns a large negative number

i found similar questions i even found the the same code as an answer but it doesn't work for me the bitmap is mutable

the code

```<code>inputBitmap=inputBitmap.copy( Bitmap.Config.ARGB_8888 , true);
int pixel;
byte r, g, b;
pixel =inputBitmap.getPixel(j, i);
Log.e("pixel","j "+j+" i "+i+" "+pixel);
r = (byte)Color.red(pixel);
g = (byte)Color.green(pixel);
b = (byte)Color.blue(pixel);
Log.e("COLOR","\n"+"Red : "+r+"\n"+"Green : "+g+"\n"+"Blue : "+b);
</code>```

Logcat

```<code>05-28 13:02:51.335 20379-20379/pfe.steganography E/COLOR:
    Red : -1
    Green : -1
    Blue : -1
05-28 13:02:51.335 20379-20379/pfe.steganography E/pixel:  -1
05-28 13:02:51.335 20379-20379/pfe.steganography E/COLOR:
    Red : -1
    Green : -1
    Blue : -1
05-28 13:02:51.335 20379-20379/pfe.steganography E/pixel:  -1
05-28 13:02:51.335 20379-20379/pfe.steganography E/COLOR:
    Red : -1
    Green : -1
    Blue : -1
05-28 13:02:51.335 20379-20379/pfe.steganography E/pixel:  -460552
05-28 13:02:51.335 20379-20379/pfe.steganography E/COLOR:
    Red : -8
    Green : -8
    Blue : -8
05-28 13:02:51.336 20379-20379/pfe.steganography E/pixel:  -1381654
05-28 13:02:51.336 20379-20379/pfe.steganography E/COLOR:
    Red : -22
    Green : -22
    Blue : -22
05-28 13:02:51.336 20379-20379/pfe.steganography E/pixel:  -1315861
05-28 13:02:51.336 20379-20379/pfe.steganography E/COLOR:
    Red : -21
    Green : -21
    Blue : -21
</code>```

答:
SOLVED

solved but still weird ,on the following log , i had randomly positive/negative signs but the absolute values are correct, all i had to do is keep their absolute value and it Worked

```<code>05-28 14:35:21.225 15064-15064/pfe.steganography E/pixel:  -16743306
05-28 14:35:21.225 15064-15064/pfe.steganography E/COLOR: Red : 0
    Green : -124
    Blue : 118
05-28 14:35:21.649 15064-15064/pfe.steganography E/pixel:  -13920116
05-28 14:35:21.649 15064-15064/pfe.steganography E/COLOR: Red : 43
    Green : -104
    Blue : -116
05-28 14:35:22.057 15064-15064/pfe.steganography E/pixel:  -48066684
05-28 14:35:22.057 15064-15064/pfe.steganography E/COLOR: Red : 34
    Green : -113
    Blue : -124 ````
```

ContentLicense: CC BY-SA 4.0

Body:
I've loaded an image as a bitmap from device storage and wanted to retrieve the pixels rgb from it , but the getPixel(x,y) method always returns a large negative number

i found similar questions i even found the the same code as an answer but it doesn't work for me the bitmap is mutable

the code

inputBitmap=inputBitmap.copy( Bitmap.Config.ARGB_8888 , true);
int pixel;
byte r, g, b;
pixel =inputBitmap.getPixel(j, i);
Log.e("pixel","j "+j+" i "+i+" "+pixel);
r = (byte)Color.red(pixel);
g = (byte)Color.green(pixel);
b = (byte)Color.blue(pixel);
Log.e("COLOR","\n"+"Red : "+r+"\n"+"Green : "+g+"\n"+"Blue : "+b);

Logcat

05-28 13:02:51.335 20379-20379/pfe.steganography E/COLOR:
    Red : -1
    Green : -1
    Blue : -1
05-28 13:02:51.335 20379-20379/pfe.steganography E/pixel:  -1
05-28 13:02:51.335 20379-20379/pfe.steganography E/COLOR:
    Red : -1
    Green : -1
    Blue : -1
05-28 13:02:51.335 20379-20379/pfe.steganography E/pixel:  -1
05-28 13:02:51.335 20379-20379/pfe.steganography E/COLOR:
    Red : -1
    Green : -1
    Blue : -1
05-28 13:02:51.335 20379-20379/pfe.steganography E/pixel:  -460552
05-28 13:02:51.335 20379-20379/pfe.steganography E/COLOR:
    Red : -8
    Green : -8
    Blue : -8
05-28 13:02:51.336 20379-20379/pfe.steganography E/pixel:  -1381654
05-28 13:02:51.336 20379-20379/pfe.steganography E/COLOR:
    Red : -22
    Green : -22
    Blue : -22
05-28 13:02:51.336 20379-20379/pfe.steganography E/pixel:  -1315861
05-28 13:02:51.336 20379-20379/pfe.steganography E/COLOR:
    Red : -21
    Green : -21
    Blue : -21

Body:
SOLVED

solved but still weird ,on the following log , i had randomly positive/negative signs but the absolute values are correct, all i had to do is keep their absolute value and it Worked

05-28 14:35:21.225 15064-15064/pfe.steganography E/pixel:  -16743306
05-28 14:35:21.225 15064-15064/pfe.steganography E/COLOR: Red : 0
    Green : -124
    Blue : 118
05-28 14:35:21.649 15064-15064/pfe.steganography E/pixel:  -13920116
05-28 14:35:21.649 15064-15064/pfe.steganography E/COLOR: Red : 43
    Green : -104
    Blue : -116
05-28 14:35:22.057 15064-15064/pfe.steganography E/pixel:  -48066684
05-28 14:35:22.057 15064-15064/pfe.steganography E/COLOR: Red : 34
    Green : -113
    Blue : -124 ````


问:
Spring Boot: How to auto login after user registration?
Here is a controller method for user registration:

```<code>@PostMapping("register_user")
public void registerUser(@RequestParam String email, @RequestParam String password, @RequestParam String name,
                         @RequestParam String info, HttpServletResponse response) throws EmailExistsException, IOException {
    userRepository.save(new User(email, new BCryptPasswordEncoder().encode(password), name, info));
    try {
        UserDetails userDetails = customUserDetailsService.loadUserByUsername(email);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
        authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (usernamePasswordAuthenticationToken.isAuthenticated()) {
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            log.debug(String.format("Auto login %s successfully!", email));
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    response.sendRedirect("/");
}
</code>```

Here is a configure method from SecurityConfig:

```<code>@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(customUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
</code>```

During user registration there is a "Bad credentials" error:

```<code>org.springframework.security.authentication.BadCredentialsException: Bad credentials
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:98) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:166) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at s7.controller.ActionController.registerUser(ActionController.java:45) ~[main/:na]
</code>```

After registration user can login without any errors. What am I doing wrong?

P.S. I also tried auto login like this topic: Auto login after successful registration
But I have the same BadCredentialsException.

If I comment authenticationManager.authenticate(usernamePasswordAuthenticationToken);, user will auto login without any BadCredentialsException with correct authentication.getPrincipal().

答:
I was able to solve this problem with the following code (SpringBoot 2.0.5):

```<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class SecurityService {

    @Autowired
    @Lazy
    AuthenticationManager authManager;

    private Logger logger = LoggerFactory.getLogger(SecurityService.class);

    public void doLogin(String username, String password) {

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);

        Authentication authentication = authManager.authenticate(authRequest);

        if (authentication.isAuthenticated()) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            logger.debug(String.format("Auto login successfully!", username));
        }
    }

}
</code>```

To make it work the hardest bit for me to figure out was the AuthenticationManager. You have to Autowire the same AuthenticationManager you set in your spring security configuration as shown bellow, dont forget to autowire lazy on the service.

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UsuarioService usuarioService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests()
                .antMatchers("/registration*").permitAll()
                .anyRequest().hasAnyAuthority("MASTER")
                .and()
                .formLogin().loginPage("/login").permitAll()
                .and()
                .csrf().disable()
                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "/img/**", "/files/**", "/forgot-password"");
    }

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(usuarioService);
    }

    @Bean
    public AuthenticationManager authManager() throws Exception {
        return this.authenticationManager();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }
}
</code>```

And the last problem that took me a while to figure out. If you add your registration endpoint with the "web.ignoring()" security context will not be present and you will not be able to log in the user. So be sure to add it as  .antMatchers("/registration*").permitAll()

Body:
Here is a controller method for user registration:

@PostMapping("register_user")
public void registerUser(@RequestParam String email, @RequestParam String password, @RequestParam String name,
                         @RequestParam String info, HttpServletResponse response) throws EmailExistsException, IOException {
    userRepository.save(new User(email, new BCryptPasswordEncoder().encode(password), name, info));
    try {
        UserDetails userDetails = customUserDetailsService.loadUserByUsername(email);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
        authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (usernamePasswordAuthenticationToken.isAuthenticated()) {
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            log.debug(String.format("Auto login %s successfully!", email));
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    response.sendRedirect("/");
}

Here is a configure method from SecurityConfig:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(customUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}

During user registration there is a "Bad credentials" error:

org.springframework.security.authentication.BadCredentialsException: Bad credentials
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:98) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:166) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at s7.controller.ActionController.registerUser(ActionController.java:45) ~[main/:na]

After registration user can login without any errors. What am I doing wrong?

P.S. I also tried auto login like this topic: Auto login after successful registration
But I have the same BadCredentialsException.

If I comment authenticationManager.authenticate(usernamePasswordAuthenticationToken);, user will auto login without any BadCredentialsException with correct authentication.getPrincipal().

Body:
I was able to solve this problem with the following code (SpringBoot 2.0.5):

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class SecurityService {

    @Autowired
    @Lazy
    AuthenticationManager authManager;

    private Logger logger = LoggerFactory.getLogger(SecurityService.class);

    public void doLogin(String username, String password) {

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);

        Authentication authentication = authManager.authenticate(authRequest);

        if (authentication.isAuthenticated()) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            logger.debug(String.format("Auto login successfully!", username));
        }
    }

}

To make it work the hardest bit for me to figure out was the AuthenticationManager. You have to Autowire the same AuthenticationManager you set in your spring security configuration as shown bellow, dont forget to autowire lazy on the service.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UsuarioService usuarioService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests()
                .antMatchers("/registration*").permitAll()
                .anyRequest().hasAnyAuthority("MASTER")
                .and()
                .formLogin().loginPage("/login").permitAll()
                .and()
                .csrf().disable()
                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "/img/**", "/files/**", "/forgot-password"");
    }

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(usuarioService);
    }

    @Bean
    public AuthenticationManager authManager() throws Exception {
        return this.authenticationManager();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }
}

And the last problem that took me a while to figure out. If you add your registration endpoint with the "web.ignoring()" security context will not be present and you will not be able to log in the user. So be sure to add it as  .antMatchers("/registration*").permitAll()


问:
Getting xy data from matplotlib fig object
I need to retrieve XY data from a fig object with 2 subplots.

Here is the way I made the fig object:

```<code>f, axarr = plt.subplots(1,2)
axarr[0].imshow(labels_map,vmax=28)
axarr[1].imshow(Y_predictions,vmax=28)
np.save('fig.npy', f)
</code>```

I can't remake the fig objects, because I no longer have access to the machine.

from a previous stackoverflow post:

```<code>fig = numpy.load("fig.npy").item()
ax = fig.gca()
xy_data = ax.get_lines()
print(xy_data[0])
</code>```

printing fails: "list index out of range"

I need to get the 2d array for both the subplots in order to make a confusion matrix.

答:
You have no line(s) in your plots; but images. Hence,</p>

```<code>import matplotlib.pyplot as plt
import numpy as np

f, axarr = plt.subplots(1,2)
axarr[0].imshow(np.random.randint(0,28, (10,10)),vmax=28)
np.save('fig.npy', f)
plt.close()

fig = np.load("fig.npy").item()
data = fig.axes[0].images[0].get_array()
print(data)
</code>```

Body:
I need to retrieve XY data from a fig object with 2 subplots.

Here is the way I made the fig object:

f, axarr = plt.subplots(1,2)
axarr[0].imshow(labels_map,vmax=28)
axarr[1].imshow(Y_predictions,vmax=28)
np.save('fig.npy', f)

I can't remake the fig objects, because I no longer have access to the machine.

from a previous stackoverflow post:

fig = numpy.load("fig.npy").item()
ax = fig.gca()
xy_data = ax.get_lines()
print(xy_data[0])

printing fails: "list index out of range"

I need to get the 2d array for both the subplots in order to make a confusion matrix.

Body:
You have no line(s) in your plots; but images. Hence,

import matplotlib.pyplot as plt
import numpy as np

f, axarr = plt.subplots(1,2)
axarr[0].imshow(np.random.randint(0,28, (10,10)),vmax=28)
np.save('fig.npy', f)
plt.close()

fig = np.load("fig.npy").item()
data = fig.axes[0].images[0].get_array()
print(data)


问:
Exception on outlet connections in Xcode 4
I have created a new iPhone project in Xcode 4 and added some files (xib and classes) from an old project which was created in Xcode 3 which works fine.

The project compiles fine with no errors or warnings. However, when I try to run it I get the infamous
"NSUnknownKeyException reason: class is not key value coding-compliant for the key dateOutlet" error.

When I opened the XIB file the connection to the dateOutlet seemed just fine, but I deleted and reconnected anyway just to be safe. Next time I ran it I got the same error but on another outlet which made me think that something went wrong with connections and I just needed to reconnect them again. However, I noticed that sometimes when I reconnected an outlet it would fail on an outlet which I had already ìfixedî. After a lot of fiddling I concluded that reconnecting didnít really fix anything, itís just that when I made changes to the xib the next failing outlet would be picked at random (or so it seems at least).

Has anybody experienced this problem? I have googled a lot but none seem to have encountered this exact behaviour. I have tried to run the project on 3 different machines now with the same result.

答: Ok, I found out the source of the problem. It seems that in the Target for the app the “Main Interface” was set to my MainView which is an instance of UIView. I changed it to MainWindow (generated by Xcode) and all worked fine.</p>


问:
BuildBot: allowed failures
Is it possible to instruct BuildBot that a step is an "allowed failure", that is to NOT mark build as failed even if this particular step fails?

I have found a warnOnFailure parameter for a build step (would prefer "ignoreOnFailure"), but it doesn't seem to be working in my BuildBot (2.1.0, twisted 18.9.0). Even if I set it to True, the overall build is still marked as failed.

I have had success with ShellCommand's decodeRC parameter, but then I lose the indication that the step failed, so it's a sub-optimal solution.

This is how I generate the steps:

```<code>self.build.addStepsAfterCurrentStep([
    steps.ShellCommand(name=stage + ' ' + ('allowed failure' if allowed_failure(stage) else ''),
                       logEnviron=False,
                       warnOnFailure=allowed_failure(stage),  # This one would be desired but doesn't seem to work
                       command=['tox', '-e', stage],
                       env={ 'PYTHONPATH': '.' },
                       decodeRC={0:SUCCESS,1:SUCCESS})  # This one works, but marks the step as SUCCESSFUL, which I don't want
    for stage in self.extract_stages(self.observer.getStdout())
])
</code>```

Please note the inline comments.

Is there a more obvious way of setting this up?

答: You're looking for flunkOnFailure=False (the default being True) in steps.ShellCommand's constructor. See the doc concerning common steps parameters.

Title: BuildBot: allowed failures

Body:
Is it possible to instruct BuildBot that a step is an "allowed failure", that is to NOT mark build as failed even if this particular step fails?

I have found a warnOnFailure parameter for a build step (would prefer "ignoreOnFailure"), but it doesn't seem to be working in my BuildBot (2.1.0, twisted 18.9.0). Even if I set it to True, the overall build is still marked as failed.

I have had success with ShellCommand's decodeRC parameter, but then I lose the indication that the step failed, so it's a sub-optimal solution.

This is how I generate the steps:

self.build.addStepsAfterCurrentStep([
    steps.ShellCommand(name=stage + ' ' + ('allowed failure' if allowed_failure(stage) else ''),
                       logEnviron=False,
                       warnOnFailure=allowed_failure(stage),  # This one would be desired but doesn't seem to work
                       command=['tox', '-e', stage],
                       env={ 'PYTHONPATH': '.' },
                       decodeRC={0:SUCCESS,1:SUCCESS})  # This one works, but marks the step as SUCCESSFUL, which I don't want
    for stage in self.extract_stages(self.observer.getStdout())
])

Please note the inline comments.

Is there a more obvious way of setting this up?


问:
How to include a custom AlertDialog in OnClickListener of ImageView?
I'm trying to put a custom alertDialog when I press an imageView, but the application breaks.

I tried to pass an activity and onClicklistener, but it does not work

My custom AlertDialog is this:

```<code>public vlass viewInfoAjustes{
   public void showDialog(Activity activity){
      final Dialog dialog = new Dialog(activity);
      dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
      dialog.setCancelable(false);
      dialog.setContentView(R.layout.icono_info_ajustes);
      Button ok = dialog.findViewById(R.id.ok);

      ok.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            dialog.dismiss();
         }
      });

      dialog.show();
   }
}
</code>```

and I call it this way:

```<code>    ImageView info = findViewById(R.id.boton_infoServer);
    info.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ViewInfoAjustes iconoInfo = new ViewInfoAjustes();
            iconoInfo.showDialog(this);
        }
    });
</code>```

this is the error:

答: You can do this by passing v.getContext() in your showDialog() method.

Body:
I'm trying to put a custom alertDialog when I press an imageView, but the application breaks.

I tried to pass an activity and onClicklistener, but it does not work

My custom AlertDialog is this:

public vlass viewInfoAjustes{
   public void showDialog(Activity activity){
      final Dialog dialog = new Dialog(activity);
      dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
      dialog.setCancelable(false);
      dialog.setContentView(R.layout.icono_info_ajustes);
      Button ok = dialog.findViewById(R.id.ok);

      ok.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            dialog.dismiss();
         }
      });

      dialog.show();
   }
}

and I call it this way:

    ImageView info = findViewById(R.id.boton_infoServer);
    info.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ViewInfoAjustes iconoInfo = new ViewInfoAjustes();
            iconoInfo.showDialog(this);
        }
    });

this is the error:


问:
Laravel Algolia Search
I was install Laravel Scout with next instruction, but I have a problem :(

1) Used command composer require laravel/scout

2) Added into providers section 'Laravel\Scout\ScoutServiceProvider::class,'

3) Used command php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

4) Added Extends

```<code>Laravel\Scout\Searchable
use Searchable;
</code>```

5) Used command composer require algolia/algoliasearch-client-php

6) Model has code:

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
use DB;

class Product extends Model
{
    use Searchable;
    protected $table = 'products';

    public static function getProductsBySearch($search)
    {
        // Список найденных продуктов
        $searchProducts = Product::search('Test')
            ->get()
            ->all();
        return $searchProducts;
    }

}
</code>```

But Have error:

```<code>AlgoliaSearch requires an applicationID
</code>```

What is Algolia? How will solve it's problem?

答:
You can also use algolia dedicated library for laravel.

Laravel-scout-extended

There is cool feature like php artisan scout:status to see your local DB / and Index in algolia.

If you need more information as an advice you should watch this video :
Scout-Extended

I hope it will help you.

Title: Laravel Algolia Search

Body:
I was install Laravel Scout with next instruction, but I have a problem :(

1) Used command composer require laravel/scout

2) Added into providers section 'Laravel\Scout\ScoutServiceProvider::class,'

3) Used command php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

4) Added Extends

Laravel\Scout\Searchable
use Searchable;

5) Used command composer require algolia/algoliasearch-client-php

6) Model has code:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
use DB;

class Product extends Model
{
    use Searchable;
    protected $table = 'products';

    public static function getProductsBySearch($search)
    {
        // Список найденных продуктов
        $searchProducts = Product::search('Test')
            ->get()
            ->all();
        return $searchProducts;
    }

}

But Have error:

AlgoliaSearch requires an applicationID

What is Algolia? How will solve it's problem?


答:
if you are using Fragment then use

iconoInfo.showDialog(getContext());

if you are using Activity then use :

```<code>iconoInfo.showDialog(YourActivity.this);
</code>```

Title: How to include a custom AlertDialog in OnClickListener of ImageView?

Body:
if you are using Fragment then use

iconoInfo.showDialog(getContext());

if you are using Activity then use :

iconoInfo.showDialog(YourActivity.this);


问:
Qt Creator can't find headers (says: "No such file or directory")
How can I tell Qt Creator 2.4.1 (based on Qt 4.7.4 32-bit) where to look by default for header files?

When I open a C file in Qt Creator and say

```<code>#include <stdio.h>
</code>```

it underlines the line and says

```<code>stdio.h: No such file or directory
</code>```

I would like to tell it to look for headers in a directory of my choice; how do I do this?

Update

I guess I should also ask: Is this even possible? Or must I create an entire project every time I want to edit a standalone C++ file?

答:
```<code>add INCLUDEPATH to "project.pro" file

example for raspberry pi qt projects:
# Qt Creator can't find headers (says: “No such file or directory”)
# add compile includes
INCLUDEPATH += /home/user/raspi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/arm-linux-gnueabihf/libc/usr/include/ \
               /home/user/raspi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/arm-linux-gnueabihf/libc/usr/include/arm-linux-gnueabihf/
# pi rootfs includes
INCLUDEPATH += /home/user/raspi/sysroot/usr/include/
</code>```

Body:
How can I tell Qt Creator 2.4.1 (based on Qt 4.7.4 32-bit) where to look by default for header files?

When I open a C file in Qt Creator and say

#include <stdio.h>

it underlines the line and says

stdio.h: No such file or directory

I would like to tell it to look for headers in a directory of my choice; how do I do this?

Update

I guess I should also ask: Is this even possible? Or must I create an entire project every time I want to edit a standalone C++ file?


问:
SQL query to get all records with certain parent IDs and two additional conditions
So I am working on a table which stores different bus routes. Each route can go through different locations (StationId) and the order in which it goes through each of them is determined by the column StationOrder.

The table looks like this:

```<code>RouteId | StationId | StationOrder |
------------------------------------
1       | 1         | 2
1       | 2         | 3
1       | 4         | 1
3       | 1         | 1
3       | 2         | 3
3       | 3         | 2
</code>```

What I know is the routes that I'm interested in. In this case those are routes with id 1 and 3. I also know which is the starting Station, StationId 1 what I need to select is all StationIds which have StationOrder number higher than the StationOrder number for StationId 1.

I would show what I've tried so far but basically, since the table contains more routes than just two those I know how to select the desired routes:

```<code>SELECT RS.StationId FROM RouteStations AS RS
WHERE RS.RouteId IN (1,3)
</code>```

But when it comes to the second part where I need to select all StationIds with StationOrder number higher than the StationOrder number for StationId 1 for each route my SQL knowledge comes short.

答:
what I need to select is all StationIds which have StationOrder number
  higher than the StationOrder number for StationId 1

Put these conditions in the WHERE clause:

```<code>SELECT RS.StationId
FROM RouteStations AS RS
WHERE
  RS.RouteId IN (1,3)
  AND
  RS.StationOrder > (
    select StationOrder
    FROM RouteStations
    WHERE RouteId = RS.RouteId AND StationId = 1
  )
</code>```

If you don't want duplicates in the results, use:

```<code>SELECT DISTINCT RS.StationId
</code>```

Body:
So I am working on a table which stores different bus routes. Each route can go through different locations (StationId) and the order in which it goes through each of them is determined by the column StationOrder.

The table looks like this:

RouteId | StationId | StationOrder |
------------------------------------
1       | 1         | 2
1       | 2         | 3
1       | 4         | 1
3       | 1         | 1
3       | 2         | 3
3       | 3         | 2

What I know is the routes that I'm interested in. In this case those are routes with id 1 and 3. I also know which is the starting Station, StationId 1 what I need to select is all StationIds which have StationOrder number higher than the StationOrder number for StationId 1.

I would show what I've tried so far but basically, since the table contains more routes than just two those I know how to select the desired routes:

SELECT RS.StationId FROM RouteStations AS RS
WHERE RS.RouteId IN (1,3)

But when it comes to the second part where I need to select all StationIds with StationOrder number higher than the StationOrder number for StationId 1 for each route my SQL knowledge comes short.

Body:
what I need to select is all StationIds which have StationOrder number
  higher than the StationOrder number for StationId 1

Put these conditions in the WHERE clause:

SELECT RS.StationId
FROM RouteStations AS RS
WHERE
  RS.RouteId IN (1,3)
  AND
  RS.StationOrder > (
    select StationOrder
    FROM RouteStations
    WHERE RouteId = RS.RouteId AND StationId = 1
  )

If you don't want duplicates in the results, use:

SELECT DISTINCT RS.StationId


问:
Oracle - How to get date from YEAR, WEEKNUM and WEEKDAY?
I need to find the date of particular year, week, and weekday in oracle.
Is there a built-in function for this in oracle? or how can I achieve this?

Ex: If Year=2019, Week=22, Day=2(Tuesday), Then date should be '28-05-2019'.

答:
I think there is no built-in function for this, you will have to build one on your own.
below is one of the solutions you can make use of.

```<code>WITH FUNCTION getDate(p_year IN NUMBER, p_weeks IN NUMBER, p_day in NUMBER) RETURN DATE
IS
  v_tmp date;
  v_day number;
BEGIN
  v_tmp := to_date('01/01/'||to_char(p_year),'dd/mm/yyyy');
  v_day := to_char(v_tmp,'D');

  RETURN v_tmp+(p_weeks-1)*7+p_day-(v_day)+1;
END;
SELECT getDate(2019,22,2)
FROM DUAL;
/
</code>```

As per my NLS_TERRITORY settings, Oracle numbers the day of the week starting from Sunday, but from your example, you seem to be considering Monday as day 1 of the week. So, the same adjustment is made to the function to return the expected result.

Also, please note that with clause function is a new feature of Oracle 12c, if you happen to use an older version of Oracle, you will have to create the stored function before calling it.

Body:
I think there is no built-in function for this, you will have to build one on your own.
below is one of the solutions you can make use of.

WITH FUNCTION getDate(p_year IN NUMBER, p_weeks IN NUMBER, p_day in NUMBER) RETURN DATE
IS
  v_tmp date;
  v_day number;
BEGIN
  v_tmp := to_date('01/01/'||to_char(p_year),'dd/mm/yyyy');
  v_day := to_char(v_tmp,'D');

  RETURN v_tmp+(p_weeks-1)*7+p_day-(v_day)+1;
END;
SELECT getDate(2019,22,2)
FROM DUAL;
/

As per my NLS_TERRITORY settings, Oracle numbers the day of the week starting from Sunday, but from your example, you seem to be considering Monday as day 1 of the week. So, the same adjustment is made to the function to return the expected result.

Also, please note that with clause function is a new feature of Oracle 12c, if you happen to use an older version of Oracle, you will have to create the stored function before calling it.


问:
How can I customise the language of the JSON response in Rails?
I have a controller that has a mobile client. The response is currently in English; however, I'm questioning if there is a way to customise the language of the response.

For example:

English: {   "success": false,   "message": "Error with your login or
password" }

Spanish:{   "success": false,   "message": "Error con tu usuario o
contraseña" }

And, of course, the content of the "message" is going to be located in the language configuration file that Rails has, as follows.

en.yml

or

es.yml

The following is the function from where the response is generated.

```<code>def invalid_login_attempt
    warden.custom_failure!
    render :json => { :success => false, :message=> "Error with your login or password" }, :status => 401
  end
</code>```

答: Setting up internationalization (I18n) for Rails should be pretty much the same for HTML and JSON responses. Have a look at the official tutorial.</p>

Body:
I have a controller that has a mobile client. The response is currently in English; however, I'm questioning if there is a way to customise the language of the response.

For example:

English: {   "success": false,   "message": "Error with your login or
password" }

Spanish:{   "success": false,   "message": "Error con tu usuario o
contraseña" }

And, of course, the content of the "message" is going to be located in the language configuration file that Rails has, as follows.

en.yml

or

es.yml

The following is the function from where the response is generated.

def invalid_login_attempt
    warden.custom_failure!
    render :json => { :success => false, :message=> "Error with your login or password" }, :status => 401
  end


答:
```<code>max([option['type'] for option in programmes_by_type], key=len)
</code>```

Title: The list with most elements

Body:
I have a list with dictionary as elements. Each dictionary has an entry called type. The type field represents a list. What is the simplest/pythonic way of obtaining the list with the most elements?

programmes_by_type = []
programmes_by_type.append({'type' : [1, 2, 3]})
programmes_by_type.append({'type' : [2, 5]})
programmes_by_type.append({'type' : [3]})
programmes_by_type.append({'type' : [11, 2, 6, 7]})

Given the previous example it should return the [11, 2, 6, 7] list.


问:
How to persist bloc instance in widget tree
I'm using an InheritedWidget to expose a bloc class to child components. However, every time the widget tree gets recreated, a new instance of the bloc class is instantiated. As I'm using BehaviourSubject classes to store the latest values of some textfields, I'm loosing the current values with every recreation. How could this be solved, i.e. the bloc class should only be instantiated once.</p>

答:
It depends on how your provider were made, if it's an a extension of StatefulWidget with an a InheritedWidget.

If it's only extends from a InheritedWigdet, you'll miss the dispose method because it doesn't extends from StatefulBuilder, but, will never instantiate again, and the dispose method will be when you'll close your application. Check this example:

```<code>class Provider extends InheritedWidget {
  Provider({Key key, Widget child}) : super(key: key, child: child);

  final AppBloc bloc = AppBloc();

  static AppBloc of(BuildContext context) =>
      (context.inheritFromWidgetOfExactType(Provider) as Provider).bloc;

  @override
  bool updateShouldNotify(Provider oldWidget) => true;
}
</code>```

This AppBloc is a component that has all my applcation's blocs.

But, if your provider extends an a StatefulWidget with a InheritedWidget, you can pass your bloc as a constructor parameter in the class you want, and this class should be Stateful too, so you can pass in the initState and will be rebuilted only when you access it again.

Body:
It depends on how your provider were made, if it's an a extension of StatefulWidget with an a InheritedWidget.

If it's only extends from a InheritedWigdet, you'll miss the dispose method because it doesn't extends from StatefulBuilder, but, will never instantiate again, and the dispose method will be when you'll close your application. Check this example:

class Provider extends InheritedWidget {
  Provider({Key key, Widget child}) : super(key: key, child: child);

  final AppBloc bloc = AppBloc();

  static AppBloc of(BuildContext context) =>
      (context.inheritFromWidgetOfExactType(Provider) as Provider).bloc;

  @override
  bool updateShouldNotify(Provider oldWidget) => true;
}

This AppBloc is a component that has all my applcation's blocs.

But, if your provider extends an a StatefulWidget with a InheritedWidget, you can pass your bloc as a constructor parameter in the class you want, and this class should be Stateful too, so you can pass in the initState and will be rebuilted only when you access it again.


问:
why is nvm (for windows) not working and whenever it runs it gives an error message?
nvm (for windows https://github.com/coreybutler/nvm-windows)

I have downloaded the nvm-setup and installed it, but whenever it runs it gives an error message.

I've tried to reinstall the nvm, reset the PATH environment variable and install version 1.1.6, and non of it seems to be working.

NVM_HOME points to my nvm file correctly and it's in the PATH.

```<code>C:\Users>nvm --version

Running version 1.1.7.

C:\Users>nvm list

12.3.1

C:\Users>nvm use 12.3.1

exit status 1: 'D:\Program' ���O�����Υ~���R�O�B�i���檺�{���Χ妸�ɡC
</code>```

答:
This happend when you install nvm in a directory that have spaces in the name, for example: C:\Program Files

Change the install directory for nvm and it solved.

Body:
nvm (for windows https://github.com/coreybutler/nvm-windows)

I have downloaded the nvm-setup and installed it, but whenever it runs it gives an error message.

I've tried to reinstall the nvm, reset the PATH environment variable and install version 1.1.6, and non of it seems to be working.

NVM_HOME points to my nvm file correctly and it's in the PATH.

C:\Users>nvm --version

Running version 1.1.7.

C:\Users>nvm list

12.3.1

C:\Users>nvm use 12.3.1

exit status 1: 'D:\Program' ���O�����Υ~���R�O�B�i���檺�{���Χ妸�ɡC


问:
Azure App Service Editor (Monaco) stoped working / no access http error 500.1001
i cant access anymore to azure App Service Editor (monaco) , every thing was ok , and than just stopped. The web site is working, and i can access using visual studio but not online

答: i had to stop the service and restart it , and it went to work again , still have no explanantion why it went wrong </p>


问:
VBA to insert TOC that can be used by many users
I am looking to setup a mail merge (Directory merge to use page breaks) template and then have users use a macro to generate a Table of Contents once the file has been created.

I tried recording a macro to go to the first space in the document, add a section break and then insert a TOC and change the numbering so that it does not include the first page, but I see that it uses my username when it loads the building blocks template.

I realise it is messy since it is a recorded and I have found some cleaner code, but then it does not have the header for the TOC.

Is there a way that I can have this work for any user that uses the code?

```<code>Sub Macro1()
'
' Macro1 Macro
'
 Set myTemplate = ActiveDocument.AttachedTemplate
    Selection.HomeKey Unit:=wdStory
    Selection.InsertBreak Type:=wdSectionBreakNextPage
    Selection.HomeKey Unit:=wdStory
    Application.Templates( _
        "C:\Users\myUsername\AppData\Roaming\Microsoft\Document Building Blocks\1033\16\Built-In Building Blocks.dotx" _
        ).BuildingBlockEntries("Automatic Table 1").Insert Where:=Selection.Range _
        , RichText:=True
    If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
        ActiveWindow.Panes(2).Close
    End If
    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
        ActivePane.View.Type = wdOutlineView Then
        ActiveWindow.ActivePane.View.Type = wdPrintView
    End If
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub
</code>```

Tried the following code, but it still uses mypath which has to be the path of the current user. Is the rest of the path the same for each user? Then perhaps I can just somehow extract the username of the current user and insert it into myUsername.

```<code>Sub ToCAndTitle()
With ActiveDocument
  'Insert a Section break before existing content
  .Range(0, 0).InsertBreak Type:=wdSectionBreakNextPage
  .TablesOfContents.Add Range:=.Range(0, 0), RightAlignPageNumbers:=True, _
     UseHeadingStyles:=True, IncludePageNumbers:=True, UseHyperlinks:=True, _
     HidePageNumbersInWeb:=True, UseOutlineLevels:=False
  'Insert a page break before existing content
  .Range(0, 0).InsertBreak Type:=wdPageBreak
  Application.Templates(mypath).BuildingBlockEntries("BuildingBlockName").Insert Where:=.Range(0, 0), RichText:=True
End With
End Sub
</code>```

答:
Since you're creating a template for distribution, store the Building Block in that template rather than in your "private" building blocks template. Then it will be available to anyone using the template.

Create the content to be saved as a building block in the template or a document created from the template. Select this content.

Insert/Quick Parts/Save selection to Quick Part Gallery

Set the name, the gallery and category under which it should be stored, as usual...

... Select the template that will be distributed from Save in

Change the code in the question to:

```<code>Sub Macro1()
'
' Macro1 Macro
'
 Set myTemplate = ActiveDocument.AttachedTemplate
    Selection.HomeKey Unit:=wdStory
    Selection.InsertBreak Type:=wdSectionBreakNextPage
    Selection.HomeKey Unit:=wdStory
    myTemplate.BuildingBlockEntries("Automatic Table 1").Insert _
        Where:=Selection.Range _
        , RichText:=True
   'Note: the macro probably does not need the rest of the lines of code
   'that were generated by the macro recorder - comment them out or delete them
   If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
        ActiveWindow.Panes(2).Close
    End If
    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
        ActivePane.View.Type = wdOutlineView Then
        ActiveWindow.ActivePane.View.Type = wdPrintView
    End If
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub
</code>```

Body:
I am looking to setup a mail merge (Directory merge to use page breaks) template and then have users use a macro to generate a Table of Contents once the file has been created.

I tried recording a macro to go to the first space in the document, add a section break and then insert a TOC and change the numbering so that it does not include the first page, but I see that it uses my username when it loads the building blocks template.

I realise it is messy since it is a recorded and I have found some cleaner code, but then it does not have the header for the TOC.

Is there a way that I can have this work for any user that uses the code?

Sub Macro1()
'
' Macro1 Macro
'
 Set myTemplate = ActiveDocument.AttachedTemplate
    Selection.HomeKey Unit:=wdStory
    Selection.InsertBreak Type:=wdSectionBreakNextPage
    Selection.HomeKey Unit:=wdStory
    Application.Templates( _
        "C:\Users\myUsername\AppData\Roaming\Microsoft\Document Building Blocks\1033\16\Built-In Building Blocks.dotx" _
        ).BuildingBlockEntries("Automatic Table 1").Insert Where:=Selection.Range _
        , RichText:=True
    If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
        ActiveWindow.Panes(2).Close
    End If
    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
        ActivePane.View.Type = wdOutlineView Then
        ActiveWindow.ActivePane.View.Type = wdPrintView
    End If
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub

Tried the following code, but it still uses mypath which has to be the path of the current user. Is the rest of the path the same for each user? Then perhaps I can just somehow extract the username of the current user and insert it into myUsername.

Sub ToCAndTitle()
With ActiveDocument
  'Insert a Section break before existing content
  .Range(0, 0).InsertBreak Type:=wdSectionBreakNextPage
  .TablesOfContents.Add Range:=.Range(0, 0), RightAlignPageNumbers:=True, _
     UseHeadingStyles:=True, IncludePageNumbers:=True, UseHyperlinks:=True, _
     HidePageNumbersInWeb:=True, UseOutlineLevels:=False
  'Insert a page break before existing content
  .Range(0, 0).InsertBreak Type:=wdPageBreak
  Application.Templates(mypath).BuildingBlockEntries("BuildingBlockName").Insert Where:=.Range(0, 0), RichText:=True
End With
End Sub

Body:
Since you're creating a template for distribution, store the Building Block in that template rather than in your "private" building blocks template. Then it will be available to anyone using the template.

Create the content to be saved as a building block in the template or a document created from the template. Select this content.

Insert/Quick Parts/Save selection to Quick Part Gallery

Set the name, the gallery and category under which it should be stored, as usual...

... Select the template that will be distributed from Save in

Change the code in the question to:

Sub Macro1()
'
' Macro1 Macro
'
 Set myTemplate = ActiveDocument.AttachedTemplate
    Selection.HomeKey Unit:=wdStory
    Selection.InsertBreak Type:=wdSectionBreakNextPage
    Selection.HomeKey Unit:=wdStory
    myTemplate.BuildingBlockEntries("Automatic Table 1").Insert _
        Where:=Selection.Range _
        , RichText:=True
   'Note: the macro probably does not need the rest of the lines of code
   'that were generated by the macro recorder - comment them out or delete them
   If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
        ActiveWindow.Panes(2).Close
    End If
    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
        ActivePane.View.Type = wdOutlineView Then
        ActiveWindow.ActivePane.View.Type = wdPrintView
    End If
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub


问:
Scala.Byte vs java.lang.Byte -Which one is recomended to use?
I was wondering which of the two possibilities is preferred. In my opinion they do more or less the same.
What are the reasons why there are two implementation?
Are there differences in the performance or functionality?</p>

答: Use scala.Byte in most cases, because it corresponds to both byte and java.lang.Byte in Java terms and you usually want byte. The compiler will use byte for scala.Byte where it's possible/makes sense.


问:
Memory consumption issue in Quartz.net core
I am using Quartz.NET 3.0.7 in my application for some scheduled tasks but when i start scheduler it will increasing memory when scheduler run.i also checked with simple schedule task which print some list of string on console the same issue is happening in this also.i can not understand what is actual issue.my observation is IJob object is released after job work done.I have no idea other than that.

I am creating Jobs Dynamically by passing JobType

```<code> private IJobDetail GetJobDetailForType<TInput>(string jobKey, string jobGroup) where TInput : IJob
    {
      IJobDetail jobDetail = JobBuilder.Create<TInput>()
                                       .WithIdentity(jobKey, jobGroup)
                                       .Build();
      return jobDetail;
    }
</code>```

And initialize schedule jobs in this function

```<code>  private void InitializeSchedulerJob(ScheduleJob scheduleJob)
    {

        IJobDetail jobDetail;
        ITrigger trigger = this.GetTrigger(scheduleJob.Code.ToString(), tenantCode, scheduleJob.CornSchedule);

        if (scheduleJob.Code == (int)EnumHelper.Scheduler.Job.EmailJob)
        {
          this.logger.LogDebug($"EmailJob");
          jobDetail = this.GetJobDetailForType<EmailJob>(scheduleJob.Code.ToString(), tenantCode);
        }

        this.scheduler.ScheduleJob(jobDetail, trigger);
    }
</code>```

Email Job Code

```<code> public class EmailJob : IJob
  {
    private IServiceProvider serviceProvider;

    public EmailJob(IServiceProvider serviceProvider)
    {
      this.serviceProvider = serviceProvider;
    }

    public async Task Execute(IJobExecutionContext context)
    {
      if (this.serviceProvider != null)
      {
          JobKey jobKey = context.JobDetail.Key;
          IEmailScheduleSendService emailScheduleSendServiceNew = this.serviceProvider.GetRequiredService<IEmailScheduleSendService>();
          ILogger<EmailJob> logger = this.serviceProvider.GetRequiredService<ILogger<EmailJob>>();
          logger.LogDebug($"FROM EXECUTE METHOD | {jobKey.Name} | {jobKey.Group} | START");
          await emailScheduleSendServiceNew.EmailScheduleSendAsync(context);
          logger.LogDebug($"FROM EXECUTE METHOD | {jobKey.Name} | {jobKey.Group} | END");
        }
      }
    }
</code>```

答:
You may want to start running some performance counters to monitor CPU usage and memory stats and figure out what's going on.

If that doesn't lead you to any obvious answers, it's time to start profiling.

JetBrains dotTrace  (Not free, 30 day trial)

Microsoft's CLR Profiler

Body:
I am using Quartz.NET 3.0.7 in my application for some scheduled tasks but when i start scheduler it will increasing memory when scheduler run.i also checked with simple schedule task which print some list of string on console the same issue is happening in this also.i can not understand what is actual issue.my observation is IJob object is released after job work done.I have no idea other than that.

I am creating Jobs Dynamically by passing JobType

 private IJobDetail GetJobDetailForType<TInput>(string jobKey, string jobGroup) where TInput : IJob
    {
      IJobDetail jobDetail = JobBuilder.Create<TInput>()
                                       .WithIdentity(jobKey, jobGroup)
                                       .Build();
      return jobDetail;
    }

And initialize schedule jobs in this function

  private void InitializeSchedulerJob(ScheduleJob scheduleJob)
    {

        IJobDetail jobDetail;
        ITrigger trigger = this.GetTrigger(scheduleJob.Code.ToString(), tenantCode, scheduleJob.CornSchedule);

        if (scheduleJob.Code == (int)EnumHelper.Scheduler.Job.EmailJob)
        {
          this.logger.LogDebug($"EmailJob");
          jobDetail = this.GetJobDetailForType<EmailJob>(scheduleJob.Code.ToString(), tenantCode);
        }

        this.scheduler.ScheduleJob(jobDetail, trigger);
    }

Email Job Code

 public class EmailJob : IJob
  {
    private IServiceProvider serviceProvider;

    public EmailJob(IServiceProvider serviceProvider)
    {
      this.serviceProvider = serviceProvider;
    }

    public async Task Execute(IJobExecutionContext context)
    {
      if (this.serviceProvider != null)
      {
          JobKey jobKey = context.JobDetail.Key;
          IEmailScheduleSendService emailScheduleSendServiceNew = this.serviceProvider.GetRequiredService<IEmailScheduleSendService>();
          ILogger<EmailJob> logger = this.serviceProvider.GetRequiredService<ILogger<EmailJob>>();
          logger.LogDebug($"FROM EXECUTE METHOD | {jobKey.Name} | {jobKey.Group} | START");
          await emailScheduleSendServiceNew.EmailScheduleSendAsync(context);
          logger.LogDebug($"FROM EXECUTE METHOD | {jobKey.Name} | {jobKey.Group} | END");
        }
      }
    }


问:
0xDEADBEEF equivalent for 64-bit development?
For C++ development for 32-bit systems (be it Linux, Mac OS or
Windows, PowerPC or x86) I have initialised pointers that
would otherwise be undefined (e.g. they can not immediately
get a proper value) like so:

```<code>int *pInt = reinterpret_cast<int *>(0xDEADBEEF);
</code>```

(To save typing and being DRY the right-hand side would normally
be in a constant, e.g. BAD_PTR.)

If pInt is dereferenced before it gets a proper value then
it will crash immediately on most systems (instead of
crashing much later when some memory is overwritten or going
into a very long loop).

Of course the behavior is dependent on the underlying
hardware (getting a 4 byte integer from the odd
address 0xDEADBEEF from a user process may be perfectly
valid), but the crashing has been 100% reliable for all the
systems I have developed for so far (Mac OS 68xxx, Mac OS
PowerPC, Linux Redhat Pentium, Windows GUI Pentium, Windows
console Pentium). For instance on PowerPC it is illegal (bus
fault) to fetch a 4 byte integer from an odd address.

What is a good value for this on 64-bit systems?

答:
As the system I worked on basically runs on x86_64 platform, the value I use is:

```<code>0xDEADBEEFDEADBEEF
</code>```

Reasons are:

On x86_64 platform, only the low-order 48 bits are used for virtual memory address in current implementation, meaning any value > 2^48 should work: https://en.wikipedia.org/wiki/X86-64

As 0xDEADBEEF is already very well known for this purpose in 32bit, 0xDEADBEEFDEADBEEF in 64bit is just more 'backward compatible'

Body:
For C++ development for 32-bit systems (be it Linux, Mac OS or
Windows, PowerPC or x86) I have initialised pointers that
would otherwise be undefined (e.g. they can not immediately
get a proper value) like so:

int *pInt = reinterpret_cast<int *>(0xDEADBEEF);

(To save typing and being DRY the right-hand side would normally
be in a constant, e.g. BAD_PTR.)

If pInt is dereferenced before it gets a proper value then
it will crash immediately on most systems (instead of
crashing much later when some memory is overwritten or going
into a very long loop).

Of course the behavior is dependent on the underlying
hardware (getting a 4 byte integer from the odd
address 0xDEADBEEF from a user process may be perfectly
valid), but the crashing has been 100% reliable for all the
systems I have developed for so far (Mac OS 68xxx, Mac OS
PowerPC, Linux Redhat Pentium, Windows GUI Pentium, Windows
console Pentium). For instance on PowerPC it is illegal (bus
fault) to fetch a 4 byte integer from an odd address.

What is a good value for this on 64-bit systems?

Body:
As the system I worked on basically runs on x86_64 platform, the value I use is:

0xDEADBEEFDEADBEEF

Reasons are:

On x86_64 platform, only the low-order 48 bits are used for virtual memory address in current implementation, meaning any value > 2^48 should work: https://en.wikipedia.org/wiki/X86-64

As 0xDEADBEEF is already very well known for this purpose in 32bit, 0xDEADBEEFDEADBEEF in 64bit is just more 'backward compatible'


问:
Finding out the interfaces/protocols a Clojure Record/Type implements?
Is there any way I can dynamically find out which interfaces or protocols a Clojure Record or Type implements?

For example I would like to do:

```<code>(show-protocols some-record-instance)
</code>```

答: Look to following article - it answers to your question</p>

Body:
Is there any way I can dynamically find out which interfaces or protocols a Clojure Record or Type implements?

For example I would like to do:

(show-protocols some-record-instance)


答: If you are using a StatefulWidget then you can instantiate the bloc in the initState method.</p>

Title: How to persist bloc instance in widget tree

Body: I'm using an InheritedWidget to expose a bloc class to child components. However, every time the widget tree gets recreated, a new instance of the bloc class is instantiated. As I'm using BehaviourSubject classes to store the latest values of some textfields, I'm loosing the current values with every recreation. How could this be solved, i.e. the bloc class should only be instantiated once.


问:
VowpalWabbit incorrect predictions. How to properly prepare learning data?
I'm trying to learn VW to predict houses prices based on number of bedrooms, bathrooms, area and other features. My training data example line are:

```<code>68000 '51-OMAHA-CT| city=SACRAMENTO zip=95823 state=CA beds:3 baths:1 sq__ft:1167 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.478902 longitude=-121.431028
56333 '3526-HIGH-ST| city=SACRAMENTO zip=95838 state=CA beds:2 baths:1 sq__ft:836 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.631913 longitude=-121.434879
68790 '2796-BRANCH-ST| city=SACRAMENTO zip=95815 state=CA beds:2 baths:1 sq__ft:796 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.618305 longitude=-121.443839
</code>```

PRICE STREET | ...
In total about 500 record.
My test data are (about 500 records as well):

```<code>'51-OMAHA-CT| city=SACRAMENTO zip=95823 state=CA beds:3 baths:1 sq__ft:1167 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.478902 longitude=-121.431028
'3526-HIGH-ST| city=SACRAMENTO zip=95838 state=CA beds:2 baths:1 sq__ft:836 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.631913 longitude=-121.434879
'2796-BRANCH-ST| city=SACRAMENTO zip=95815 state=CA beds:2 baths:1 sq__ft:796 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.618305 longitude=-121.443839
</code>```

Predicting gives these values:

```<code>4819.900391 51-OMAHA-CT
4609.826172 3526-HIGH-ST
4537.140137 2796-BRANCH-ST
</code>```

These aren't correct predictions. I am not sure if there's a problem with my training data? I'm still confused about | char and placing features.

答:
When you construct a feature as city=SACRAMENTO, VW is interpreting that as a string feature with name city=SACRAMENTO and assigning it an implicit value of 1.0. city=SACRAMENTO is hashed and that forms the index for the feature.

When you construct a feature as beds:2, VW is interpreting it as a feature with name beds and a feature value of 2.0. beds is hashed and forms the index.

So think of features in the form __=__ as enums, or values from a discrete set. When you have continuous features then a float value should be used.

Using the __=__ format seems fine for city names, but when you use this same format for latitude and longitude then it is very unlikely that another example is going to share the same exact lat/lng string be able to use that feature in the prediction. It seems to me that lat/lng should be a float based feautre.

For the sale_date you have a similar problem. This is perhaps more of a feature engineering thing, but perhaps you want to split this feature apart into year, day of the week, month, etc.

Body:
I'm trying to learn VW to predict houses prices based on number of bedrooms, bathrooms, area and other features. My training data example line are:

68000 '51-OMAHA-CT| city=SACRAMENTO zip=95823 state=CA beds:3 baths:1 sq__ft:1167 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.478902 longitude=-121.431028
56333 '3526-HIGH-ST| city=SACRAMENTO zip=95838 state=CA beds:2 baths:1 sq__ft:836 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.631913 longitude=-121.434879
68790 '2796-BRANCH-ST| city=SACRAMENTO zip=95815 state=CA beds:2 baths:1 sq__ft:796 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.618305 longitude=-121.443839

PRICE STREET | ...
In total about 500 record.
My test data are (about 500 records as well):

'51-OMAHA-CT| city=SACRAMENTO zip=95823 state=CA beds:3 baths:1 sq__ft:1167 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.478902 longitude=-121.431028
'3526-HIGH-ST| city=SACRAMENTO zip=95838 state=CA beds:2 baths:1 sq__ft:836 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.631913 longitude=-121.434879
'2796-BRANCH-ST| city=SACRAMENTO zip=95815 state=CA beds:2 baths:1 sq__ft:796 type=Residential sale_date=Wed-May-21-00-00-00-EDT-2008 latitude=38.618305 longitude=-121.443839

Predicting gives these values:

4819.900391 51-OMAHA-CT
4609.826172 3526-HIGH-ST
4537.140137 2796-BRANCH-ST

These aren't correct predictions. I am not sure if there's a problem with my training data? I'm still confused about | char and placing features.


问:
Reusing types across multiple services and .net versions
I have Services (Service1, Service2, ...) all which reference a Common.dll all of which are in .Net 4.0, and I am having trouble reusing the types in the consumer of the service.

Common.dll has

```<code>Identifier {
    int Id;
    string Type;
}
</code>```

Each Service implements

```<code>byte[] Get(Common.Identifier);
string Test();
</code>```

The consumer of the service (.Net3.5) generates code in reference.cs

```<code>class Service1 {
    byte[] Get(Service1.Identifier);
    string Test();
}

class Service2 {
    byte[] Get(Service2.Identifier);
    string Test();
}
</code>```

I tied them together by creating an Interface
Adding the interface to partial classes, but can only get it to work for the Test() call

```<code>public interface IService {
    //byte[] Get(Service2.Identifier);
    string Test();
}

public partial class Service1 : IService;
public partial class Service2 : IService;
</code>```

This way I can use the services interchangably.
I plan on creating many more to use as basically plugins to integrate to different systems

```<code>IService GetService(string provider) {
    switch (provider) {
        case "Service1":
            return (IService)new Service1();

        case "Service2":
            return (IService)new Service2();
    }
}

GetService.Test() //works perfectly.
</code>```

My problem is how do I define, decorate "Identifier" in such a way that will allow me to use the Get(?? Identifier) without writing a bunch of code.

The only way I can think of right now is to create an interface IIdentifier, and then add to the partial classes

```<code>public partial class Service1 : IService {
    byte[] Get(IIdentifier id) {
        return this.Get(new Service1.Identifier() { Id = id.Id, Type = id.Type});
}
</code>```

but there are a lot of calls and I don't want to have to wrap them all. I'm sure I'm just missing something simple, thanks for any help that can be provided.

答:
I was approaching this from the wrong side, and the way I was trying to do it wouldn't work as Alexei pointed out.

I managed to get everything to work and reuse the classes in the common.dll by compiling it for .net 3.5 instead of 4.0.

.Net 4.0 is backwards compatible with 3.5 so I was able to reference the 3.5 common.dll from my services which allowed my 3.5 code to reference common.dll and thus reuse the types.

Body:
I have Services (Service1, Service2, ...) all which reference a Common.dll all of which are in .Net 4.0, and I am having trouble reusing the types in the consumer of the service.

Common.dll has

Identifier {
    int Id;
    string Type;
}

Each Service implements

byte[] Get(Common.Identifier);
string Test();

The consumer of the service (.Net3.5) generates code in reference.cs

class Service1 {
    byte[] Get(Service1.Identifier);
    string Test();
}

class Service2 {
    byte[] Get(Service2.Identifier);
    string Test();
}

I tied them together by creating an Interface
Adding the interface to partial classes, but can only get it to work for the Test() call

public interface IService {
    //byte[] Get(Service2.Identifier);
    string Test();
}

public partial class Service1 : IService;
public partial class Service2 : IService;

This way I can use the services interchangably.
I plan on creating many more to use as basically plugins to integrate to different systems

IService GetService(string provider) {
    switch (provider) {
        case "Service1":
            return (IService)new Service1();

        case "Service2":
            return (IService)new Service2();
    }
}

GetService.Test() //works perfectly.

My problem is how do I define, decorate "Identifier" in such a way that will allow me to use the Get(?? Identifier) without writing a bunch of code.

The only way I can think of right now is to create an interface IIdentifier, and then add to the partial classes

public partial class Service1 : IService {
    byte[] Get(IIdentifier id) {
        return this.Get(new Service1.Identifier() { Id = id.Id, Type = id.Type});
}

but there are a lot of calls and I don't want to have to wrap them all. I'm sure I'm just missing something simple, thanks for any help that can be provided.


问:
How to search between messages between two time ranges?
I have a channel in slack, to which a CI tool sends notification. The CI tool sends notification for failure for every operation and there is no way to filter it out. But I know that important notifications come from 12 AM to 2 AM. Is there a way that I can apply a filter daily on that channel between two time intervals ?</p>

答:
Yes. you can call the API method conversations.history, which will return messages from a channel. By settings the parameters oldest and latest accordingly you will only get messages from a specified timeframe.

Note that those parameters are provided as absolute timestamps (e.g. 1234567890.123456), so you need to calculate them for the current day.


问:
Does Python Have a Wildcard Similar to PowerShell?
I'm currently working on an email inbox automation project, and I'm trying to use a wildcard to find certain email subjects. The emails sometimes have randomly generated ticket numbers, so I need to compensate for that. Here is how I'd write it in PowerShell.

```<code>if($email.'Subject' -like 'Test Number:*') {...}
</code>```

This would trigger for each email with the subject line Test Number:, regardless of the randomly generated number following.

From what I'm seeing, Python does not simply have a wildcard like PowerShell has -like and *. That or I'm dumb and can't find it. The only thing I'm seeing involves installing modules to get a wildcard to work. Does Python have a built in wildcard?

答:
You can use startswith in your case

```<code>email_subjects = ['Test:1', 'Test:25', 'not_valid!']
for email_subject in email_subjects:
    if email_subject.startswith('Test:'):
        print('valid email subjet', email_subject)
    else:
        print('invalid email subjet', email_subject)
</code>```

For the note :

substring* is equivalent to string.startsWith(substring)

*substring is equivalent to string.endswith(substring)

*substring* is equivalent to substring in string

If you have some more complex patterns, I suggest you to use the re module. For instance you want to match every: 'Test:X with X a number between 1 and 25

```<code>import re

email_subjects = ['Test:1', 'Test:25', 'not_valid!', 'Test:52']
for email_subject in email_subjects:
    if re.search(''^Test:([0-9]|1[0-9]|2[0-5])$'', email_subject): # Compiles to a regular expression and looks for it in email_subject
        print('valid email subjet', email_subject)
    else:
        print('invalid email subjet', email_subject)
</code>```

Regex breakdown:

^ Starting character match

Test: Your string you want to match

([0-9]|1[0-9]|2[0-5]): your range, which means: a number from 0 to 9, or a 1 and a number from 0 to 9 (which means between 10 and 19) or 2 and a number from 0 to 5 (which means between 20 and 25)

$ Ending character

Body:
I'm currently working on an email inbox automation project, and I'm trying to use a wildcard to find certain email subjects. The emails sometimes have randomly generated ticket numbers, so I need to compensate for that. Here is how I'd write it in PowerShell.

if($email.'Subject' -like 'Test Number:*') {...}

This would trigger for each email with the subject line Test Number:, regardless of the randomly generated number following.

From what I'm seeing, Python does not simply have a wildcard like PowerShell has -like and *. That or I'm dumb and can't find it. The only thing I'm seeing involves installing modules to get a wildcard to work. Does Python have a built in wildcard?

Body:
You can use startswith in your case

email_subjects = ['Test:1', 'Test:25', 'not_valid!']
for email_subject in email_subjects:
    if email_subject.startswith('Test:'):
        print('valid email subjet', email_subject)
    else:
        print('invalid email subjet', email_subject)

For the note :

substring* is equivalent to string.startsWith(substring)

*substring is equivalent to string.endswith(substring)

*substring* is equivalent to substring in string

If you have some more complex patterns, I suggest you to use the re module. For instance you want to match every: 'Test:X with X a number between 1 and 25

import re

email_subjects = ['Test:1', 'Test:25', 'not_valid!', 'Test:52']
for email_subject in email_subjects:
    if re.search(''^Test:([0-9]|1[0-9]|2[0-5])$'', email_subject): # Compiles to a regular expression and looks for it in email_subject
        print('valid email subjet', email_subject)
    else:
        print('invalid email subjet', email_subject)

Regex breakdown:

^ Starting character match

Test: Your string you want to match

([0-9]|1[0-9]|2[0-5]): your range, which means: a number from 0 to 9, or a 1 and a number from 0 to 9 (which means between 10 and 19) or 2 and a number from 0 to 5 (which means between 20 and 25)

$ Ending character


问:
How to reverse sort a map and send it to model in go lang
I want to send a reverse order of a list of books that are stored in a map and send this to a model instead of the map in its current order.

I need to display a list in reverse order of date entered which is pubDate so that the webpage (model) displays the most recently added books instead of the books added first.

I have tried many various sort methods listed but I do not know how I would send this to the model.  For example, I tried
import "sort"

```<code>var m map[int]string
var keys []int
for k := range m {
    keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
    fmt.Println("Key:", k, "Value:", m[k])
}
</code>```

I also tried
sort.Slice(ad, func(i, j int) bool {

```<code>    return ad[i].date.Before(ad[j].date)})
</code>```

there are many others but I can not seem to get any working.

```<code>type Book struct {
    ID     int64  `json:"id"`
    Title  string `json:"title"`
    Author string `json:"author"`
    pubDate time.Time `json:"pubDate"`
}

var bookModels = map[string]*Book{}

s := res.NewService("library")

    // Add handlers for "library.book.$id" models
    s.Handle(
        "book.$id",
        res.Access(res.AccessGranted),
        res.GetModel(getBookHandler),
        res.Set(setBookHandler),
    )

    // Add handlers for "library.books" collection
    s.Handle(
        "books",
        res.Access(res.AccessGranted),
        res.GetCollection(getBooksHandler),
        res.New(newBookHandler),
        res.Call("delete", deleteBookHandler),
    )

func getBookHandler(r res.ModelRequest) {

    book := bookModels[r.ResourceName()]
    if book == nil {
        r.NotFound()
        return
    }
    r.Model(book)
}
</code>```

Mainly I get errors that the map does not allow indexing, or the wrong type, or cant access the fields, etc...  How can you use a map and send it to a model and ensure that you have the most recent items listed first on the web page?

答:
While you cant sort maps directly, you can wrap each key value pair in a new struct and sort this structarray. It just needs to implement the sort interface, like stated here

Example:

```<code>type structSorter []mystruct
func (a structSorter) Len() int           { return len(a) }
func (a structSorter) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a structSorter) Less(i, j int) bool { return a[i].MyValue < a.[j].MyValue }
</code>```

and called with

```<code>sort.Sort(structSorter(mystructArray))
</code>```

Body:
I want to send a reverse order of a list of books that are stored in a map and send this to a model instead of the map in its current order.

I need to display a list in reverse order of date entered which is pubDate so that the webpage (model) displays the most recently added books instead of the books added first.

I have tried many various sort methods listed but I do not know how I would send this to the model.  For example, I tried
import "sort"

var m map[int]string
var keys []int
for k := range m {
    keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
    fmt.Println("Key:", k, "Value:", m[k])
}

I also tried
sort.Slice(ad, func(i, j int) bool {

    return ad[i].date.Before(ad[j].date)})

there are many others but I can not seem to get any working.

type Book struct {
    ID     int64  `json:"id"`
    Title  string `json:"title"`
    Author string `json:"author"`
    pubDate time.Time `json:"pubDate"`
}

var bookModels = map[string]*Book{}

s := res.NewService("library")

    // Add handlers for "library.book.$id" models
    s.Handle(
        "book.$id",
        res.Access(res.AccessGranted),
        res.GetModel(getBookHandler),
        res.Set(setBookHandler),
    )

    // Add handlers for "library.books" collection
    s.Handle(
        "books",
        res.Access(res.AccessGranted),
        res.GetCollection(getBooksHandler),
        res.New(newBookHandler),
        res.Call("delete", deleteBookHandler),
    )

func getBookHandler(r res.ModelRequest) {

    book := bookModels[r.ResourceName()]
    if book == nil {
        r.NotFound()
        return
    }
    r.Model(book)
}

Mainly I get errors that the map does not allow indexing, or the wrong type, or cant access the fields, etc...  How can you use a map and send it to a model and ensure that you have the most recent items listed first on the web page?

Body:
While you cant sort maps directly, you can wrap each key value pair in a new struct and sort this structarray. It just needs to implement the sort interface, like stated here

Example:

type structSorter []mystruct
func (a structSorter) Len() int           { return len(a) }
func (a structSorter) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a structSorter) Less(i, j int) bool { return a[i].MyValue < a.[j].MyValue }

and called with

sort.Sort(structSorter(mystructArray))


问:
How do I get Xcode to replicate project group structure in the folder structure on disk?
I have an Xcode project with the following group structure:

```<code>ProjectName/
    Classes/
        class1.h
        class1.m
        class2.h
        class2.m
        ...
    XMLDocs/
        doc1.xml
        doc2.xml
        ...
    Resources/
        Info.plist
        MainMenu.xib
        ...
</code>```

and so on and so forth.

I'd like this to be represented in the folder structure on the disk as well:

```<code>ProjectFolder/
    Project.xcodeproj
    Classes/
        class1.h
        class1.m
        class2.h
        class2.m
        ...
    XMLDocs/
        doc1.xml
        doc2.xml
        ...
    Resources/
        Info.plist
        MainMenu.xib
        ...
</code>```

as opposed to the usual everything in the root project folder methodology.

Is there any way to do this without manually creating the folder structure on the disk and then having to repoint all the reference in Xcode to the new location?

Bonus points if you can tell me how to do this automatically any time I create a new group or add files to an existing group in Xcode.

答: I found out that if you move files around in Xcode and press [CMD] at the same time then the folder structure will match the Xcode structure. </p>

OwnerDisplayName: Lawrence Johnston

Body:
I have an Xcode project with the following group structure:

ProjectName/
    Classes/
        class1.h
        class1.m
        class2.h
        class2.m
        ...
    XMLDocs/
        doc1.xml
        doc2.xml
        ...
    Resources/
        Info.plist
        MainMenu.xib
        ...

and so on and so forth.

I'd like this to be represented in the folder structure on the disk as well:

ProjectFolder/
    Project.xcodeproj
    Classes/
        class1.h
        class1.m
        class2.h
        class2.m
        ...
    XMLDocs/
        doc1.xml
        doc2.xml
        ...
    Resources/
        Info.plist
        MainMenu.xib
        ...

as opposed to the usual everything in the root project folder methodology.

Is there any way to do this without manually creating the folder structure on the disk and then having to repoint all the reference in Xcode to the new location?

Bonus points if you can tell me how to do this automatically any time I create a new group or add files to an existing group in Xcode.

LastEditorDisplayName: Chris Hanson


问:
Merge pull request by Github API: SHA parameter
I was reading the documentation of GitHub API and I'm not sure what do do with the Merge Pull Request method.

https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button

Specifically with the parameter SHA. I don't understand what exactly I should provide to API.

The INPUT section says I must provide

commit_title Title for the automatic commit message.

commit_message Extra detail to append to automatic commit message.

sha SHA that pull request head must match to allow merge.

merge_method Merge method to
use.

Where do I exactly get the sha value that I need to pass to API?

Thanks!

答:
Consider the following diagram, which shows a feature branch derived from some base branch:

```<code>base:     ... A -- B -- C
                    \
feature:             D -- E
</code>```

Let's suppose that we created a pull request from feature going back to base.  GitHub would execute this pull request by merging feature into base.  The pull request HEAD, at the time we created the pull request, would be commit E in feature.  But, the HEAD of the feature branch could change before the pull request is completed.

The API call you mention includes the SHA-1 hash of the pull request HEAD, as a requirement for the pull request to complete.  This would avoid the possibility of feature being merged back to base while containing additional commits beyond commit E.

Regarding how you would find the SHA-1 hash for E, the pull request HEAD, you may simply try using git log, e.g.

```<code># from feature
git log
</code>```

Then, check the output for what should be the latest entry from commit E, and find the hash.

Body:
Consider the following diagram, which shows a feature branch derived from some base branch:

base:     ... A -- B -- C
                    \
feature:             D -- E

Let's suppose that we created a pull request from feature going back to base.  GitHub would execute this pull request by merging feature into base.  The pull request HEAD, at the time we created the pull request, would be commit E in feature.  But, the HEAD of the feature branch could change before the pull request is completed.

The API call you mention includes the SHA-1 hash of the pull request HEAD, as a requirement for the pull request to complete.  This would avoid the possibility of feature being merged back to base while containing additional commits beyond commit E.

Regarding how you would find the SHA-1 hash for E, the pull request HEAD, you may simply try using git log, e.g.

# from feature
git log

Then, check the output for what should be the latest entry from commit E, and find the hash.


问:
outlook emails from a particular user should be sent to sharepoint list or document library...:(
when a user sends an email from his id ex:aa to me, i want a way to configure my outlook so that all the emails from that particular user(aa) are redirected to sharepoint list or document library.....i have created some rules and stored all the emails in a particular folder but i want all those emails on sharepoint, when ever a new email arrives it has to update automatically......

please help me on this

thank you...

raj

答:
Configure incoming emails in SharePoint and allow this particular library to receive emails. Some pointers here.

Set outlook rule to forward emails from this particular ID to the Doc Library Eamil ID.


问:
How to decrypt asp.net owin token in asp.net core manually?
I have an existing application which generates owin identity token with machine key approach. The same token is used to authenticate various application. One of the application is now in asp.net core. Is there any way to use same owin generated identity token in asp.net core?

or we can decode that token manually in asp.net core

答:
You cannot share anything between ASP.NET and ASP.NET Core when using machine keys. The only way to be able to decrypt something in ASP.NET Core set by an ASP.NET app is if 1) the ASP.NET app(s) utilize the data protection provider 2) the data protection provider key ring is persisted to filesystem or network location accessible by all the apps (ASP.NET and ASP.NET Core alike) and all the apps utilize the same application name.

The docs go into great detail on this.


问:
Google Play Leaderboard - Cannot Submit Score
I would like to pick your brains on something that might be as simple as a config issue.

I am developing a game using Xamarin Forms and I have an issue when I am trying to submit a time score to Google Play Leaderboards.

The user signs in correctly with Google Play and I can see the leaderboards correctly but I cannot submit a score.

I am suspecting that this is because my project in Android Studio is on internal testing phase (less than Alpha). The game, game services and leaderboards are published. The published APK is for the previous version of the game which didn't have the leaderboards code added.

When I use GamesClass.Leaderboards.SubmitScore() it will not error but then the leaderboard is corrupted and when the leaderboard is shown, it says something went wrong. Reinstalling the app is the only way to fix it. Using GamesClass.Leaderboards.SubmitScoreImmediate doesn't error and the leaderboard is not corrupted, but the score is not shown.

This is my call to submit the score in the MainActivity.cs (Android project)

```<code>if (mGoogleApiClient.IsConnected)
{
  var result = await GamesClass.Leaderboards.SubmitScoreImmediate(mGoogleApiClient, LeaderboardID, score);
  return true;
}
</code>```

答:
After a lot of testing and retesting, the issue was that the API Oauths were not set correctly (even though they looked ok) in Google Play Console.

The error message when submitting a score and then viewing the leadeboard was because of the above and not a real leaderboard corruption or error.

I resolved it by creating two Game Services linked to the same application, one authorised with my upload certificate and the other authorised with Google App signing certificate.

This now allows me to use Google Play Services while debugging (Upload certificate) and from the Play Store app (Signing certificate).

Hope this might help anyone with similar issues.

Body:
I would like to pick your brains on something that might be as simple as a config issue.

I am developing a game using Xamarin Forms and I have an issue when I am trying to submit a time score to Google Play Leaderboards.

The user signs in correctly with Google Play and I can see the leaderboards correctly but I cannot submit a score.

I am suspecting that this is because my project in Android Studio is on internal testing phase (less than Alpha). The game, game services and leaderboards are published. The published APK is for the previous version of the game which didn't have the leaderboards code added.

When I use GamesClass.Leaderboards.SubmitScore() it will not error but then the leaderboard is corrupted and when the leaderboard is shown, it says something went wrong. Reinstalling the app is the only way to fix it. Using GamesClass.Leaderboards.SubmitScoreImmediate doesn't error and the leaderboard is not corrupted, but the score is not shown.

This is my call to submit the score in the MainActivity.cs (Android project)

if (mGoogleApiClient.IsConnected)
{
  var result = await GamesClass.Leaderboards.SubmitScoreImmediate(mGoogleApiClient, LeaderboardID, score);
  return true;
}


问:
How to control Sass Variable with javascript
I have a Sass file which is generating a CSS file. I have used many variables in my sass file for background color, font-size, now I want to control my all variables through JavaScript.

For example, in style.sass we have

```<code>$bg : #000;
$font-size: 12px;
</code>```

How can I change these values from JavaScript?

答:
I find sass-extract-loader especially helpful for using with Create-React-App.

You can use it like:

_variables.scss

```<code>$theme-colors: (
  "primary": #00695F,
  "info": #00A59B
);
</code>```

component.tsx

```<code> const style = require('sass-extract-loader!./_variables.scss');
 const brandInfo = style.global['$theme-colors'].value.primary.value.hex; // '#00695F';
</code>```

Body:
I have a Sass file which is generating a CSS file. I have used many variables in my sass file for background color, font-size, now I want to control my all variables through JavaScript.

For example, in style.sass we have

$bg : #000;
$font-size: 12px;

How can I change these values from JavaScript?

Body:
I find sass-extract-loader especially helpful for using with Create-React-App.

You can use it like:

_variables.scss

$theme-colors: (
  "primary": #00695F,
  "info": #00A59B
);

component.tsx

 const style = require('sass-extract-loader!./_variables.scss');
 const brandInfo = style.global['$theme-colors'].value.primary.value.hex; // '#00695F';