问:
fastshap::explain() returning error 'number of items to replace is not a multiple of replacement length'
I'm trying to use fastshap::explain() to understand the feature importance for N clusters in a probability forest.

I set up the model like so:

```<code>X <- df %>%
  dplyr::select(-c(var1, var15, var29, var30, var31, clusters)) %>%
  mutate_if(is.character, as.factor) %>%
  mutate_if(is.factor, as.numeric)

Y <- df %>% pull(clusters)

p_forest <- grf::probability_forest(
  X = X,
  Y = Y)

# Set up function
pfun <- function(object, newdata) {
  grf:::predict.probability_forest(object = object, newdata = newdata)$predictions
}

# Set up parallel backend
cl <- if (.Platform$OS.type == "unix") 8 else makeCluster(32)
registerDoParallel(cl)

# Run some simulations
system.time({  # estimate run time
  set.seed(5038)
  shap_vals <- fastshap::explain(p_forest,
                       X = X,
                       pred_wrapper = pfun,
                       adjust = TRUE,
                       nsim = 10,
                       .parallel = TRUE
                       )
})
</code>```

And I receive the following error:

```<code>Warning message in err * (v - (v * sum(v))/(1 + sum(v))):
“longer object length is not a multiple of shorter object length”
Warning message in res[, 1L] + adj:
“longer object length is not a multiple of shorter object length”
Error in res[, 1L] <- res[, 1L] + adj: number of items to replace is not a multiple of replacement length
Error in res[, 1L] <- res[, 1L] + adj: number of items to replace is not a multiple of replacement length
Traceback:
1. system.time({
 .     set.seed(5038)
 .     shap_vals <- explain(p_forest, X = X, pred_wrapper = pfun,
 .         adjust = TRUE, nsim = 10, .parallel = TRUE)
 . })
2. explain(p_forest, X = X, pred_wrapper = pfun, adjust = TRUE,
 .     nsim = 10, .parallel = TRUE)   # at line 13-19 of file <text>
3. explain.default(p_forest, X = X, pred_wrapper = pfun, adjust = TRUE,
 .     nsim = 10, .parallel = TRUE)
Timing stopped at: 1.235e+04 105.8 483.4
</code>```

Does anyone know where i'm going wrong here? And how to solve it?

答:
So it turns out that the output of the line:

```<code>grf:::predict.probability_forest(object = object, newdata = newdata)$predictions
</code>```

was a matrix where explain() expected a vector. I was able to solve it by indexing the predictions like so:

```<code>grf:::predict.probability_forest(object = object, newdata = newdata)$predictions[,1]
</code>```

And then repeating for each cluster's set of predictions

Body:
I'm trying to use fastshap::explain() to understand the feature importance for N clusters in a probability forest.

I set up the model like so:

X <- df %>%
  dplyr::select(-c(var1, var15, var29, var30, var31, clusters)) %>%
  mutate_if(is.character, as.factor) %>%
  mutate_if(is.factor, as.numeric)

Y <- df %>% pull(clusters)

p_forest <- grf::probability_forest(
  X = X,
  Y = Y)

# Set up function
pfun <- function(object, newdata) {
  grf:::predict.probability_forest(object = object, newdata = newdata)$predictions
}

# Set up parallel backend
cl <- if (.Platform$OS.type == "unix") 8 else makeCluster(32)
registerDoParallel(cl)

# Run some simulations
system.time({  # estimate run time
  set.seed(5038)
  shap_vals <- fastshap::explain(p_forest,
                       X = X,
                       pred_wrapper = pfun,
                       adjust = TRUE,
                       nsim = 10,
                       .parallel = TRUE
                       )
})

And I receive the following error:

Warning message in err * (v - (v * sum(v))/(1 + sum(v))):
“longer object length is not a multiple of shorter object length”
Warning message in res[, 1L] + adj:
“longer object length is not a multiple of shorter object length”
Error in res[, 1L] <- res[, 1L] + adj: number of items to replace is not a multiple of replacement length
Error in res[, 1L] <- res[, 1L] + adj: number of items to replace is not a multiple of replacement length
Traceback:
1. system.time({
 .     set.seed(5038)
 .     shap_vals <- explain(p_forest, X = X, pred_wrapper = pfun,
 .         adjust = TRUE, nsim = 10, .parallel = TRUE)
 . })
2. explain(p_forest, X = X, pred_wrapper = pfun, adjust = TRUE,
 .     nsim = 10, .parallel = TRUE)   # at line 13-19 of file <text>
3. explain.default(p_forest, X = X, pred_wrapper = pfun, adjust = TRUE,
 .     nsim = 10, .parallel = TRUE)
Timing stopped at: 1.235e+04 105.8 483.4

Does anyone know where i'm going wrong here? And how to solve it?

Body:
So it turns out that the output of the line:

grf:::predict.probability_forest(object = object, newdata = newdata)$predictions

was a matrix where explain() expected a vector. I was able to solve it by indexing the predictions like so:

grf:::predict.probability_forest(object = object, newdata = newdata)$predictions[,1]

And then repeating for each cluster's set of predictions


来源: stackexchange

问:
Is it Possible to Name the Azure Network Watcher?
When I created an Azure virtual network, it automatically creates a Network Watcher called NetworkWatcher_canadacentral for me in its own resource group called NetworkWatcherRG.

My question is whether its possible to give the Network Watcher and the resource group it gets created in a custom name. I'm using Pulumi to Create my virtual network but answers showing ARM/Bicep/Terraform are also welcome.

答:
You can name it whatever you want as long as it meets the naming requirements which is 1-80 chars, Alphanumerics, underscores, periods, and hyphens. Start with alphanumeric. End alphanumeric or underscore.

Terraform

In Terraform you just give the Network Watcher resource name whatever you want like so:

```<code>resource "azurerm_network_watcher" "app1_traffic" {
  name                = "MyAwesomeNetworkWatcherName"
  location            = azurerm_resource_group.application1.location
  resource_group_name = azurerm_resource_group.application1.name
}
</code>```

PowerShell

In PowerShell the command is:

```<code>New-AzNetworkWatcher -Name "MyNetworkWatcherName" -ResourceGroupName "secstuff" -Location "East US 2"
</code>```

Pulumi

From what I see on the Pulumi docs Network Watcher does take a name parameter.

ContentLicense: CC BY-SA 4.0

Body:
You can name it whatever you want as long as it meets the naming requirements which is 1-80 chars, Alphanumerics, underscores, periods, and hyphens. Start with alphanumeric. End alphanumeric or underscore.

Terraform

In Terraform you just give the Network Watcher resource name whatever you want like so:

resource "azurerm_network_watcher" "app1_traffic" {
  name                = "MyAwesomeNetworkWatcherName"
  location            = azurerm_resource_group.application1.location
  resource_group_name = azurerm_resource_group.application1.name
}

PowerShell

In PowerShell the command is:

New-AzNetworkWatcher -Name "MyNetworkWatcherName" -ResourceGroupName "secstuff" -Location "East US 2"

Pulumi

From what I see on the Pulumi docs Network Watcher does take a name parameter.


问:
Configure a bean with a parameter sent with API Call
I have a configuration class to configure a sqlite database connection. Here I do configure it manually.

```<code>@Configuration
@EnableJpaRepositories(basePackages = "fr.company.dashboard.io.repository")
public class DBConfiguration {
    private final ApplicationProperties applicationProperties;

    @Autowired
    public DBConfiguration(ApplicationProperties applicationProperties) {
        this.applicationProperties = applicationProperties;
    }

    @Bean
    public DataSource dataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(applicationProperties.getProperty("hibernate.connection.driverClassName"));
        dataSource.setUrl(applicationProperties.getProperty("url"));
        dataSource.setUsername(applicationProperties.getProperty("user"));
        dataSource.setPassword(applicationProperties.getProperty("password"));
        return dataSource;
    }
}
</code>```

I would like to set the database by using an API get method which includes the database name in the URL

答:
In my case, I have multiple sqlite db in a same folder.
I changed my controller in order to retrieve the database name from entry point:

```<code>@RestController
@RequestMapping("/dbfiles")
public class AppController {
    private final AppService appService;
    private final DataSourceContextHolder dataSourceContextHolder;

    @Autowired
    public DatabaseListController(AppService AppService,
                                  DataSourceContextHolder dataSourceContextHolder) {
        this.appService= appService;
        this.dataSourceContextHolder = dataSourceContextHolder;
    }

    @GetMapping("/{dbName}")
    public List<AppResponse> getAll(@PathVariable("dbName") String dbName) throws IOException {
        Set<String> databases = Utils.getDatabaseList();
        if(databases.contains(dbName) || databases.contains(dbName + ".db")) {
            dataSourceContextHolder.setBranchContext(dbName);
        }

        List<AppResponse> returnValue = new ArrayList<>();
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        List<AppResponse> appResponses = appService.getAll();
        returnValue = modelMapper.map(
                appResponses ,
                new TypeToken<List<AppDto>>() {}.getType()
        );
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(returnValue);

        System.out.println(json);
        return returnValue;
    }
}
</code>```

I used a component class where i pass the database name:

```<code>@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class DataSourceContextHolder {
    private static ThreadLocal<String> threadLocal;

    public DataSourceContextHolder() {
        threadLocal = new ThreadLocal<>();
    }

    public void setBranchContext(String dbName) {
        threadLocal.set(dbName);
    }

    public String getBranchContext() {
        return threadLocal.get();
    }

    public static void clearBranchContext() {
        threadLocal.remove();
    }
}
</code>```

I also created a DataSourceRouting class that handles at start the databases:

```<code>@Component
public class DataSourceRouting extends AbstractRoutingDataSource {
    private DataSourceContextHolder dataSourceContextHolder;
    private DataSourceConfig dataSourceConfig;

    public DataSourceRouting(DataSourceContextHolder dataSourceContextHolder,
                             DataSourceConfig dataSourceConfig) throws IOException {
        this.dataSourceContextHolder = dataSourceContextHolder;
        this.dataSourceConfig = dataSourceConfig;

        Map<Object, Object> dataSourceMap = new HashMap<>();
        Set<String> databases = Utils.getDatabaseList();
        databases.forEach(database -> {
            DataSource dataSource = dataSourceBuilder(database);
            dataSourceMap.put(database, dataSource);
            this.setDefaultTargetDataSource(dataSource);

        });
        this.setTargetDataSources(dataSourceMap);

    }

    private DataSource dataSourceBuilder(String database) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(dataSourceConfig.getDriverClassName());
        dataSource.setUrl(dataSourceConfig.getUrl() + database);
        dataSource.setUsername(dataSourceConfig.getUsername());
        dataSource.setPassword(dataSourceConfig.getPassword());
        return dataSource;
    }

    @Override
    protected Object determineCurrentLookupKey() {
        //System.out.println(dataSourceContextHolder.getBranchContext().toString());
        return dataSourceContextHolder.getBranchContext();
    }
}
</code>```

I created a POJO that reads in application.properties :

```<code>@Component
@ConfigurationProperties(prefix="datasource")
@Getter @Setter
public class DataSourceConfig {
    private String url;
    private String password;
    private String username;
    private String driverClassName;
}
</code>```

This code allow to pass the database name and to make queries on the right one. As the databases have the same structure, I do output the correct values as expected.

Body:
I have a configuration class to configure a sqlite database connection. Here I do configure it manually.

@Configuration
@EnableJpaRepositories(basePackages = "fr.company.dashboard.io.repository")
public class DBConfiguration {
    private final ApplicationProperties applicationProperties;

    @Autowired
    public DBConfiguration(ApplicationProperties applicationProperties) {
        this.applicationProperties = applicationProperties;
    }

    @Bean
    public DataSource dataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(applicationProperties.getProperty("hibernate.connection.driverClassName"));
        dataSource.setUrl(applicationProperties.getProperty("url"));
        dataSource.setUsername(applicationProperties.getProperty("user"));
        dataSource.setPassword(applicationProperties.getProperty("password"));
        return dataSource;
    }
}

I would like to set the database by using an API get method which includes the database name in the URL

Body:
In my case, I have multiple sqlite db in a same folder.
I changed my controller in order to retrieve the database name from entry point:

@RestController
@RequestMapping("/dbfiles")
public class AppController {
    private final AppService appService;
    private final DataSourceContextHolder dataSourceContextHolder;

    @Autowired
    public DatabaseListController(AppService AppService,
                                  DataSourceContextHolder dataSourceContextHolder) {
        this.appService= appService;
        this.dataSourceContextHolder = dataSourceContextHolder;
    }

    @GetMapping("/{dbName}")
    public List<AppResponse> getAll(@PathVariable("dbName") String dbName) throws IOException {
        Set<String> databases = Utils.getDatabaseList();
        if(databases.contains(dbName) || databases.contains(dbName + ".db")) {
            dataSourceContextHolder.setBranchContext(dbName);
        }

        List<AppResponse> returnValue = new ArrayList<>();
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        List<AppResponse> appResponses = appService.getAll();
        returnValue = modelMapper.map(
                appResponses ,
                new TypeToken<List<AppDto>>() {}.getType()
        );
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(returnValue);

        System.out.println(json);
        return returnValue;
    }
}

I used a component class where i pass the database name:

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class DataSourceContextHolder {
    private static ThreadLocal<String> threadLocal;

    public DataSourceContextHolder() {
        threadLocal = new ThreadLocal<>();
    }

    public void setBranchContext(String dbName) {
        threadLocal.set(dbName);
    }

    public String getBranchContext() {
        return threadLocal.get();
    }

    public static void clearBranchContext() {
        threadLocal.remove();
    }
}

I also created a DataSourceRouting class that handles at start the databases:

@Component
public class DataSourceRouting extends AbstractRoutingDataSource {
    private DataSourceContextHolder dataSourceContextHolder;
    private DataSourceConfig dataSourceConfig;

    public DataSourceRouting(DataSourceContextHolder dataSourceContextHolder,
                             DataSourceConfig dataSourceConfig) throws IOException {
        this.dataSourceContextHolder = dataSourceContextHolder;
        this.dataSourceConfig = dataSourceConfig;

        Map<Object, Object> dataSourceMap = new HashMap<>();
        Set<String> databases = Utils.getDatabaseList();
        databases.forEach(database -> {
            DataSource dataSource = dataSourceBuilder(database);
            dataSourceMap.put(database, dataSource);
            this.setDefaultTargetDataSource(dataSource);

        });
        this.setTargetDataSources(dataSourceMap);

    }

    private DataSource dataSourceBuilder(String database) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(dataSourceConfig.getDriverClassName());
        dataSource.setUrl(dataSourceConfig.getUrl() + database);
        dataSource.setUsername(dataSourceConfig.getUsername());
        dataSource.setPassword(dataSourceConfig.getPassword());
        return dataSource;
    }

    @Override
    protected Object determineCurrentLookupKey() {
        //System.out.println(dataSourceContextHolder.getBranchContext().toString());
        return dataSourceContextHolder.getBranchContext();
    }
}

I created a POJO that reads in application.properties :

@Component
@ConfigurationProperties(prefix="datasource")
@Getter @Setter
public class DataSourceConfig {
    private String url;
    private String password;
    private String username;
    private String driverClassName;
}

This code allow to pass the database name and to make queries on the right one. As the databases have the same structure, I do output the correct values as expected.


问:
Automate the Boring Stuff - Coin Flip Streaks - How to optimize my answer?
I've been going through automate the boring stuff, and am trying the practice problems.
I came up with this solution to the project on the lists chapter - Coin Flip Streaks.

The objective of the problem is the following:
''For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.

Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.''
And this is my code.

```<code>numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    experimentNumber = experimentNumber + 1
    for test in range(100):
        selector = random.randint(0,1)
        if selector == 0:
            experiment = experiment + ['H']
        elif selector == 1:
            experiment = experiment + ['T']

    for n in range(94):
        if experiment[n:n+6] == ['T', 'T', 'T', 'T', 'T', 'T']:
            numberOfStreaks = numberOfStreaks + 1
        elif experiment[n:n+6] == ['H', 'H', 'H', 'H', 'H', 'H']:
            numberOfStreaks = numberOfStreaks + 1
        else:
            numberOfStreaks = numberOfStreaks
print((numberOfStreaks / 100000) * 100)
</code>```

I can only run this solution efficiently for 1000 experiments, and the book says to run for 10000, but it takes too long.
I think this derives from the inneficiency of the algorithm I came up with.

How do I make this algorithm more efficient?

答:
If the question is what I paraphrased in my comment, this is about as efficient as you can be. (Notice that once a streak is seen, that trial is over before 100 coins were flipped)</p>
```<code>import random
EXPERIMENT_COUNT = 10_000
streaks = 0
random.seed()  # make sure each run is different
for trials in range(EXPERIMENT_COUNT):
    heads = tails = 0
    for flips in range(100):
        if random.choice((False,True)):
            heads += 1
            tails = 0
        else:
            tails += 1
            heads = 0
        if heads >= 6 or tails >= 6:
            streaks += 1
            break
print (f"In {EXPERIMENT_COUNT} trials of 100 flips, {streaks} trials contained a streak of 6 or more")
print (f"Which is about {streaks*100 // EXPERIMENT_COUNT}%")
</code>```

Body:
I've been going through automate the boring stuff, and am trying the practice problems.
I came up with this solution to the project on the lists chapter - Coin Flip Streaks.

The objective of the problem is the following:
''For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.

Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.''
And this is my code.

numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    experimentNumber = experimentNumber + 1
    for test in range(100):
        selector = random.randint(0,1)
        if selector == 0:
            experiment = experiment + ['H']
        elif selector == 1:
            experiment = experiment + ['T']

    for n in range(94):
        if experiment[n:n+6] == ['T', 'T', 'T', 'T', 'T', 'T']:
            numberOfStreaks = numberOfStreaks + 1
        elif experiment[n:n+6] == ['H', 'H', 'H', 'H', 'H', 'H']:
            numberOfStreaks = numberOfStreaks + 1
        else:
            numberOfStreaks = numberOfStreaks
print((numberOfStreaks / 100000) * 100)

I can only run this solution efficiently for 1000 experiments, and the book says to run for 10000, but it takes too long.
I think this derives from the inneficiency of the algorithm I came up with.

How do I make this algorithm more efficient?

Body:
If the question is what I paraphrased in my comment, this is about as efficient as you can be. (Notice that once a streak is seen, that trial is over before 100 coins were flipped)

import random
EXPERIMENT_COUNT = 10_000
streaks = 0
random.seed()  # make sure each run is different
for trials in range(EXPERIMENT_COUNT):
    heads = tails = 0
    for flips in range(100):
        if random.choice((False,True)):
            heads += 1
            tails = 0
        else:
            tails += 1
            heads = 0
        if heads >= 6 or tails >= 6:
            streaks += 1
            break
print (f"In {EXPERIMENT_COUNT} trials of 100 flips, {streaks} trials contained a streak of 6 or more")
print (f"Which is about {streaks*100 // EXPERIMENT_COUNT}%")


问:
convert string to object for using jQuery.each() function
I create a string:

```<code>myOption = "{val1:'text1', val2:'text2'...}"
</code>```

I need convert this string into a Object:

```<code>myOption = {val1:'text1', val2:'text2'...}
</code>```

for using the jquery each function and take a pair value/text in each iteration.

Now in each iteration, it takes one char of the string.

答:
You can use:

```<code>$.parseJSON(myOption);
</code>```

Keep in mind that your JSON string needs to be well-formed, and that means double-quoting property names and values:

```<code>var myOption = '{"val1":"text1", "val2":"text2"}';
var obj = $.parseJSON(myOption);
$.each(obj, function(i, val) {
    alert(i + ' ' + val);
});
</code>```

Demo.

Body:
I create a string:

myOption = "{val1:'text1', val2:'text2'...}"

I need convert this string into a Object:

myOption = {val1:'text1', val2:'text2'...}

for using the jquery each function and take a pair value/text in each iteration.

Now in each iteration, it takes one char of the string.

Body:
You can use:

$.parseJSON(myOption);

Keep in mind that your JSON string needs to be well-formed, and that means double-quoting property names and values:

var myOption = '{"val1":"text1", "val2":"text2"}';
var obj = $.parseJSON(myOption);
$.each(obj, function(i, val) {
    alert(i + ' ' + val);
});

Demo.

ContentLicense: CC BY-SA 3.0


问:
Can I use to_char() and make_date() in postgreSQL table definition?
I'm working on a poc to migrate an on-prem SQL Server database to Amazon Aurora for PostgreSQL. Amazon's Schema Conversion Tool struggled to translate the SQL Server code for the creation of a table on this column:

```<code>[DOB] AS (CONVERT([varchar],datefromparts([DOB_year],[DOB_month],[DOB_day]),(120))) PERSISTED,
</code>```

as the CONVERT function is unsupported in Postgres.

The best translation I can come up with is:

```<code>dob varchar(30) GENERATED ALWAYS AS (to_char((make_date(dob_year, dob_month, dob_day))::timestamp, 'YYYY-MM-DD HH24:MI:SS')) STORED,
</code>```

but neither the SCT nor pgAdmin4 are recognising to_char() and make_date() as functions. 'dob_day', 'dob_month' and 'dob_year' are all column names with datatype of integer. I'm new to all this but another column definition is using other functions, e.g. replace() and right(), successfully, so I'm confused why this isn't working.

When I tried to run the code in pgAdmin I got this error:

```<code>ERROR:  generation expression is not immutable
SQL state: 42P17
</code>```

Thanks

答:
to_char() is is not marked as immutable even though in your case it would be. But there are format masks that are not immutable if e.g. time zones or different locales are involved.

If you really want to (or are forced to) convert day,month, year in a formatted string (rather than a proper date which would be the correct thing to do), then you can only achieve this with a custom function:

```<code>create function create_string_date(p_year int, p_month int, p_day int)
  returns text
as
$$
   select to_char(make_date(p_year, p_month, p_day), 'yyyy-mm-dd hh24:mi:ss');
$$
language sql
immutable;
</code>```

Marking the function as immutable isn't cheating, because we know that with the given input and format string this is indeed immutable.

```<code>dob text generated always as (create_string_date(dob_year, dob_month, dob_day)) stored
</code>```

Body:
I'm working on a poc to migrate an on-prem SQL Server database to Amazon Aurora for PostgreSQL. Amazon's Schema Conversion Tool struggled to translate the SQL Server code for the creation of a table on this column:

[DOB] AS (CONVERT([varchar],datefromparts([DOB_year],[DOB_month],[DOB_day]),(120))) PERSISTED,

as the CONVERT function is unsupported in Postgres.

The best translation I can come up with is:

dob varchar(30) GENERATED ALWAYS AS (to_char((make_date(dob_year, dob_month, dob_day))::timestamp, 'YYYY-MM-DD HH24:MI:SS')) STORED,

but neither the SCT nor pgAdmin4 are recognising to_char() and make_date() as functions. 'dob_day', 'dob_month' and 'dob_year' are all column names with datatype of integer. I'm new to all this but another column definition is using other functions, e.g. replace() and right(), successfully, so I'm confused why this isn't working.

When I tried to run the code in pgAdmin I got this error:

ERROR:  generation expression is not immutable
SQL state: 42P17

Thanks

Body:
to_char() is is not marked as immutable even though in your case it would be. But there are format masks that are not immutable if e.g. time zones or different locales are involved.

If you really want to (or are forced to) convert day,month, year in a formatted string (rather than a proper date which would be the correct thing to do), then you can only achieve this with a custom function:

create function create_string_date(p_year int, p_month int, p_day int)
  returns text
as
$$
   select to_char(make_date(p_year, p_month, p_day), 'yyyy-mm-dd hh24:mi:ss');
$$
language sql
immutable;

Marking the function as immutable isn't cheating, because we know that with the given input and format string this is indeed immutable.

dob text generated always as (create_string_date(dob_year, dob_month, dob_day)) stored


问:
How to add an item to a list on a separate page in Flutter
I am new to Flutter and currently building an app to log spasms that happens due to spasticity. This is somewhat like a ToDo style app in structure. So I have a list in my home.dart file that a ListViewBuilder to display my Spasm objects. What I want to do is to create a Spasm object in recordSpasm.dart and add it to the list in home.dart. How  do I do that? I´ll post my code here:

home.dart

```<code>import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:spasmlogger/classses/spasm.dart';

class Home extends StatefulWidget {
  const Home({ Key? key }) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  List<Spasm> Spasms = [
    Spasm("Extremely strong", "Upper body", "Cannot control  left arm"),
    Spasm("Extremely strong", "Upper body", "Cannot control  left arm")
  ];

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("SpasmLogger"),
        actions: <Widget>[
          IconButton(
            icon: Icon(MdiIcons.help),
            onPressed: () {
              Navigator.pushNamed(context, '/about');
            },
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(MdiIcons.plus),
        onPressed: () {
          Navigator.pushNamed(context, "/recordSpasm");
        }
      ),
      body: Padding(
        padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
        child: ListView.builder(
          itemCount: Spasms.length,
          itemBuilder: (BuildContext context, int index){
            return Card(
              child: ListTile(
                title: Text(Spasms[index].strength + " spasm detected in " + Spasms[index].bodyPart),
                subtitle: Text(Spasms[index].comment)
            )
            );
          },
        )
      ),
    );
  }
}
</code>```

recordSpasm.dart

```<code>import 'package:flutter/material.dart';
import 'package:spasmlogger/classses/spasm.dart';

class RecordSpasm extends StatefulWidget {
  const RecordSpasm({ Key? key }) : super(key: key);

  @override
  _RecordSpasmState createState() => _RecordSpasmState();
}

class _RecordSpasmState extends State<RecordSpasm> {
  @override

  String Strength = "Regular strength";
  List<String> Strengths = ["Regular strength", "Mildly stronger", "Severely Strong", "Extremely strong"];
  String BodyPart = "Lower body";
  List<String> BodyParts = ["Lower body", "Upper body", "Head"];
  TextEditingController comment = new TextEditingController();

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Record spasm")

      ),
      body:
      Padding(
        padding: EdgeInsets.all(16),
        child: Form(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget> [
              Text("Spasm strength"),
              DropdownButton(
                value: Strength,
                items: Strengths.map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
        );
      }).toList(),
                onChanged: (String? value) {
                  setState(() {
                    Strength = value!;

                  });

                },
                ),
                Text("Part of body"),
                DropdownButton(
                  value: BodyPart,
                  items: BodyParts.map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                  );
                }).toList(),
                onChanged: (String? value) {
                  setState(() {
                    BodyPart = value!;

                  });

                },
                ),
                Text("Comments"),
                TextFormField(
                  maxLines: 5,
                  controller: comment,

                ),
                ElevatedButton(
                  onPressed: () {
                    // Add object to the list in home.dart
                    print(Strength);
                    print(BodyPart);
                    print(comment.text);

                  },
                  child: Text("Record spasm")
                  )

          ]
        )
      )
      )
    );
  }
}
</code>```

答:
Navigator.push returns a Future when the pushed page is popped. So you just need to add the Spasm object in the recordSpasm.dart:

```<code>ElevatedButton(
    onPressed: () {
       Navigator.pop(context,Spasm(Strength, BodyPart, comment.text));
                   },
       child: Text("Record spasm")
              )
</code>```

and retrieve the object and "refresh" the page in the home.dart

```<code>floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            Navigator.pushNamed(context, "/recordSpasm").then((value) {
              if (value != null && value is Spasm) {
                setState(() {
             // if this doesn't work add the value to the list then call setState
                  Spasms.add(value);
                });
              }
            });
          }),
</code>```

Just a tip, in dart variable names should be lowercase (eg: String strength) :)

Body:
I am new to Flutter and currently building an app to log spasms that happens due to spasticity. This is somewhat like a ToDo style app in structure. So I have a list in my home.dart file that a ListViewBuilder to display my Spasm objects. What I want to do is to create a Spasm object in recordSpasm.dart and add it to the list in home.dart. How  do I do that? I´ll post my code here:

home.dart

import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:spasmlogger/classses/spasm.dart';

class Home extends StatefulWidget {
  const Home({ Key? key }) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  List<Spasm> Spasms = [
    Spasm("Extremely strong", "Upper body", "Cannot control  left arm"),
    Spasm("Extremely strong", "Upper body", "Cannot control  left arm")
  ];

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("SpasmLogger"),
        actions: <Widget>[
          IconButton(
            icon: Icon(MdiIcons.help),
            onPressed: () {
              Navigator.pushNamed(context, '/about');
            },
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(MdiIcons.plus),
        onPressed: () {
          Navigator.pushNamed(context, "/recordSpasm");
        }
      ),
      body: Padding(
        padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
        child: ListView.builder(
          itemCount: Spasms.length,
          itemBuilder: (BuildContext context, int index){
            return Card(
              child: ListTile(
                title: Text(Spasms[index].strength + " spasm detected in " + Spasms[index].bodyPart),
                subtitle: Text(Spasms[index].comment)
            )
            );
          },
        )
      ),
    );
  }
}

recordSpasm.dart

import 'package:flutter/material.dart';
import 'package:spasmlogger/classses/spasm.dart';

class RecordSpasm extends StatefulWidget {
  const RecordSpasm({ Key? key }) : super(key: key);

  @override
  _RecordSpasmState createState() => _RecordSpasmState();
}

class _RecordSpasmState extends State<RecordSpasm> {
  @override

  String Strength = "Regular strength";
  List<String> Strengths = ["Regular strength", "Mildly stronger", "Severely Strong", "Extremely strong"];
  String BodyPart = "Lower body";
  List<String> BodyParts = ["Lower body", "Upper body", "Head"];
  TextEditingController comment = new TextEditingController();

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Record spasm")

      ),
      body:
      Padding(
        padding: EdgeInsets.all(16),
        child: Form(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget> [
              Text("Spasm strength"),
              DropdownButton(
                value: Strength,
                items: Strengths.map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
        );
      }).toList(),
                onChanged: (String? value) {
                  setState(() {
                    Strength = value!;

                  });

                },
                ),
                Text("Part of body"),
                DropdownButton(
                  value: BodyPart,
                  items: BodyParts.map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                  );
                }).toList(),
                onChanged: (String? value) {
                  setState(() {
                    BodyPart = value!;

                  });

                },
                ),
                Text("Comments"),
                TextFormField(
                  maxLines: 5,
                  controller: comment,

                ),
                ElevatedButton(
                  onPressed: () {
                    // Add object to the list in home.dart
                    print(Strength);
                    print(BodyPart);
                    print(comment.text);

                  },
                  child: Text("Record spasm")
                  )

          ]
        )
      )
      )
    );
  }
}

Body:
Navigator.push returns a Future when the pushed page is popped. So you just need to add the Spasm object in the recordSpasm.dart:

ElevatedButton(
    onPressed: () {
       Navigator.pop(context,Spasm(Strength, BodyPart, comment.text));
                   },
       child: Text("Record spasm")
              )

and retrieve the object and "refresh" the page in the home.dart

floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            Navigator.pushNamed(context, "/recordSpasm").then((value) {
              if (value != null && value is Spasm) {
                setState(() {
             // if this doesn't work add the value to the list then call setState
                  Spasms.add(value);
                });
              }
            });
          }),

Just a tip, in dart variable names should be lowercase (eg: String strength) :)


问:
Plug.Conn, all plugs must receive a connection (conn) and return a connection
so I'm trying to update a schema by matching the params["state"] on a callback, In my controller, I'm doing something like this.

```<code>def create(conn, params) do
  viewer = GiftActions.get_gift_user!(params["user_id"])

  case params["state"] do
    "captured" ->
      GiftActions.validate_gift_order(viewer, params)
      Logger.info("Request is validated sending code to #{inspect(viewer.email)}")

      {:ok, id} ->
        put_status(conn, 200)
        |> json(%{data: id})

      _ -> put_status(conn, 404) |> json(%{data: ""})
  end
end
</code>```

My function will handle update if params["state"] is captured, like this

```<code>def validate_gift_order(viewer, attrs) do
 {:ok, gift_order} = __MODULE__.get_gift_by_payment_id(viewer, attrs["id"])

 gift_order
 |> GiftOrders.changeset(%{state: attrs["state"]})
 |> Repo.update()
end
</code>```

Everything work's fine but in the end I'm failing to return Plug.Conn. Error is saying

```<code>[error] #PID<0.5693.0> running VWeb.Endpoint (connection #PID<0.5692.0>, stream id 1) terminated
Server: localhost:4000 (http)
Request: POST /api/v1/gift-callback?user_id=#######
** (exit) an exception was raised:
    ** (RuntimeError) expected action/2 to return a Plug.Conn, all plugs must receive a connection (conn) and return a connection, got: :ok
        (viavolo 0.1.0) lib/v_web/controllers/gif_callback_controller.ex:1: VWeb.GiftCallbackController.phoenix_controller_pipeline/2
        (phoenix 1.5.9) lib/phoenix/router.ex:352: Phoenix.Router.__call__/2
        (viavolo 0.1.0) lib/viavolo_web/endpoint.ex:1: ViavoloWeb.Endpoint.plug_builder_call/2
        (viavolo 0.1.0) lib/viavolo_web/endpoint.ex:1: VWeb.Endpoint."call (overridable 3)"/2
        (viavolo 0.1.0) lib/plug/debugger.ex:136: VWeb.Endpoint."call (overridable 4)"/2
        (viavolo 0.1.0) lib/v_web/endpoint.ex:1: VWeb.Endpoint.call/2
</code>```

and I'm not entirely sure why? What I'm I supposed to return here?

答:
Your code is indented wrong, which makes me think you think you have another case statement. Here is the correct indentation for your code:

def create(conn, params) do
  viewer = GiftActions.get_gift_user!(params["user_id"])

  case params["state"] do
    "captured" ->
      GiftActions.validate_gift_order(viewer, params)
      Logger.info("Request is validated sending code to #{inspect(viewer.email)}")

    {:ok, id} ->
      put_status(conn, 200)
      |> json(%{data: id})

    _ -> put_status(conn, 404) |> json(%{data: ""})
  end
end
```
<p>So, when <code>params["state"]</code> is <code>"captured"</code>, your last command is <code>Logger.info</code>, which doesn't return a <code>Plug.Conn</code>.</p>
<p>It seems like you meant to have a <code>case</code> on <code>validate_gift_order</code>'s return:</p>
<pre class="lang-elixir prettyprint-override"><code>def create(conn, params) do
  viewer = GiftActions.get_gift_user!(params["user_id"])

  case params["state"] do
    "captured" ->
      validation = GiftActions.validate_gift_order(viewer, params)
      Logger.info("Request is validated sending code to #{inspect(viewer.email)}")

      case validation do
        {:ok, id} ->
          put_status(conn, 200)
          |> json(%{data: id})

        _ -> put_status(conn, 404) |> json(%{data: ""})
      end
  end
end
</code>```

Body:
so I'm trying to update a schema by matching the params["state"] on a callback, In my controller, I'm doing something like this.

def create(conn, params) do
  viewer = GiftActions.get_gift_user!(params["user_id"])

  case params["state"] do
    "captured" ->
      GiftActions.validate_gift_order(viewer, params)
      Logger.info("Request is validated sending code to #{inspect(viewer.email)}")

      {:ok, id} ->
        put_status(conn, 200)
        |> json(%{data: id})

      _ -> put_status(conn, 404) |> json(%{data: ""})
  end
end

My function will handle update if params["state"] is captured, like this

def validate_gift_order(viewer, attrs) do
 {:ok, gift_order} = __MODULE__.get_gift_by_payment_id(viewer, attrs["id"])

 gift_order
 |> GiftOrders.changeset(%{state: attrs["state"]})
 |> Repo.update()
end

Everything work's fine but in the end I'm failing to return Plug.Conn. Error is saying

[error] #PID<0.5693.0> running VWeb.Endpoint (connection #PID<0.5692.0>, stream id 1) terminated
Server: localhost:4000 (http)
Request: POST /api/v1/gift-callback?user_id=#######
** (exit) an exception was raised:
    ** (RuntimeError) expected action/2 to return a Plug.Conn, all plugs must receive a connection (conn) and return a connection, got: :ok
        (viavolo 0.1.0) lib/v_web/controllers/gif_callback_controller.ex:1: VWeb.GiftCallbackController.phoenix_controller_pipeline/2
        (phoenix 1.5.9) lib/phoenix/router.ex:352: Phoenix.Router.__call__/2
        (viavolo 0.1.0) lib/viavolo_web/endpoint.ex:1: ViavoloWeb.Endpoint.plug_builder_call/2
        (viavolo 0.1.0) lib/viavolo_web/endpoint.ex:1: VWeb.Endpoint."call (overridable 3)"/2
        (viavolo 0.1.0) lib/plug/debugger.ex:136: VWeb.Endpoint."call (overridable 4)"/2
        (viavolo 0.1.0) lib/v_web/endpoint.ex:1: VWeb.Endpoint.call/2

and I'm not entirely sure why? What I'm I supposed to return here?

Body:
Your code is indented wrong, which makes me think you think you have another case statement. Here is the correct indentation for your code:

def create(conn, params) do
  viewer = GiftActions.get_gift_user!(params["user_id"])

  case params["state"] do
    "captured" ->
      GiftActions.validate_gift_order(viewer, params)
      Logger.info("Request is validated sending code to #{inspect(viewer.email)}")

    {:ok, id} ->
      put_status(conn, 200)
      |> json(%{data: id})

    _ -> put_status(conn, 404) |> json(%{data: ""})
  end
end

So, when params["state"] is "captured", your last command is Logger.info, which doesn't return a Plug.Conn.

It seems like you meant to have a case on validate_gift_order's return:

def create(conn, params) do
  viewer = GiftActions.get_gift_user!(params["user_id"])

  case params["state"] do
    "captured" ->
      validation = GiftActions.validate_gift_order(viewer, params)
      Logger.info("Request is validated sending code to #{inspect(viewer.email)}")

      case validation do
        {:ok, id} ->
          put_status(conn, 200)
          |> json(%{data: id})

        _ -> put_status(conn, 404) |> json(%{data: ""})
      end
  end
end


问:
Using autotokenizer for question answering task
I have trained this tokenizer

I have a question answering task using T5 and I need the question and context to be tokenized as T5Tokenizer do. I mean quesion_ids</s>context_ids</s><pad>  I did the following

```<code>tokenizer = AutoTokenizer.from_pretrained(path_to_tokenizer_json_file, config=AutoConfig.from_pretrained(path_to_model_config))
query_tok = 'Do you go to school?'
doc_tok = 'What could be a second sequence to the uninteresting text, What could \
           be a second sequence to the uninteresting text'

query_tok = " ".join(query_tok.split()[:min(5,len(query_tok.split()))])
doc_tok = " ".join(doc_tok.split()[:min(9,len(doc_tok.split()))])
print("query_tok: ", query_tok)
print("doc_tok: ", doc_tok)

ids = tokenizer(
      query_tok+'</s>',
      doc_tok+'</s>',
      max_length=15,
      padding='max_length',
      truncation="only_second",   #   need to experiement
      return_attention_mask=True,
      add_special_tokens=True,
      return_tensors="pt"
      )
print("ids: ",ids)
print("ids shape: ",ids['input_ids'].shape)

print("Len ids: ",len(ids['input_ids'].flatten()), len(ids['input_ids'].flatten()) - 9)

print(tokenizer.decode([id for id in ids['input_ids'].flatten()]))
</code>```

the result was

```<code>> query_tok:  Do you go to school?
> doc_tok:  What could be a second sequence to the uninteresting
> ids:  {'input_ids': tensor([[   3,   11,   36,  316,  475,   16,  156,  187,    1,  219,  312,   63,
>             3,    8,  114, 1906,   16,    4,  352, 6347,  483,   38,    0,    0,
>             0]]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
>          0]])}
> ids shape:  torch.Size([1, 25])
> Len ids:  25 16
> do you go to school?</s> what could be a second sequence to the uninteresting<pad><pad><pad>
>
</code>```

How to make the tokenizer add  to the end of the context before padding or after truncation?

答:
Ok, for those who want to use the pretrained tokenizer in question answering tasks it can be done for one example as follows:</p>
```<code>if (ids['input_ids'] == 0).nonzero(as_tuple=True)[1].nelement() == 0:
    ids['input_ids'][0][-1] = 1
else :
    idx = (ids['input_ids'] == 0).nonzero(as_tuple=True)[1][0]
    ids['input_ids'][0][idx] = 1
    ids['attention_mask'][0][idx] = 1
</code>```

Body:
I have trained this tokenizer

I have a question answering task using T5 and I need the question and context to be tokenized as T5Tokenizer do. I mean quesion_ids</s>context_ids</s><pad>  I did the following

tokenizer = AutoTokenizer.from_pretrained(path_to_tokenizer_json_file, config=AutoConfig.from_pretrained(path_to_model_config))
query_tok = 'Do you go to school?'
doc_tok = 'What could be a second sequence to the uninteresting text, What could \
           be a second sequence to the uninteresting text'

query_tok = " ".join(query_tok.split()[:min(5,len(query_tok.split()))])
doc_tok = " ".join(doc_tok.split()[:min(9,len(doc_tok.split()))])
print("query_tok: ", query_tok)
print("doc_tok: ", doc_tok)

ids = tokenizer(
      query_tok+'</s>',
      doc_tok+'</s>',
      max_length=15,
      padding='max_length',
      truncation="only_second",   #   need to experiement
      return_attention_mask=True,
      add_special_tokens=True,
      return_tensors="pt"
      )
print("ids: ",ids)
print("ids shape: ",ids['input_ids'].shape)

print("Len ids: ",len(ids['input_ids'].flatten()), len(ids['input_ids'].flatten()) - 9)

print(tokenizer.decode([id for id in ids['input_ids'].flatten()]))

the result was

> query_tok:  Do you go to school?
> doc_tok:  What could be a second sequence to the uninteresting
> ids:  {'input_ids': tensor([[   3,   11,   36,  316,  475,   16,  156,  187,    1,  219,  312,   63,
>             3,    8,  114, 1906,   16,    4,  352, 6347,  483,   38,    0,    0,
>             0]]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
>          0]])}
> ids shape:  torch.Size([1, 25])
> Len ids:  25 16
> do you go to school?</s> what could be a second sequence to the uninteresting<pad><pad><pad>
>

How to make the tokenizer add  to the end of the context before padding or after truncation?

Body:
Ok, for those who want to use the pretrained tokenizer in question answering tasks it can be done for one example as follows:

if (ids['input_ids'] == 0).nonzero(as_tuple=True)[1].nelement() == 0:
    ids['input_ids'][0][-1] = 1
else :
    idx = (ids['input_ids'] == 0).nonzero(as_tuple=True)[1][0]
    ids['input_ids'][0][idx] = 1
    ids['attention_mask'][0][idx] = 1


问:
How to make sure a line of code is executed after another is completed?
I have a viewControl called PostViewController which has a UITableView of posts. I also have a class called PostCell which defines the UITableViewCell. I made a button function in PostCell called likeButtonClicked to favour a post similar to twitter.

```<code>@IBAction func likesButtonClicked(_ sender: Any) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "likeButtonClicked"), object: nil, userInfo: ["cell":self, "likesButton":likesButton!]) }
</code>```

This is to pass the cell indexPath and the button name to PostViewController. I need indexPath to increase the likes by 1 and the button name to change its image to pink when post is favoured.

I then subscribed to the notification in viewDidLoad of PostViewController.

```<code> NotificationCenter.default.addObserver(self, selector: #selector(postLiked), name: NSNotification.Name(rawValue: "likeButtonClicked"), object: nil)
</code>```

I then wrote this function in the same viewController

```<code>  @objc func postLiked(notification: Notification){
    if let cell = notification.userInfo?["cell"] as? UITableViewCell{
        let likesButton = notification.userInfo?["likesButton"] as? SpringButton
        if let indexPath = postsTableView.indexPath(for: cell){
            let post = posts[indexPath.row]
            postId = post.id
            PostAPI.getPostById(postId: postId) { post in
                //Check if the same post were already favoured.
                if !self.liked || self.oldPostId != self.postId{
                    self.newLikes = post.likes + 1
                    self.liked = true
                    self.oldPostId = self.postId
                }else{
                    self.newLikes = self.newLikes - 1
                    self.liked = false
                }
                PostAPI.favourPost(postId: self.postId, likes: self.newLikes) {
                    PostAPI.getPostById(postId: self.postId) { postResponse in
                        let post = postResponse
                        self.posts[indexPath.row] = post
                        let cellNumber = IndexPath(row: indexPath.row, section: indexPath.section)
                        self.reloadRowData(cellNumber: cellNumber){
                            if !self.liked{
                                likesButton?.tintColor = .systemPink
                            }else{
                                likesButton?.tintColor = .darkGray
                            }
                        }
                    }
                }
            }
        }
    }
}
func reloadRowData(cellNumber: IndexPath, completion: @escaping () -> ()) {
    self.postsTableView.reloadRows(at: [cellNumber], with: .none)
    completion()
}

</code>```

Please tell me why the last 4 lines of postLiked function is executed before reloadRowData function, which causes the button to change its color to pink then returns immediately to gray when it should stay pink.

Any help will be most appreciated.
Thank you.

答:
I expect the specific problem is your call to reloadRows. As the docs note:

Reloading a row causes the table view to ask its data source for a new cell for that row. The table animates that new cell in as it animates the old row out. Call this method if you want to alert the user that the value of a cell is changing. If, however, notifying the user is not important—that is, you just want to change the value that a cell is displaying—you can get the cell for a particular row and set its new value.

So this is likely creating an entirely new cell, and then the later code modifies the old cell that is being removed from the table. (So you see the change, and then the cell is removed and replaced.)

I would start by getting rid of the entire reloadRowData call.

Generally, though, this code is fragile, and I'd redesign it. The cell should take care of setting the tint colors itself based on the data. You generally shouldn't be reaching into a cell and manipulating its subviews. This will cause you a problem when cells are recycled (for example, when this scrolls off screen). All the configuration should be done in cellForRow(at:), and the cell should observe its Post and update itself when there are changes.

Data should live in the Model. The View should observe the Model and react. The Model should not reach into the View and manipulate anything.

As a side: your reloadRowData looks async, but it's not. There's no reason for a completion handler. It could just call return.

Body:
I have a viewControl called PostViewController which has a UITableView of posts. I also have a class called PostCell which defines the UITableViewCell. I made a button function in PostCell called likeButtonClicked to favour a post similar to twitter.

@IBAction func likesButtonClicked(_ sender: Any) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "likeButtonClicked"), object: nil, userInfo: ["cell":self, "likesButton":likesButton!]) }

This is to pass the cell indexPath and the button name to PostViewController. I need indexPath to increase the likes by 1 and the button name to change its image to pink when post is favoured.

I then subscribed to the notification in viewDidLoad of PostViewController.

 NotificationCenter.default.addObserver(self, selector: #selector(postLiked), name: NSNotification.Name(rawValue: "likeButtonClicked"), object: nil)

I then wrote this function in the same viewController

  @objc func postLiked(notification: Notification){
    if let cell = notification.userInfo?["cell"] as? UITableViewCell{
        let likesButton = notification.userInfo?["likesButton"] as? SpringButton
        if let indexPath = postsTableView.indexPath(for: cell){
            let post = posts[indexPath.row]
            postId = post.id
            PostAPI.getPostById(postId: postId) { post in
                //Check if the same post were already favoured.
                if !self.liked || self.oldPostId != self.postId{
                    self.newLikes = post.likes + 1
                    self.liked = true
                    self.oldPostId = self.postId
                }else{
                    self.newLikes = self.newLikes - 1
                    self.liked = false
                }
                PostAPI.favourPost(postId: self.postId, likes: self.newLikes) {
                    PostAPI.getPostById(postId: self.postId) { postResponse in
                        let post = postResponse
                        self.posts[indexPath.row] = post
                        let cellNumber = IndexPath(row: indexPath.row, section: indexPath.section)
                        self.reloadRowData(cellNumber: cellNumber){
                            if !self.liked{
                                likesButton?.tintColor = .systemPink
                            }else{
                                likesButton?.tintColor = .darkGray
                            }
                        }
                    }
                }
            }
        }
    }
}
func reloadRowData(cellNumber: IndexPath, completion: @escaping () -> ()) {
    self.postsTableView.reloadRows(at: [cellNumber], with: .none)
    completion()
}

Please tell me why the last 4 lines of postLiked function is executed before reloadRowData function, which causes the button to change its color to pink then returns immediately to gray when it should stay pink.

Any help will be most appreciated.
Thank you.


问:
Does "return await" makes any difference?
Is there any difference between

```<code>const foo = async () => {
  // some other code that uses await
  return await bar()
}
</code>```

and

```<code>const foo = async () => {
  // some other code that uses await
  return bar()
}
</code>```

Where bar is a function that returns a promise.

Is the await redundant or does it make any difference?

答:
Yes.

If the function bar() returns a Promise, in the second case foo will return a pending Promise (a Promise that has not yet resolved). In the first case, foo will return the data the Promise resolved with after waiting for the Promise to resolve

Body:
Is there any difference between

const foo = async () => {
  // some other code that uses await
  return await bar()
}

and

const foo = async () => {
  // some other code that uses await
  return bar()
}

Where bar is a function that returns a promise.

Is the await redundant or does it make any difference?


问:
Convert an array into nested Object
For exemple I have arr

```<code>  var arr = [
    {
     nID: 1,
     sLogin: 'user1',
     sParent: ''
    },
    {
     nID: 2,
     sLogin: 'user2',
     sParent: 'user1'
    },{
     nID: 3,
     sLogin: 'user3',
     sParent: ''
    },
 ]
</code>```

And I need to make an Obj that's gonna look like this

```<code>{
 "user1": {
     nID: 1,
     sLogin: 'user1',
     sParent: '',
     oChild: {
       "user2": {
         nID: 2,
         sLogin: 'user2',
         sParent: 'user1'
       }
    }
  },
  "user3": {
     nID: 3,
     sLogin: 'user3',
     sParent: ''}

}
</code>```

We need to track "sLogin" and "sParent" and if it matches we should set into "oChild" to the parent's object and remove from the main

答:
First I created a mapping object for users that have a parent so that I can easily pick the child from the mapping object. It will look like this

```<code>{
  user2: {
    nID: 2,
    sLogin: "user2",
    sParent: "user1"
  }
}
</code>```

After that i did a reduce on the original array and picked from the mapping when sParentis not an empty string

var arr = [{nID: 1,sLogin: 'user1',sParent: ''},{nID: 2,sLogin: 'user2',sParent: 'user1'},{nID: 3,sLogin: 'user3',sParent: ''},]

const mapping = {}
arr.forEach(el => {if(el.sParent !== '') mapping[el.sLogin]=el})

const res = arr.reduce((acc,curr)=>{
    const {nID,sLogin,sParent} = curr
  if(sParent===''){
    acc[sLogin]=curr
  }
  else{
    acc[sParent]['oChild'] = {}
    acc[sParent]['oChild'][sLogin] = mapping[sLogin]
  }

  return acc;
},{})

console.log(res)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Convert an array into nested Object

Body:
For exemple I have arr

  var arr = [
    {
     nID: 1,
     sLogin: 'user1',
     sParent: ''
    },
    {
     nID: 2,
     sLogin: 'user2',
     sParent: 'user1'
    },{
     nID: 3,
     sLogin: 'user3',
     sParent: ''
    },
 ]

And I need to make an Obj that's gonna look like this

{
 "user1": {
     nID: 1,
     sLogin: 'user1',
     sParent: '',
     oChild: {
       "user2": {
         nID: 2,
         sLogin: 'user2',
         sParent: 'user1'
       }
    }
  },
  "user3": {
     nID: 3,
     sLogin: 'user3',
     sParent: ''}

}

We need to track "sLogin" and "sParent" and if it matches we should set into "oChild" to the parent's object and remove from the main

Body:
First I created a mapping object for users that have a parent so that I can easily pick the child from the mapping object. It will look like this

{
  user2: {
    nID: 2,
    sLogin: "user2",
    sParent: "user1"
  }
}

After that i did a reduce on the original array and picked from the mapping when sParentis not an empty string

var arr = [{nID: 1,sLogin: 'user1',sParent: ''},{nID: 2,sLogin: 'user2',sParent: 'user1'},{nID: 3,sLogin: 'user3',sParent: ''},]

const mapping = {}
arr.forEach(el => {if(el.sParent !== '') mapping[el.sLogin]=el})

const res = arr.reduce((acc,curr)=>{
    const {nID,sLogin,sParent} = curr
  if(sParent===''){
    acc[sLogin]=curr
  }
  else{
    acc[sParent]['oChild'] = {}
    acc[sParent]['oChild'][sLogin] = mapping[sLogin]
  }

  return acc;
},{})

console.log(res)

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to parse a complex SOAP response in Android
Since two days I am trying to consume a WCF (.NET) Soap Service and serialize it's response without success. I am getting a correct response (I had to put it on pastebin: SOAP Response Example), but KSOAP2 is not able to handle .NET Datasets correctly.
I already consultated various articles about this specific problem, but none has a .NET Dataset to handle. The main article which gave guideance was an
article by IBM "Working with XML on Android"

I tried following steps to parse my data without success:

Parsing with SAX (android) -> Seems not to work with this complex document because of the different namespaces.

with DOM Object(android) -> NullPointerExeption (dooh!)

with Digester (dom4j) -> NullPointerException (arggh!)

method suggested by helloandroid.com "Using ksoap2 for android, and parsing output data"

Some questions:
- The returned response is a normal XML, but actually it includes a .NET Dataset. Has anyone had success to parse data out of such a response?
- Is there a way to make KSOAP2 not to trying to parse the data? It returns a rubbish SoapObject, which is unreadable. I would like just the contents of the SOAP body. Is there a way to intercept that?
- Do you have any other hint?

答: I have the same problem. First I used vtd-xml. It was working without problems but it is a bit slow. Now I switched to standard Java SAX (not Android SAX implementation) and it works ok.</p>

ContentLicense: CC BY-SA 2.5


问:
React native router (V6) is not routing to a different page based on the endpoint, instead shows the same page for both routes
```<code>import {NativeRouter, Route, Routes} from 'react-router-native';
import Loader from  '../components/Loader';
import Home from '../components/Home';

export default function RoutingFunc(){
  return(
    <NativeRouter>
      <Routes>
        <Route path='/home' element={<Home />} />
        <Route path='/' element={<Loader />} />
      </Routes>
    </NativeRouter>
  )
}
</code>```

For both the routes / and /home ,the Loader component is being rendered

Loader Component

```<code>import { Box, Flex, Heading,Text } from "native-base";
import {Image} from 'react-native';

export default function Loader(){
  console.log(window.location.href)
  return(
    <Flex flexDirection="column"
    justifyContent="center"
    alignItems="center"
    h="100%"
    w="100vw"
    position="relative"
    backgroundColor="#25A9B0">
      <Heading color="white" fontSize="5xl">page<Text color="#05386B">in</Text></Heading>
      <Box position="absolute"
      top="55%"
      left="46%"
      backgroundColor="#36BAC2"
      w="45"
      h="45"
      borderRadius="full"
      borderColor="#05386B"
      borderWidth="2">
      </Box>
      <Box position="absolute"
      top="58%"
      left="49%"
      backgroundColor="#36BAC2"
      w="45"
      h="45"
      borderRadius="full"
      borderColor="#05386B"
      borderWidth="2">
      </Box>
      <Image source={require('../../resource/logo1.png')} />
      {/* <Text position="absolute" bottom="5%" fontSize="md">Randomized Text</Text> */}
    </Flex>
  )
}
</code>```

Home Component

```<code>import {View,Text,Dimensions} from "react-native";
import Posts from "./Posts";
import Footer from "./Footer";

export default function Home() {
    return (
        <>
         <View
         style={{display:'flex',
         justifyContent:'center',
         width:'100%',
         height:`${Dimensions.get('window').height}px`,
         flexDirection:"column",
         overflow:'scroll'}}>
           <Posts/>
         </View>
         <Footer/>
        </>

    )
}
</code>```

答:
I think the / is superfluous now for everything but the home route so what happens if you try the path (/home) without /. The matching logic in v6 has improved, so perhaps the below, and it will automatically match the most specific:

```<code>   <NativeRouter>
      <Routes>
        <Route path='home' element={<Home />} />
        <Route path='/' element={<Loader />} />
      </Routes>
    </NativeRouter>
</code>```

Body:
import {NativeRouter, Route, Routes} from 'react-router-native';
import Loader from  '../components/Loader';
import Home from '../components/Home';

export default function RoutingFunc(){
  return(
    <NativeRouter>
      <Routes>
        <Route path='/home' element={<Home />} />
        <Route path='/' element={<Loader />} />
      </Routes>
    </NativeRouter>
  )
}

For both the routes / and /home ,the Loader component is being rendered

Loader Component

import { Box, Flex, Heading,Text } from "native-base";
import {Image} from 'react-native';

export default function Loader(){
  console.log(window.location.href)
  return(
    <Flex flexDirection="column"
    justifyContent="center"
    alignItems="center"
    h="100%"
    w="100vw"
    position="relative"
    backgroundColor="#25A9B0">
      <Heading color="white" fontSize="5xl">page<Text color="#05386B">in</Text></Heading>
      <Box position="absolute"
      top="55%"
      left="46%"
      backgroundColor="#36BAC2"
      w="45"
      h="45"
      borderRadius="full"
      borderColor="#05386B"
      borderWidth="2">
      </Box>
      <Box position="absolute"
      top="58%"
      left="49%"
      backgroundColor="#36BAC2"
      w="45"
      h="45"
      borderRadius="full"
      borderColor="#05386B"
      borderWidth="2">
      </Box>
      <Image source={require('../../resource/logo1.png')} />
      {/* <Text position="absolute" bottom="5%" fontSize="md">Randomized Text</Text> */}
    </Flex>
  )
}

Home Component

import {View,Text,Dimensions} from "react-native";
import Posts from "./Posts";
import Footer from "./Footer";

export default function Home() {
    return (
        <>
         <View
         style={{display:'flex',
         justifyContent:'center',
         width:'100%',
         height:`${Dimensions.get('window').height}px`,
         flexDirection:"column",
         overflow:'scroll'}}>
           <Posts/>
         </View>

        </>

    )
}

Body:
I think the / is superfluous now for everything but the home route so what happens if you try the path (/home) without /. The matching logic in v6 has improved, so perhaps the below, and it will automatically match the most specific:

   <NativeRouter>
      <Routes>
        <Route path='home' element={<Home />} />
        <Route path='/' element={<Loader />} />
      </Routes>
    </NativeRouter>


问:
Is there a fast way to generate a dict of the alphabet in Python?
I want to generate a dict with the letters of the alphabet as the keys, something like

```<code>letter_count = {'a': 0, 'b': 0, 'c': 0}
</code>```

what would be a fast way of generating that dict, rather than me having to type it in?

Thanks for your help.

EDIT

Thanks everyone for your solutions :)

nosklo's
solution is probably the shortest

Also, thanks for reminding me about the Python string module.

答: Construct a dict of words from alphabetical order A to zop each words adjectives, adverbs as to be included. Convert the list of adjective and adverbs from dict to list</p>

OwnerDisplayName: Casey

Body:
I want to generate a dict with the letters of the alphabet as the keys, something like

letter_count = {'a': 0, 'b': 0, 'c': 0}

what would be a fast way of generating that dict, rather than me having to type it in?

Thanks for your help.

EDIT

Thanks everyone for your solutions :)

nosklo's
solution is probably the shortest

Also, thanks for reminding me about the Python string module.

LastEditorDisplayName: cdleary


问:
Advantages and disadvantages of GUID / UUID database keys
I've worked on a number of database systems in the past where moving entries between databases would have been made a lot easier if all the database keys had been GUID / UUID values. I've considered going down this path a few times, but there's always a bit of uncertainty, especially around performance and un-read-out-over-the-phone-able URLs.

Has anyone worked extensively with GUIDs in a database? What advantages would I get by going that way, and what are the likely pitfalls?

答:
One thing not mentioned so far: UUIDs make it much harder to profile data

For web apps at least, it's common to access a resource with the id in the url, like stackoverflow.com/questions/45399. If the id is an integer, this both

provides information about the number of questions (ie September 5th, 2008, the 45,399th question was asked)

provides a leverage point to iterate through questions (what happens when I increment that by 1? I open the next asked question)

From the first point, I can combine the timestamp from the question and the number to profile how frequently questions are asked and how that changes over time. this matters less on a site like Stack Overflow, with publicly available information, but, depending on context, this may expose sensitive information.

For example, I am a company that offers customers a permissions gated portal. the address is portal.com/profile/{customerId}. If the id is an integer, you could profile the number of customers regardless of being able to see their information by querying for lastKnownCustomerCount + 1 regularly, and checking if the result is 404 - NotFound (customer does not exist) or 403 - Forbidden (customer does exist, but you do not have access to view).

UUIDs non-sequential nature mitigate these issues. This isn't a garunted to prevent profiling, but it's a start.

OwnerDisplayName: Matt Sheppard


问:
How to trigger a rollout restart on deployment resource from controller-runtime
I have been using kubebuilder for writing custom controller, and aware of Get(), Update(), Delete() methods that it provides. But Now I am looking for a method which mimic the behaviour of kubectl rollout restart deployment. If there is no such direct method then I am looking for correct way to mimic the same.

type CustomReconciler struct {
    client.Client
    Log    logr.Logger
    Scheme *runtime.Scheme
}

func (r *CustomReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    configMap := &v1.ConfigMap{}
    err = r.Get(ctx, req.namespacedName, configMap)
    if err != nil {
        logger.Error(err, "Failed to GET configMap")
        return ctrl.Result{}, err
    }
```
<p>Say in above code I read a deployment name from the configmap and rollout restart the same as follows:</p>
<pre class="lang-golang prettyprint-override"><code>    val := configMap.Data["config.yml"]
    config := Config{}
    if err := yaml.Unmarshal([]byte(val), &config); err != nil {
        logger.Error(err, "failed to unmarshal config data")
        return ctrl.Result{}, err
    }

    // Need equivalent of following
    // r.RolloutRestart(config.DeploymentName)
</code>```

答:
In all cases where you wish to replicate kubectl behavior, the answer is always to increase its verbosity and it'll show you exactly -- sometimes down to the wire payloads -- what it is doing.

For rollout restart, one will find that it just bumps an annotation on the Deployment/StatefulSet/whatever and that causes the outer object to be "different," and triggering a reconciliation run

You can squat on their annotation, or you can make up your own, or you can use a label change -- practically any "meaningless" change will do

Body:
I have been using kubebuilder for writing custom controller, and aware of Get(), Update(), Delete() methods that it provides. But Now I am looking for a method which mimic the behaviour of kubectl rollout restart deployment. If there is no such direct method then I am looking for correct way to mimic the same.

type CustomReconciler struct {
    client.Client
    Log    logr.Logger
    Scheme *runtime.Scheme
}

func (r *CustomReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    configMap := &v1.ConfigMap{}
    err = r.Get(ctx, req.namespacedName, configMap)
    if err != nil {
        logger.Error(err, "Failed to GET configMap")
        return ctrl.Result{}, err
    }

Say in above code I read a deployment name from the configmap and rollout restart the same as follows:

    val := configMap.Data["config.yml"]
    config := Config{}
    if err := yaml.Unmarshal([]byte(val), &config); err != nil {
        logger.Error(err, "failed to unmarshal config data")
        return ctrl.Result{}, err
    }

    // Need equivalent of following
    // r.RolloutRestart(config.DeploymentName)


问:
React hooks one checkbox checked to uncheck other checkbox
Hi I have a parent component which contains a bunch child components which are checkboxes.
parent component is something like this inside:

```<code>const [items, setItems] = useState([
{
    id:1,
    selected: false,
},
{
    id:2,
    selected: false,
}
]);
const changeSelected = (id) =>
  {
    items.forEach((item)=>
    {
      if (item.id === id)
      {
        item.selected = !item.selected;
      }
      else{
        item.selected = false;
      }
    })
  }
return(
    <div>
        {items.map((item)=>{
            <Child item={item} changeSelected={changeSelected}/>
        })}
    </div>
)
</code>```

and in the child component, it has something like this inside:

```<code>return(
    <div>
        <input type="checkbox" checked={props.item.selected} onChange={()=>{props.changeSelected(props.item.id)}} />
    </div>
)
</code>```

I know partially this isnt working is because useState is async but I dont know what to do to make it work, or if I should try a different approach? Thank you

答:
You are not updating the state anywhere. You should make a copy of the array and then change the object you want to:

```<code>const changeSelected = (id) =>
  { let newItems = [];
    items.forEach((item)=>
    {
      if (item.id === id)
      {
        newItems.push({  id : item.id , selected : item.selected });
      }
      else{
        newItems.push({  id : item.id , selected : false });
      }
    })
setItems(newItems);
  }
</code>```

Call setItems to set it.

Note:
Not related to the question but you should use unique keys when iterating over list.

```<code>{items.map((item)=>{
            <Child key={item.id} item={item} changeSelected={changeSelected}/>
        })}
</code>```

Body:
Hi I have a parent component which contains a bunch child components which are checkboxes.
parent component is something like this inside:

const [items, setItems] = useState([
{
    id:1,
    selected: false,
},
{
    id:2,
    selected: false,
}
]);
const changeSelected = (id) =>
  {
    items.forEach((item)=>
    {
      if (item.id === id)
      {
        item.selected = !item.selected;
      }
      else{
        item.selected = false;
      }
    })
  }
return(

        {items.map((item)=>{
            <Child item={item} changeSelected={changeSelected}/>
        })}

)

and in the child component, it has something like this inside:

return(

        <input type="checkbox" checked={props.item.selected} onChange={()=>{props.changeSelected(props.item.id)}} />

)

I know partially this isnt working is because useState is async but I dont know what to do to make it work, or if I should try a different approach? Thank you

Body:
You are not updating the state anywhere. You should make a copy of the array and then change the object you want to:

const changeSelected = (id) =>
  { let newItems = [];
    items.forEach((item)=>
    {
      if (item.id === id)
      {
        newItems.push({  id : item.id , selected : item.selected });
      }
      else{
        newItems.push({  id : item.id , selected : false });
      }
    })
setItems(newItems);
  }

Call setItems to set it.

Note:
Not related to the question but you should use unique keys when iterating over list.

{items.map((item)=>{
            <Child key={item.id} item={item} changeSelected={changeSelected}/>
        })}


问:
To use Doctrine entity attributes you'll need PHP 8, doctrine/orm 2.9, doctrine/doctrine-bundle 2.4 and symfony/framework-bundle 5.2
I have a problem on my Symfony project version 4.4.9, with PHP 8. when I run php bin/console make:entity these errors appear:

To use Doctrine entity attributes you'll need PHP 8, doctrine/orm 2.9, doctrine/doctrine-bundle 2.4 and
symfony/framework-bundle 5.2.

composer.json

```<code>    "php": ">=7.1.3",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "doctrine/annotations": "^1.13",
    "doctrine/doctrine-bundle": "^2.5",
    "doctrine/doctrine-migrations-bundle": "^3.2",
    "doctrine/orm": "2.9.6",
    "symfony/console": "4.4.*",
    "symfony/dotenv": "4.4.*",
    "symfony/flex": "^1.3.1",
    "symfony/framework-bundle": "4.4.*",
    "symfony/proxy-manager-bridge": "4.4.*",
    "symfony/yaml": "4.4.*"
},
</code>```

and my PHP Version : 8.1

答:
Seems to be an issue running Symfony 4.4 + Symfony Maker Bundle under under PHP 8+.

I can reproduce the issue with a project created from scratch on PHP 8.

$ composer create-project symfony/skeleton maker-annotations ^4.4.0
$ cd maker-annotations
$ composer require doctrine symfony/maker-bundle
$ bin/console make:entity
```

This will consistently error out under PHP8. Funnily enough, you can call make:entity again over the same entity, and it will appear to work... but it will error out for some other reason in the end.

The only solution I could find was to downgrade PHP to 7.4. If you are using a version of Symfony that old, it might be safer to use an older version of PHP as well in any case.

Or better yet, simply upgrade your Symfony version to 5.2.

Body:
I have a problem on my Symfony project version 4.4.9, with PHP 8. when I run php bin/console make:entity these errors appear:

To use Doctrine entity attributes you'll need PHP 8, doctrine/orm 2.9, doctrine/doctrine-bundle 2.4 and
symfony/framework-bundle 5.2.

composer.json

    "php": ">=7.1.3",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "doctrine/annotations": "^1.13",
    "doctrine/doctrine-bundle": "^2.5",
    "doctrine/doctrine-migrations-bundle": "^3.2",
    "doctrine/orm": "2.9.6",
    "symfony/console": "4.4.*",
    "symfony/dotenv": "4.4.*",
    "symfony/flex": "^1.3.1",
    "symfony/framework-bundle": "4.4.*",
    "symfony/proxy-manager-bridge": "4.4.*",
    "symfony/yaml": "4.4.*"
},

and my PHP Version : 8.1

Body:
Seems to be an issue running Symfony 4.4 + Symfony Maker Bundle under under PHP 8+.

I can reproduce the issue with a project created from scratch on PHP 8.

$ composer create-project symfony/skeleton maker-annotations ^4.4.0
$ cd maker-annotations
$ composer require doctrine symfony/maker-bundle
$ bin/console make:entity

This will consistently error out under PHP8. Funnily enough, you can call make:entity again over the same entity, and it will appear to work... but it will error out for some other reason in the end.

The only solution I could find was to downgrade PHP to 7.4. If you are using a version of Symfony that old, it might be safer to use an older version of PHP as well in any case.

Or better yet, simply upgrade your Symfony version to 5.2.


问:
Write jquery plugin and "$.something" construct
Currently i'm working on a jquery plugin and looking at other plugin code i found a common way to write it passing throught an object, somethng like :

```<code>$.fn.myplugin = function(method){
    //... some code
    object = new $.myobject(param);
    //... other code

    // myobject definition
    $.myobject = function(param){
        //.... my object code
    }
}
</code>```

I can't understand how works $.myobject definition and why many developers use it to define their plugins.

Could you give some info and tutorial/links to documentation if possibile ?

答:
The true power of jQuery lies in the ability to easily and quickly select and operate on
DOM elements. Luckily, we can extend that power by adding wrapper methods of our
own that manipulate selected DOM elements as we deem appropriate. By adding wrap-per methods, we automatically gain the use of the powerful jQuery selectors to pick
and choose which elements are to be operated on without having to do all the work
ourselves.

 Given what we know about JavaScript, we probably could have figured out on our
own how to add utility functions to the $ namespace, but that’s not necessarily true of
wrapper functions. There’s a  tidbit of jQuery-specific information that we need to
know: to add wrapper methods to jQuery, we must assign them as properties to an
object named fn in the $ namespace.
 The general pattern for creating a wrapper function is

```<code>$.fn.wrapperFunctionName = function(params){function-body};
</code>```

Let’s concoct a trivial wrapper method to set the color of the matched DOM elements
to blue:

```<code>(function($){
  $.fn.makeItBlue = function() {
    return this.css('color','blue');
  };
})(jQuery);
</code>```

http://www.manning.com/bibeault2/

Body:
Currently i'm working on a jquery plugin and looking at other plugin code i found a common way to write it passing throught an object, somethng like :

$.fn.myplugin = function(method){
    //... some code
    object = new $.myobject(param);
    //... other code

    // myobject definition
    $.myobject = function(param){
        //.... my object code
    }
}

I can't understand how works $.myobject definition and why many developers use it to define their plugins.

Could you give some info and tutorial/links to documentation if possibile ?

Body:
The true power of jQuery lies in the ability to easily and quickly select and operate on
DOM elements. Luckily, we can extend that power by adding wrapper methods of our
own that manipulate selected DOM elements as we deem appropriate. By adding wrap-per methods, we automatically gain the use of the powerful jQuery selectors to pick
and choose which elements are to be operated on without having to do all the work
ourselves.

 Given what we know about JavaScript, we probably could have figured out on our
own how to add utility functions to the $ namespace, but that’s not necessarily true of
wrapper functions. There’s a  tidbit of jQuery-specific information that we need to
know: to add wrapper methods to jQuery, we must assign them as properties to an
object named fn in the $ namespace.
 The general pattern for creating a wrapper function is

$.fn.wrapperFunctionName = function(params){function-body};

Let’s concoct a trivial wrapper method to set the color of the matched DOM elements
to blue:

(function($){
  $.fn.makeItBlue = function() {
    return this.css('color','blue');
  };
})(jQuery);

http://www.manning.com/bibeault2/


问:
Writing to C program using GO but C program doesn't stop at scanf()
In these snippets the go program tries to write to C program's stdin. The problem is that the c program starts an infinite loop after the go loop finishes.

main.c

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

int main(){
    int age;
    char name[8];

    for(;;)
    {
    scanf(" %s : %d\n",&name, &age);
    printf("%s : %d\n",name, age);
    }
    return 0;
}
</code>```

run/main.go

```<code>func main() {

    proc := exec.Command("../main")
    stdin, err := proc.StdinPipe()
    if err != nil {
        fmt.Println(err)
    }

    defer stdin.Close()

    proc.Stdout = os.Stdout
    proc.Stderr = os.Stderr

    fmt.Println("START")
    if err = proc.Start(); err != nil {
        log.Fatal("An error occured: ", err)
    }

    for i := 0; i < 500; i++ {
        io.WriteString(stdin, fmt.Sprintf("hello : %d\n", i))
        //How to wait here and read from printf()?
    }

    //proc.Process.Kill() Here proc gets killed too fast

    fmt.Println("END")
}
</code>```

When killed, process doesn't complete it's output

Output

```<code>START
END
hello : 497
hello : 498
hello : 499
hello : 499
</code>```

Output Expected

```<code>START
....
hello : 497
hello : 498
hello : 499
END
</code>```

答:
After reading the comments and few more searching I have worked it out.
On C program I removed \n from scanf() and added fflush(stdout) after printf.
According to this page I changed them to these:</p>
```<code>int main(){
    int age;
    char name[8];

    int ret;

    for(;;)
    {
    ret= scanf("%s : %d",&name, &age);
    if (ret == -1) {
        break;
    }
    printf("%s : %d\n",name, age);

    fflush(stdout);
    }

    return 0;
}
</code>```
```<code>func main(){
    proc := exec.Command("../main")

    stdin, err := proc.StdinPipe()
    if err != nil {
        fmt.Println(err)
    }

    reader, err := proc.StdoutPipe()
    if err != nil {
        fmt.Println(err)
        return
    }

    scanner := bufio.NewScanner(reader)
    resp := make(chan string)

    go func() {
        for scanner.Scan() {
            resp <- scanner.Text()
        }
    }()

    err = proc.Start()
    if err != nil {
        fmt.Fprintln(err)
        return
    }
    fmt.Println("START")

    for i := 0; i < 500; i++ {
        io.WriteString(stdin, fmt.Sprintf("hello : %d\n", i))

        v := <-resp
        print(v+"\n")

    }

    err = proc.Process.Kill()

    if err != nil {
        fmt.Fprintln(err)
        return
    }
    fmt.Println("END")

}
</code>```

Body:
In these snippets the go program tries to write to C program's stdin. The problem is that the c program starts an infinite loop after the go loop finishes.

main.c

#include <stdio.h>
#include <stdlib.h>

int main(){
    int age;
    char name[8];

    for(;;)
    {
    scanf(" %s : %d\n",&name, &age);
    printf("%s : %d\n",name, age);
    }
    return 0;
}

run/main.go

func main() {

    proc := exec.Command("../main")
    stdin, err := proc.StdinPipe()
    if err != nil {
        fmt.Println(err)
    }

    defer stdin.Close()

    proc.Stdout = os.Stdout
    proc.Stderr = os.Stderr

    fmt.Println("START")
    if err = proc.Start(); err != nil {
        log.Fatal("An error occured: ", err)
    }

    for i := 0; i < 500; i++ {
        io.WriteString(stdin, fmt.Sprintf("hello : %d\n", i))
        //How to wait here and read from printf()?
    }

    //proc.Process.Kill() Here proc gets killed too fast

    fmt.Println("END")
}

When killed, process doesn't complete it's output

Output

START
END
hello : 497
hello : 498
hello : 499
hello : 499

Output Expected

START
....
hello : 497
hello : 498
hello : 499
END

Body:
After reading the comments and few more searching I have worked it out.
On C program I removed \n from scanf() and added fflush(stdout) after printf.
According to this page I changed them to these:

int main(){
    int age;
    char name[8];

    int ret;

    for(;;)
    {
    ret= scanf("%s : %d",&name, &age);
    if (ret == -1) {
        break;
    }
    printf("%s : %d\n",name, age);

    fflush(stdout);
    }

    return 0;
}

func main(){
    proc := exec.Command("../main")

    stdin, err := proc.StdinPipe()
    if err != nil {
        fmt.Println(err)
    }

    reader, err := proc.StdoutPipe()
    if err != nil {
        fmt.Println(err)
        return
    }

    scanner := bufio.NewScanner(reader)
    resp := make(chan string)

    go func() {
        for scanner.Scan() {
            resp <- scanner.Text()
        }
    }()

    err = proc.Start()
    if err != nil {
        fmt.Fprintln(err)
        return
    }
    fmt.Println("START")

    for i := 0; i < 500; i++ {
        io.WriteString(stdin, fmt.Sprintf("hello : %d\n", i))

        v := <-resp
        print(v+"\n")

    }

    err = proc.Process.Kill()

    if err != nil {
        fmt.Fprintln(err)
        return
    }
    fmt.Println("END")

}


问:
Can another telegram user make me access his bot?
My friend has a tranding bot made with BotFather.

Is there a way to make the bot shared betweeen our account in a way we can use it together?

答:
Bot usernames are unique to each Telegram account and only that account is able to change the settings of the bot.

But you can make use of a bot through its API_TOKEN which you can get from botfather.

It looks like this:

300123900:BARsAbMYBJv5wFhzNJ-Gbx678qpln7IgvzI

If you share the token with anyone, they can use your bot. They will receive an error if they try to use it at the same time (calling getUpdates method from more than one instance would reject the caller except for the first one).

If by sharing you meant using the bot (not developing it), you can't do that unless the bot's developer designs it in a way that multiple Telegram accounts messaging the bot are considered one account.


问:
How do you export a variable from app.js into another route in Node js
i'm using socket.io in my node project and wanted to know how to possibly export the io variable

this is what i have done so far but i get this error: Object #<Object> has no method 'on'

in app.js:

```<code>        var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index')(io);
var users = require('./routes/user');

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4000);

require('./routes/index')(io);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err,
            title: 'error'
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {},
        title: 'error'
    });
});
/*
io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
*/

module.exports = app;
</code>```

in index.js

```<code>var io = require('../app');

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
</code>```

the reason i want export the variable is so that i dont have to define io is index.js like i did in app.js which leads to me basically defining both server and app variable !

I just want to do all my socket.io stuff in the index.js route essentially (except from having to redefine the app, server and io variables in index.js ) !

Hope i have explained my self enough

Thank you !

答: Use "global.io" instead of "var io" in app.js</p>

Body:
i'm using socket.io in my node project and wanted to know how to possibly export the io variable

this is what i have done so far but i get this error: Object #<Object> has no method 'on'

in app.js:

        var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index')(io);
var users = require('./routes/user');

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4000);

require('./routes/index')(io);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err,
            title: 'error'
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {},
        title: 'error'
    });
});
/*
io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
*/

module.exports = app;

in index.js

var io = require('../app');

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

the reason i want export the variable is so that i dont have to define io is index.js like i did in app.js which leads to me basically defining both server and app variable !

I just want to do all my socket.io stuff in the index.js route essentially (except from having to redefine the app, server and io variables in index.js ) !

Hope i have explained my self enough

Thank you !