问:
How to scaffold DbContext with plural DbSet property names in Entity Framework Core?
UPDATE 2023: for modern EF Core versions (.NET 5+), pluralization is enabled by default, as it is shown in the answer https://stackoverflow.com/a/64801660/5112433. The rest of the discussion, while totally relevant at the time given, is nothing more than a history.

Original question:

I use Scaffold-DbContext command in Package Manager Console to create and re-create context and entities for an existed SQL Server database:

```<code>Scaffold-DbContext -provider EntityFramework.MicrosoftSqlServer -connection "my connection string"
</code>```

It works perfectly except one thing: DbSet's have property names in singular form:

```<code>public partial class MyDbContext : DbContext
{
    public virtual DbSet<Request> Request { get; set; }
    public virtual DbSet<RequestHeader> RequestHeader { get; set; }
}
</code>```

I prefer these names to be in plural form (Requests etc.). In addition to web search I checked command syntax:

```<code>get-Help Scaffold-DbContext -detailed
</code>```

And found nothing to change this behaviour. Here is my packages.config:

```<code><packages>
  <package id="EntityFramework.Commands" version="7.0.0-rc1-final" targetFramework="net46" />
  <package id="EntityFramework.Core" version="7.0.0-rc1-final" targetFramework="net46" />
  ...
</packages>
</code>```

How to pluralize DbSet names when scaffolding?

UPDATE 2017-04: DB First scaffolding pluralization is now possible in Entity Framework Core 1.1. Read my answer below for details.

答:
Short Answer

1. Install Package

Install-Package Bricelam.EntityFrameworkCore.Pluralizer

2. Run Scaffold-DbContext Command

Scaffold-DbContext -Connection "Server=<server>;Database=<dbname>;user id=<userid>;password=<pwd>;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Data/EFModels/

Long Answer:

As pointed out by @KalinKrastev in the comments of @natemcmaster's answer. Pluralization in EF Core is possible using a package called Bricelam.EntityFrameworkCore.Pluralizer that can be installed using

in the Package Manager Console (PMC) or

dotnet add package Bricelam.EntityFrameworkCore.Pluralizer

using Dotnet cli.

After installing the package just use the regular Scaffold-DbContext command.

Scaffold-DbContext -Connection "Server=<server>;Database=<dbname>;user id=<userid>;password=<pwd>;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Data/EFModels/ -Force

See More About Bricelam's Pluralizer

Body:
UPDATE 2023: for modern EF Core versions (.NET 5+), pluralization is enabled by default, as it is shown in the answer https://stackoverflow.com/a/64801660/5112433. The rest of the discussion, while totally relevant at the time given, is nothing more than a history.

Original question:

I use Scaffold-DbContext command in Package Manager Console to create and re-create context and entities for an existed SQL Server database:

Scaffold-DbContext -provider EntityFramework.MicrosoftSqlServer -connection "my connection string"

It works perfectly except one thing: DbSet's have property names in singular form:

public partial class MyDbContext : DbContext
{
    public virtual DbSet<Request> Request { get; set; }
    public virtual DbSet<RequestHeader> RequestHeader { get; set; }
}

I prefer these names to be in plural form (Requests etc.). In addition to web search I checked command syntax:

get-Help Scaffold-DbContext -detailed

And found nothing to change this behaviour. Here is my packages.config:

<packages>
  <package id="EntityFramework.Commands" version="7.0.0-rc1-final" targetFramework="net46" />
  <package id="EntityFramework.Core" version="7.0.0-rc1-final" targetFramework="net46" />
  ...
</packages>

How to pluralize DbSet names when scaffolding?

UPDATE 2017-04: DB First scaffolding pluralization is now possible in Entity Framework Core 1.1. Read my answer below for details.


来源: stackexchange

问:
For loop with steps OPL Cplex
I need to write matrices of different dimensions in OPL CPLEX.

Currently, I wrote this for loop :

```<code>{int} row=...;
{int} col=...;
int y[row][col];

execute
{
 for (var i=1; i<=row.size; i+=10){
   for (var j in col){
     y[i][j]=i;
   }
 }
 writeln("y= ",y,
 "/ row = ", row.size,
 "/ col = ", col.size,
 "/ time = ", cplex.getCplexTime());
}
</code>```

Currently, in the scripting log, I obtain as a solution all the matrices (from 1x2 to 100x2).

I would like to compute (and print) only the matrices 1x2, 10x2, 20x2, ..., 90x2 and 100x2.

Essentially I would like to print a matrix every 10 rows (so in total 11 matrices and not 100).

I tried to multiply the row.size per 10 (or divide it per 10 when the row value is 100).

How can I do that ?

UPDATE :

main.mod :

```<code>{int} set1={};
{int} set2={};
int ar[1..100][1..100];

main {
  var source = new IloOplModelSource("sub.mod");
  var cplex = new IloCplex();
  var def = new IloOplModelDefinition(source);
  for(var i=1;i<=30;i++) if (i % 10 == 0) {
    for (var j=1; j<=30; j++) if (j % 10 == 0) {
        var opl = new IloOplModel(def,cplex);
        var data2= new IloOplDataElements();
        data2.row=thisOplModel.set1;
        data2.row.add(i);
        data2.col=thisOplModel.set2;
        data2.col.add(j);
    }
  opl.addDataSource(data2);
  opl.generate();
}
if (cplex.solve()) {
writeln("Solution = " + cplex.getObjValue(),
"/ time = ", cplex.getCplexTime());
} else {
    writeln("No solution");
}
data2.end();
opl.end();
}
</code>```

sub.mod :

```<code>{int} row=...;
{int} col=...;
int y[row][col];

execute {

 for (var i in row) {
     for (var j in col) {
        y[i][j]=i;
    }
 }
    writeln("y= ",y,
//    " / i= ", i,
//  "/ row = ", row,
    "/ col = ", col,
    "/ time = ", cplex.getCplexTime());
}

dvar float x;

maximize x;
subject to {
   x<=sum(i in row, j in col) y[i][j];
}

execute
{
writeln("x=",x);
}
</code>```

Now, I obtain the right values in row = {10, 20, 30} and col = {10, 20, 30} in the main.mod.

In sub.mod row and col are sets. I need to use those values as matrices dimensions. So the first matrix is 10x10, the second 20x20 etc..

How can I access the values inside the set so that I can create those matrices ?

Sorry for the multiple questions but I am really new to CPLEX.

答:
you could use modulo

```<code>range r=1..100;

execute
{
  for(var i in r) if (i % 10==0) writeln(i);
}
</code>```

gives

```<code>10
20
30
40
50
60
70
80
90
100
</code>```

ContentLicense: CC BY-SA 4.0

Title: For loop with steps OPL Cplex

Body:
I need to write matrices of different dimensions in OPL CPLEX.

Currently, I wrote this for loop :

{int} row=...;
{int} col=...;
int y[row][col];

execute
{
 for (var i=1; i<=row.size; i+=10){
   for (var j in col){
     y[i][j]=i;
   }
 }
 writeln("y= ",y,
 "/ row = ", row.size,
 "/ col = ", col.size,
 "/ time = ", cplex.getCplexTime());
}

Currently, in the scripting log, I obtain as a solution all the matrices (from 1x2 to 100x2).

I would like to compute (and print) only the matrices 1x2, 10x2, 20x2, ..., 90x2 and 100x2.

Essentially I would like to print a matrix every 10 rows (so in total 11 matrices and not 100).

I tried to multiply the row.size per 10 (or divide it per 10 when the row value is 100).

How can I do that ?

UPDATE :

main.mod :

{int} set1={};
{int} set2={};
int ar[1..100][1..100];

main {
  var source = new IloOplModelSource("sub.mod");
  var cplex = new IloCplex();
  var def = new IloOplModelDefinition(source);
  for(var i=1;i<=30;i++) if (i % 10 == 0) {
    for (var j=1; j<=30; j++) if (j % 10 == 0) {
        var opl = new IloOplModel(def,cplex);
        var data2= new IloOplDataElements();
        data2.row=thisOplModel.set1;
        data2.row.add(i);
        data2.col=thisOplModel.set2;
        data2.col.add(j);
    }
  opl.addDataSource(data2);
  opl.generate();
}
if (cplex.solve()) {
writeln("Solution = " + cplex.getObjValue(),
"/ time = ", cplex.getCplexTime());
} else {
    writeln("No solution");
}
data2.end();
opl.end();
}

sub.mod :

{int} row=...;
{int} col=...;
int y[row][col];

execute {

 for (var i in row) {
     for (var j in col) {
        y[i][j]=i;
    }
 }
    writeln("y= ",y,
//    " / i= ", i,
//  "/ row = ", row,
    "/ col = ", col,
    "/ time = ", cplex.getCplexTime());
}

dvar float x;

maximize x;
subject to {
   x<=sum(i in row, j in col) y[i][j];
}

execute
{
writeln("x=",x);
}

Now, I obtain the right values in row = {10, 20, 30} and col = {10, 20, 30} in the main.mod.

In sub.mod row and col are sets. I need to use those values as matrices dimensions. So the first matrix is 10x10, the second 20x20 etc..

How can I access the values inside the set so that I can create those matrices ?

Sorry for the multiple questions but I am really new to CPLEX.

Body:
you could use modulo

range r=1..100;

execute
{
  for(var i in r) if (i % 10==0) writeln(i);
}

gives

10
20
30
40
50
60
70
80
90
100


问:
How to pass any URL to an APIFY task?
There is a box to configure the "Start URL" in APIFY, but what happens if i don't know the start URL and it depends of my user input? I would like to be able to pass a variable URL to "Start URL"

Configuration of Start URL in APIFY:

I want to pass any URL automatically through an APIFY task and then scrap it.

I tried to make it automatically through Zapier, in the configuration is possible to select the URL input and pass it to APIFY, but finally it stops the task because is not able to read the format passed. Data out log from Zapier:

I think that APIFY probably lets configure dynamic input URL's but by my beginner level, probably there is something that scapes from my knowledge.

I want to be able to pass variable URL's to be scraped by APIFY.

答:
You can check how input looks like in JSON format using Editor/JSON switcher on the top of input configuration.

After you switch to JSON you can easily check the structure of startUrls.
If you want to override startUrls for example in Zapier integration you can do it using Input JSON overrides field in Run Task Apify<>Zapier action.

You can override input same way using API to run the task, where you need to pass JSON as POST payload of the API request.

If you want to read more about Apify<>Zapier integration you can check article Scrape single URL using Zapier.

Title: How to pass any URL to an APIFY task?


问:
create folder under test folder Flutter
I'm new in Flutter, i started creating unit tests and UI interface tests, if i put the tests classes under test directory everything works fine, but when i decided to separate UI and unitTest in separate folders under test folder

test/unitTest/test1.dart

test/ui/widget1.dart

I got an error

Error: Not found: 'dart:ui'

is it possible to create folders under test folder ?

答:
Finally i found the solution

OK so I actually found a solution for this.

In Android studio in the run dropdown you select Edit Configurations
  Then you press the + button and select Flutter test Make sure the Test
  scope is All in file and point it at your test file. You can now run
  the individual test file and also debug it in android studio by
  selecting >this configuration in the run drop-down.

chose Flutter test > click + > Flutter test > click Test File > select the test file from your project.

Origin solution from here

Title: create folder under test folder Flutter


问:
Using AppConfig to import signals is not working Django 2.08
I have an app companies. Inside the app there is a file called signals.py with the following code:

```<code>post_save.connect(update_descendants, sender=Company)
</code>```

Inside companies apps.py I have:

```<code>class CompaniesConfig(AppConfig):
    name = 'apps.companies'

    def ready(self):
        from . import signals
</code>```

But the signals are not imported/called.

If I import the file in models.py it work but it creates a circular import issue, and I need to this imports inside functions not at top.

Structure:

```<code> - companies
   -apps
   -models
   -signals
</code>```

Why app config is not working ?

答:
If you are using a custom AppConfig class then you need to tell Django about it. It isn't automatically discovered. Reference in in the Django settings files like this:</p>

```<code>INSTALLED_APPS [
    ....
    "companies.apps.CompaniesConfig",
    ....
]
</code>```

Body:
I have an app companies. Inside the app there is a file called signals.py with the following code:

post_save.connect(update_descendants, sender=Company)

Inside companies apps.py I have:

class CompaniesConfig(AppConfig):
    name = 'apps.companies'

    def ready(self):
        from . import signals

But the signals are not imported/called.

If I import the file in models.py it work but it creates a circular import issue, and I need to this imports inside functions not at top.

Structure:

 - companies
   -apps
   -models
   -signals

Why app config is not working ?

Body:
If you are using a custom AppConfig class then you need to tell Django about it. It isn't automatically discovered. Reference in in the Django settings files like this:

INSTALLED_APPS [
    ....
    "companies.apps.CompaniesConfig",
    ....
]


问:
Is it possible to obtain and modify standard system context menu for textbox?
I have a simple winform app with textbox.

I didnt assigned any context menu to text field and "it uses" standard one. I desire to add some new items to textbox's standard context menu. But I cant obtain it for modification, if be more clearly I didnt know how to obtain HMENU native object.

ContextMenu property of my textbox equals null so I suppose that menu appers within textbox defaul windProc routing. It there a way to get the default context menu or get a copy of it?

Thanks in advance!

答: Depending on any plug-ins you're using, it may be easier, and more understandable, to create a custom control that derives from TextBox and defines a "default" contextual menu. Then, change all TextBoxes in your solution to be your custom control instead. Failing that, if you have a common window ancestor, set up some initialization code that assigns a given ContextMenu to all controls in the form's hierarchy of type TextBox. Instead of plugging in to low-level Windows hooks, you're using what the framework gives you to accomplish the same end, and your posterity doesn't have to know how Windows handles contextual menus at a message-passing level in order to alter this behavior.</p>

ContentLicense: CC BY-SA 3.0


问:
Why does "npm install" rewrite package-lock.json?
I just recently upgraded to npm@5.  I now have a package-lock.json file with everything from package.json.  I would expect that, when I run npm install that the dependency versions would be pulled from the lock file to determine what should be installed in my node_modules directory.  What's strange is that it actually ends up modifying and rewriting my package-lock.json file.

For example, the lock file had typescript specified to be at version 2.1.6.  Then, after the npm install command, the version was changed to 2.4.1.  That seems to defeat the whole purpose of a lock file.

What am I missing?  How do I get npm to actually respect my lock file?

答:
Probably you should use something like this

```<code>npm ci
</code>```

Instead of using npm install
if you don't want to change the version of your package.

According to the official documentation, both npm install and npm ci install the dependencies which are needed for the project.

The main difference is, npm install does install the packages taking packge.json as a reference. Where in the case of npm ci, it does install the packages taking package-lock.json as a reference, making sure every time the exact package is installed.

Body:
Probably you should use something like this

npm ci

Instead of using npm install
if you don't want to change the version of your package.

According to the official documentation, both npm install and npm ci install the dependencies which are needed for the project.

The main difference is, npm install does install the packages taking packge.json as a reference. Where in the case of npm ci, it does install the packages taking package-lock.json as a reference, making sure every time the exact package is installed.


问:
login as a user and admin at the same time in laravel
I am working on a laravel project in which from ADMIN panel I can log in in the user module, but when I want to go back from the browser the admin panel is not working means admin is logout. is there any method in which I can log in in both module admin and user.</p>

答:
If you log in as one user, you log out as the other.

I see 2 possibilities:

1) Make 2 user tables, with separate login/logout/etc. one for your frontend users, one for your admin panel.

The advantage here is that your regular users will never be able to login as an admin, because they don't exist in that table.

2) Separate your frontend and admin panel into 2 different projects. You can link them to the same database. Put the admin panel on a subsite admin.my-project.com.

The advantage here is that you seperate your logic between 2 projects, each focused on different functionality, with their own styling, layout and most important for your example: authentication.


问:
ASP.NET Core - producing "000000..." sha256 hash under heavy load
I have a bit of a strange problem. I'm running a web API on ASP.NET Core 3.1. One thing the API does is to generate a SHA256 from an input string

```<code>private static HashAlgorithm algorithm = SHA256.Create();
public static byte[] GetSha256Hash(string inputString)
{
    return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}

public static string GetSha256HashString(string inputString)
{
    var result = GetSha256Hash(inputString);
    // Return as hexadecimal string
    return string.Join(
        string.Empty,
        result.Select(x => x.ToString("x2")));
}

player.Id = GetSha256HashString($"{player.Name}-{player.Region}-{player.Country}");

</code>```

I check that the fields player.Name, region and country and not null before I do the hashing. But sometimes, mostly seems to happen when the server is under heavy load (~100 requests/second), for a few requests (about ~0.5%) it generates

0000000000000000000000000000000000000000000000000000000000000000 for the player.id. Usually they look something like this a7da37b8a57ea714ec11f92c0025d6e654a483144eb68b829d388ea91eb81c79

Even if all the fields would be empty, the three dashes alone would ensure that this should not happen.

I do not see any exceptions and I am a bit out of ideas how to debug this. Any help is welcome! Let me know if I need to add any more information.

Env: Running in Docker on Linux.

答:
```<code>public static string GetSha256HashString(string inputString)
{
    SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();
    byte[] B1;
    byte[] B2;
    B1 = UTF8Encoding.UTF8.GetBytes(inputString.Trim());
    B2 = sha256.ComputeHash(B1);
    string HashString = BitConverter.ToString(B2);
    return HashString;
}
</code>```

Body:
I have a bit of a strange problem. I'm running a web API on ASP.NET Core 3.1. One thing the API does is to generate a SHA256 from an input string

private static HashAlgorithm algorithm = SHA256.Create();
public static byte[] GetSha256Hash(string inputString)
{
    return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}

public static string GetSha256HashString(string inputString)
{
    var result = GetSha256Hash(inputString);
    // Return as hexadecimal string
    return string.Join(
        string.Empty,
        result.Select(x => x.ToString("x2")));
}

player.Id = GetSha256HashString($"{player.Name}-{player.Region}-{player.Country}");

I check that the fields player.Name, region and country and not null before I do the hashing. But sometimes, mostly seems to happen when the server is under heavy load (~100 requests/second), for a few requests (about ~0.5%) it generates

0000000000000000000000000000000000000000000000000000000000000000 for the player.id. Usually they look something like this a7da37b8a57ea714ec11f92c0025d6e654a483144eb68b829d388ea91eb81c79

Even if all the fields would be empty, the three dashes alone would ensure that this should not happen.

I do not see any exceptions and I am a bit out of ideas how to debug this. Any help is welcome! Let me know if I need to add any more information.

Env: Running in Docker on Linux.


问:
Postgres jsonb : cast array element to integer
Using Postgres 11.2.9 (ubuntu),

In my database, I have a jsonb field containing values that look like this :
[1618171589133, 1618171589245, 1618171589689]

I'd like to retrieve rows where the first element is lower than a specific value. I've tried this :

SELECT * FROM user.times WHERE time ->> 0 < 1618171589133

but I get the following error : ERROR: operator does not exist: text = bigint

Should I somehow cast the time value to numeric value ? I've tried time ->> 0::numeric but I actually don't know what to do.

答:
The ->> operator returns the element at given position as text, which you can then convert to integer (or as it seems in this case, bigint), as you would normally do in postgres, using the :: as suffix.

```<code>SELECT * FROM user.times WHERE ((time ->> 0)::bigint) < 1618171589133
</code>```

Body:
The ->> operator returns the element at given position as text, which you can then convert to integer (or as it seems in this case, bigint), as you would normally do in postgres, using the :: as suffix.

SELECT * FROM user.times WHERE ((time ->> 0)::bigint) < 1618171589133


问:
Add Column to end of CSV file using 'awk' in BASH script
How do you add a column to the end of a CSV file with using a string in a variable?

input.csv

```<code>2012-02-29,01:00:00,Manhattan,New York,234
2012-02-29,01:00:00,Manhattan,New York,843
2012-02-29,01:00:00,Manhattan,New York,472
2012-02-29,01:00:00,Manhattan,New York,516
</code>```

output.csv

```<code>2012-02-29,01:00:00,Manhattan,New York,234,2012-02-29 16:13:00
2012-02-29,01:00:00,Manhattan,New York,843,2012-02-29 16:13:00
2012-02-29,01:00:00,Manhattan,New York,472,2012-02-29 16:13:00
2012-02-29,01:00:00,Manhattan,New York,516,2012-02-29 16:13:00
</code>```

awk.sh

```<code>#!/bin/bash

awk -F"," '{$6="2012-02-29 16:13:00" OFS $6; print}' input.csv > output.csv
</code>```

My attempt above in awk.sh added the string to the end but stripped all the comma separators.

awk.sh result

```<code>2012-02-29 01:00:00 Manhattan New York 234 2012-02-29 16:13:00
2012-02-29 01:00:00 Manhattan New York 843 2012-02-29 16:13:00
2012-02-29 01:00:00 Manhattan New York 472 2012-02-29 16:13:00
2012-02-29 01:00:00 Manhattan New York 516 2012-02-29 16:13:00
</code>```

Appreciate any help!

Updated awk.sh

```<code>#!/bin/bash

GAWK="/bin/gawk"
TIMESTAMP=$(date +"%F %T")
ORIG_FILE="input.csv"
NEW_FILE="output.csv"

#Append 'Create' DateTimeStamp to CSV for MySQL logging
$GAWK -v d="$TIMESTAMP" -F"," 'BEGIN {OFS = ","} {$6=d; print}' $ORIG_FILE > $NEW_FILE
rm -f $ORIG_FILE
</code>```

答:
If anyone wants to create csv file through shell with column names:
where first input stored in variables from_time, to_time.

example:insert two timestamps with from_time and to_time as column names with respective values -

CODE-

```<code>FROM_TIME=2020-02-06T00:00:00
TO_TIME=2020-02-07T00:00:00
{ echo -e "$FROM_TIME,$TO_TIME";}>input1.csv
{ echo -e "from_time,to_time"; cat input1.csv;} > input.csv
</code>```

first line storing the values
second line responsible for adding column name

Body:
How do you add a column to the end of a CSV file with using a string in a variable?

input.csv

2012-02-29,01:00:00,Manhattan,New York,234
2012-02-29,01:00:00,Manhattan,New York,843
2012-02-29,01:00:00,Manhattan,New York,472
2012-02-29,01:00:00,Manhattan,New York,516

output.csv

2012-02-29,01:00:00,Manhattan,New York,234,2012-02-29 16:13:00
2012-02-29,01:00:00,Manhattan,New York,843,2012-02-29 16:13:00
2012-02-29,01:00:00,Manhattan,New York,472,2012-02-29 16:13:00
2012-02-29,01:00:00,Manhattan,New York,516,2012-02-29 16:13:00

awk.sh

#!/bin/bash

awk -F"," '{$6="2012-02-29 16:13:00" OFS $6; print}' input.csv > output.csv

My attempt above in awk.sh added the string to the end but stripped all the comma separators.

awk.sh result

2012-02-29 01:00:00 Manhattan New York 234 2012-02-29 16:13:00
2012-02-29 01:00:00 Manhattan New York 843 2012-02-29 16:13:00
2012-02-29 01:00:00 Manhattan New York 472 2012-02-29 16:13:00
2012-02-29 01:00:00 Manhattan New York 516 2012-02-29 16:13:00

Appreciate any help!

Updated awk.sh

#!/bin/bash

GAWK="/bin/gawk"
TIMESTAMP=$(date +"%F %T")
ORIG_FILE="input.csv"
NEW_FILE="output.csv"

#Append 'Create' DateTimeStamp to CSV for MySQL logging
$GAWK -v d="$TIMESTAMP" -F"," 'BEGIN {OFS = ","} {$6=d; print}' $ORIG_FILE > $NEW_FILE
rm -f $ORIG_FILE

Body:
If anyone wants to create csv file through shell with column names:
where first input stored in variables from_time, to_time.

example:insert two timestamps with from_time and to_time as column names with respective values -

CODE-

FROM_TIME=2020-02-06T00:00:00
TO_TIME=2020-02-07T00:00:00
{ echo -e "$FROM_TIME,$TO_TIME";}>input1.csv
{ echo -e "from_time,to_time"; cat input1.csv;} > input.csv

first line storing the values
second line responsible for adding column name


问:
GCP Bulk Decompress maintaining file structure
We have a large number of compressed files stored in a GCS bucket. I am attempting to bulk decompress them using the provided utility. The data is in a timestamp directory hierarchy; YEAR/MONTH/DAY/HOUR/files.txt.gz. Dataflow accepts wildcard input patterns; inputFilePattern=gs://source-data/raw/nginx/2019/01/01/*/*.txt.gz. However the directory structure is flattened at output. All the files are decompressed into a single directory. Is it possible to maintain the directory hierarchy using the bulk decompressor? Is there another possible solution?

```<code>gcloud dataflow jobs run gregstest \
    --gcs-location gs://dataflow-templates/latest/Bulk_Decompress_GCS_Files \
    --service-account-email greg@gmeow.com \
    --project shopify-data-kernel \
    --parameters \
inputFilePattern=gs://source-data/raw/nginx/2019/01/01/*/*.txt.gz,\
outputDirectory=gs://uncompressed-data/uncompressed,\
outputFailureFile=gs://uncompressed-data/failed
</code>```

答:
I have looked for Java code of bulk decompressor and the PipelineResult method does following steps:

Find all files matching the input pattern

Decompress the files found and output them to the output directory

Write any errors to the failure output file

It looks like API decompress only files, not directories with files. I recommend you to check this thread on Stackoverflow with possible solutions concerning decompress file in GCS.

I hope you find the above pieces of information useful.

Body:
We have a large number of compressed files stored in a GCS bucket. I am attempting to bulk decompress them using the provided utility. The data is in a timestamp directory hierarchy; YEAR/MONTH/DAY/HOUR/files.txt.gz. Dataflow accepts wildcard input patterns; inputFilePattern=gs://source-data/raw/nginx/2019/01/01/*/*.txt.gz. However the directory structure is flattened at output. All the files are decompressed into a single directory. Is it possible to maintain the directory hierarchy using the bulk decompressor? Is there another possible solution?

gcloud dataflow jobs run gregstest \
    --gcs-location gs://dataflow-templates/latest/Bulk_Decompress_GCS_Files \
    --service-account-email greg@gmeow.com \
    --project shopify-data-kernel \
    --parameters \
inputFilePattern=gs://source-data/raw/nginx/2019/01/01/*/*.txt.gz,\
outputDirectory=gs://uncompressed-data/uncompressed,\
outputFailureFile=gs://uncompressed-data/failed


问:
Why does my page work in IE9's IE7 mode, but not in IE7 itself?
I recently went live with our new home page, after heavily testing it in each of IE9's browser and document modes (not just compatibility mode, but actual IE7 and IE8 emulation). The site works in each mode, not to mention modern browsers. However, after it launched I got an email that said the site was very broken in IE7. I went to an abandoned machine and booted up Windows XP, started IE7, and loaded the page. To my horror, the layout was indeed broken! (NOT just the slideshow!)

Most importantly, why does my page not work in IE7, even though it works in IE7 mode in IE9? And as a secondary question, what might be "wrong" with it?

Edit: I have figured out that one of my problems may be the slideshow, but adding .ie7 #slideshow {display:none !important} won't even hide the slideshow. I can't access it via CSS.

Edit 2: There is another problem that only shows up in native IE7 -- the footer on that home page, and this page, is ultra-tiny text that can't be zoomed. It doesn't do this in IE9's IE7 mode (not compatibility), or in any other browser. Another example of the discrepancy.

答:
I'm with the others in saying that the possible culprit is the slideshow. I would get a more CSS friendly slideshow:

http://flowplayer.org/tools/index.html

And definitely test in the ACTUAL browser! You could use an online browser check site like browsershots.org. They take aLONG time to produce a shot of your site, but it is accurate.


问:
Trying to alter 'createdTime' in google docs with Google Apps Script. Getting Error 403 ..."field not writable". Any workaround?
Full error message:

Request failed for https://www.googleapis.com returned code 403. Truncated server response: { "error": { "errors": [ { "domain": "global", "reason": "fieldNotWritable", "message": "The resource body includes fields which ... (use muteHttpExceptions option to examine full response). (line 13, file "Code")

The code below worked with 'viewedByMeTime' & 'modifiedTime'

```<code>function myFunction() {
  var newModifiedTime = "2019-01-01T00:00:00.000Z";
  var fileId = "1LaKH-wsjgGrCyG6zpbyzsBgsgTah2jQRIIDvDKaaRio";
  var url = "https://www.googleapis.com/drive/v3/files/" + fileId;

var params = {
    method: "patch",
    headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},//Last time opend by you
    payload: JSON.stringify({createdTime: newModifiedTime}),
    contentType: "application/json",
  };
  UrlFetchApp.fetch(url, params);
</code>```

答:
You appear to be trying to do a file.update

"fieldNotWritable"

means exactly that not all of the fields can be writen to.  which means you cant update every fields. and create time is one of the fields that you cant update.  if you check the documentation under request body you will see the fields you are allowed to update.

Body:
Full error message:

Request failed for https://www.googleapis.com returned code 403. Truncated server response: { "error": { "errors": [ { "domain": "global", "reason": "fieldNotWritable", "message": "The resource body includes fields which ... (use muteHttpExceptions option to examine full response). (line 13, file "Code")

The code below worked with 'viewedByMeTime' & 'modifiedTime'

function myFunction() {
  var newModifiedTime = "2019-01-01T00:00:00.000Z";
  var fileId = "1LaKH-wsjgGrCyG6zpbyzsBgsgTah2jQRIIDvDKaaRio";
  var url = "https://www.googleapis.com/drive/v3/files/" + fileId;

var params = {
    method: "patch",
    headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},//Last time opend by you
    payload: JSON.stringify({createdTime: newModifiedTime}),
    contentType: "application/json",
  };
  UrlFetchApp.fetch(url, params);


问:
Can you force Vue.js to reload/re-render?
Just a quick question.

Can you force Vue.js to reload/recalculate everything? If so, how?

答:
So there's two way you can do this,

You can use $forceUpdate() inside your method handler i.e

<your-component @click="reRender()"></your-component>

```
<ol start="2">
<li>You can give a <code>:key</code> attribute to your component and increment when want to rerender</li>
</ol>
<p><code><your-component :key="index" @click="reRender()"></your-component></code></p>
<pre class="lang-html prettyprint-override"><code><script>
export default {
   data() {
     return {
        index: 1
     }
   },
   methods: {
     reRender(){
        this.index++
     }
   }
}
</script>
</code>```

Body:
So there's two way you can do this,

You can use $forceUpdate() inside your method handler i.e

<your-component @click="reRender()"></your-component>

<script>
export default {
   methods: {
     reRender(){
        this.$forceUpdate()
     }
   }
}
</script>

You can give a :key attribute to your component and increment when want to rerender

<your-component :key="index" @click="reRender()"></your-component>

<script>
export default {
   data() {
     return {
        index: 1
     }
   },
   methods: {
     reRender(){
        this.index++
     }
   }
}
</script>


问:
Unable to use nyc/istanbul for code coverage
I am using nightwatch for selenium based tests, but when I use nyc nightwatch, it only reports the test code and their 100% coverage. This is my primary blocker right now. How do I get the coverage? Basically, I want to get this as a report in Jenkins CI ultimately.

Additionally, I thought to test with my UTs as well for which I am using jest. Normally, "test": "jest --coverage" will list the coverage properly with all the tested code. So when I give nyc npm run test it gives me same coverage, which is good. But the moment I run with only nyc jest, it returns 100% coverage for jest.config.js!!

I don't have mocha or grunt etc.

答:
Since jest uses nyc under the hood, there is no reason to use them together. You can call jest with the --coverage flag and tell it which reports to use in your config, as defined in the config:

```<code>  "jest": {
    "collectCoverage": true,
    "collectCoverageFrom": [
      "**/*.{js,jsx}",
      "!**/node_modules/**",
      "!**/vendor/**"
    ],
    "coverageReporters": [
      "text",
      "cobertura"
    ],
    "reporters": [
      "default",
      "jest-junit"
    ]
  }
</code>```

https://jestjs.io/docs/en/configuration#coveragereporters-arraystring

Body:
Since jest uses nyc under the hood, there is no reason to use them together. You can call jest with the --coverage flag and tell it which reports to use in your config, as defined in the config:

  "jest": {
    "collectCoverage": true,
    "collectCoverageFrom": [
      "**/*.{js,jsx}",
      "!**/node_modules/**",
      "!**/vendor/**"
    ],
    "coverageReporters": [
      "text",
      "cobertura"
    ],
    "reporters": [
      "default",
      "jest-junit"
    ]
  }

https://jestjs.io/docs/en/configuration#coveragereporters-arraystring


问:
How to scroll to a specific element in ScrollRect with Unity UI?
I built a registration form for a mobile game using Unity 5.1.
To do that, I use Unity UI components: ScrollRect + Autolayout (Vertical layout) + Text (labels) + Input Field.
This part works fine.

But, when keyboard is opened, the selected field is under keyboard. Is there a way to programmatically scroll the form to bring the selected field into view?

I have tried using ScrollRect.verticalNormalizedPosition and it works fine to scroll some, however I am not able to make selected field appear where I want.

Thanks for your help !

答:
Vertical adjustment:

[SerializeField]
private ScrollRect _scrollRect;

private void ScrollToCurrentElement()
{
    var siblingIndex = _currentListItem.transform.GetSiblingIndex();

    float pos = 1f - (float)siblingIndex / _scrollRect.content.transform.childCount;

    if (pos < 0.4)
    {
        float correction = 1f / _scrollRect.content.transform.childCount;
        pos -= correction;
    }

    _scrollRect.verticalNormalizedPosition = pos;
}
```


问:
angular application not reachable by nginx on kubernetes
After creating my application, creating the image through the Dockerfile, I proceeded to configure it in a pod of kubernetes. However, I can't reach it via IP address. In fact, I noticed that there is no ip assigned.

```<code>NAME                  TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes            ClusterIP   XX.XX.X.X       <none>        443/TCP   2d1h
app                   ClusterIP   XX.XX.XXX.XX   <none>        80/TCP    1h
</code>```

I have tried to edited the file yaml to set the selector run:ning, but I do not see the external ip.

This is the situation of the services:

```<code>NAMESPACE     NAME                                       TYPE
default       service/kubernetes                         ClusterIP
default       service/app                                ClusterIP
kube-system   service/kube-dns                           ClusterIP
kube-system   service/nginx-ingress-controller           LoadBalancer
kube-system   service/nginx-ingress-controller-metrics   ClusterIP
kube-system   service/nginx-ingress-default-backend      ClusterIP
</code>```

答:
You don't need to have an external IP when you use ingress because the traffic will come into the nginx ingress and will be routed to the app service based on the rules defined in ingress resource.The app service will just be a clusterIP type service .You need to define an ingress resource as below:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: app-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
  - http:
      paths:
        - path: /
          backend:
            serviceName: app
            servicePort: 80 # port of the service
</code>```

After you create above you should able to access the service by hitting the LoadBalancer IP or DNS of service nginx-ingress-controller.

Body:
After creating my application, creating the image through the Dockerfile, I proceeded to configure it in a pod of kubernetes. However, I can't reach it via IP address. In fact, I noticed that there is no ip assigned.

NAME                  TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes            ClusterIP   XX.XX.X.X       <none>        443/TCP   2d1h
app                   ClusterIP   XX.XX.XXX.XX   <none>        80/TCP    1h

I have tried to edited the file yaml to set the selector run:ning, but I do not see the external ip.

This is the situation of the services:

NAMESPACE     NAME                                       TYPE
default       service/kubernetes                         ClusterIP
default       service/app                                ClusterIP
kube-system   service/kube-dns                           ClusterIP
kube-system   service/nginx-ingress-controller           LoadBalancer
kube-system   service/nginx-ingress-controller-metrics   ClusterIP
kube-system   service/nginx-ingress-default-backend      ClusterIP

Body:
You don't need to have an external IP when you use ingress because the traffic will come into the nginx ingress and will be routed to the app service based on the rules defined in ingress resource.The app service will just be a clusterIP type service .You need to define an ingress resource as below:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: app-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
  - http:
      paths:
        - path: /
          backend:
            serviceName: app
            servicePort: 80 # port of the service

After you create above you should able to access the service by hitting the LoadBalancer IP or DNS of service nginx-ingress-controller.


问:
Convert PHP date into javascript date format
I have a PHP script that outputs an array of data.  This is then transformed into JSON using the json_encode() function.

My issue is I have a date within my array and it's not in the correct JavaScript format.  How can I convert this within PHP so it is?

```<code>$newticket['ThreadID'] =  $addticket;
$newticket['Subject'] =  $subject;
//$newticket['DateCreated'] =  date('d-m-Y G:H');
</code>```

Instead of the above for the date I need the equivalent of the JavaScript function

new Date()

When I output the above I get the following "Fri Jun 01 2012 11:08:48 GMT+0100 (GMT Daylight Time)" However, If I format my PHP date to be the same, then JavaScript rejects it.  Confused...

Can anyone help?

答:
An improvement or simplification of @jeremyharris answer would be this one:

DateTime objects in PHP have the getTimestamp() format, use it and multiply the value by 1000:

```<code><?php
    $phpDateTimeStamp = new Date('Y/m/d H:i:s')->getTimestamp() * 1000;
?>

// JavaScript
let phpDateTimeStamp = 'YOUR_PHP_VARIABLE';
let startTime = new Date(parseInt(phpDateTimeStamp));
</code>```

Body:
I have a PHP script that outputs an array of data.  This is then transformed into JSON using the json_encode() function.

My issue is I have a date within my array and it's not in the correct JavaScript format.  How can I convert this within PHP so it is?

$newticket['ThreadID'] =  $addticket;
$newticket['Subject'] =  $subject;
//$newticket['DateCreated'] =  date('d-m-Y G:H');

Instead of the above for the date I need the equivalent of the JavaScript function

new Date()

When I output the above I get the following "Fri Jun 01 2012 11:08:48 GMT+0100 (GMT Daylight Time)" However, If I format my PHP date to be the same, then JavaScript rejects it.  Confused...

Can anyone help?

Body:
An improvement or simplification of @jeremyharris answer would be this one:

DateTime objects in PHP have the getTimestamp() format, use it and multiply the value by 1000:

<?php
    $phpDateTimeStamp = new Date('Y/m/d H:i:s')->getTimestamp() * 1000;
?>

// JavaScript
let phpDateTimeStamp = 'YOUR_PHP_VARIABLE';
let startTime = new Date(parseInt(phpDateTimeStamp));


Title: R - How to change elements in a matrix starting from a specific point

Body:
I have a data frame M, which looks like:

 [,1]      [,2]      [,3]       [,4]     [,5]
 [1,] 0.4212778 0.6874073 0.1551896 Cluster_1
 [2,] 0.6874073 0.5610995 0.1779030 Cluster_1
 [3,] 0.1551896 0.1779030 0.9515304 Cluster_1
 [4,] 0.4675764 0.5407295 0.7942978 Cluster_1_A
 [5,] 0.4675764 0.5407295 0.7942978 Cluster_1
 [6,] 0.4675764 0.5407295 0.7942978 Cluster_1
 [7,] 0.4675764 0.5407295 0.7942978 Cluster_2
 [8,] 0.4675764 0.5407295 0.7942978 Cluster_2_A
 [9,] 0.4675764 0.5407295 0.7942978 Cluster_2
[10,] 0.4675764 0.5407295 0.7942978 Cluster_2
[11,] 0.4675764 0.5407295 0.7942978 Cluster_2_1_A
[12,] 0.4675764 0.5407295 0.7942978 Cluster_2
[13,] 0.4675764 0.5407295 0.7942978 Cluster_2
[14,] 0.4675764 0.5407295 0.7942978 Cluster_3
[15,] 0.4675764 0.5407295 0.7942978 Cluster_3
[15,] 0.4675764 0.5407295 0.7942978 Cluster_3
[16,] 0.4675764 0.5407295 0.7942978 Cluster_4
[17,] 0.4675764 0.5407295 0.7942978 Cluster_4

I want to assign the same name of the elements of the matrix (column 5) in the range starting from the element with "_A" flag until the next name change.
In this case:

from M[4,5] until element M[6,5]

from M[8,5] until element M[10,5]

from M[11,5] until element M[13,5]

The result I want is the following:

 [,1]      [,2]      [,3]       [,4]     [,5]
 [1,] 0.4212778 0.6874073 0.1551896 Cluster_1
 [2,] 0.6874073 0.5610995 0.1779030 Cluster_1
 [3,] 0.1551896 0.1779030 0.9515304 Cluster_1
 [4,] 0.4675764 0.5407295 0.7942978 Cluster_1_A
 [5,] 0.4675764 0.5407295 0.7942978 Cluster_1_A
 [6,] 0.4675764 0.5407295 0.7942978 Cluster_1_A
 [7,] 0.4675764 0.5407295 0.7942978 Cluster_2
 [8,] 0.4675764 0.5407295 0.7942978 Cluster_2_A
 [9,] 0.4675764 0.5407295 0.7942978 Cluster_2_A
[10,] 0.4675764 0.5407295 0.7942978 Cluster_2_A
[11,] 0.4675764 0.5407295 0.7942978 Cluster_2_1_A
[12,] 0.4675764 0.5407295 0.7942978 Cluster_2_1_A
[13,] 0.4675764 0.5407295 0.7942978 Cluster_2_1_A
[14,] 0.4675764 0.5407295 0.7942978 Cluster_3
[15,] 0.4675764 0.5407295 0.7942978 Cluster_3
[15,] 0.4675764 0.5407295 0.7942978 Cluster_3
[16,] 0.4675764 0.5407295 0.7942978 Cluster_4
[17,] 0.4675764 0.5407295 0.7942978 Cluster_4

How can I do that quickly, also avoiding a for loop (which I'm able to code)? I've seen many similar posts, but no one gave me what I want. Thank you!

Body:
You can try something like this, convert your (what looks like a matrix) into a data.frame:

df = structure(list(value1 = c(0.4212778, 0.6874073, 0.1551896, 0.4675764,
0.4675764, 0.4675764, 0.4675764, 0.4675764, 0.4675764, 0.4675764,
0.4675764, 0.4675764, 0.4675764, 0.4675764, 0.4675764, 0.4675764,
0.4675764, 0.4675764), value2 = c(0.6874073, 0.5610995, 0.177903,
0.5407295, 0.5407295, 0.5407295, 0.5407295, 0.5407295, 0.5407295,
0.5407295, 0.5407295, 0.5407295, 0.5407295, 0.5407295, 0.5407295,
0.5407295, 0.5407295, 0.5407295), value3 = c(0.1551896, 0.177903,
0.9515304, 0.7942978, 0.7942978, 0.7942978, 0.7942978, 0.7942978,
0.7942978, 0.7942978, 0.7942978, 0.7942978, 0.7942978, 0.7942978,
0.7942978, 0.7942978, 0.7942978, 0.7942978), cluster = structure(c(1L,
1L, 1L, 2L, 1L, 1L, 3L, 5L, 3L, 3L, 4L, 3L, 3L, 6L, 6L, 6L, 7L,
7L), .Label = c("Cluster_1", "Cluster_1_A", "Cluster_2", "Cluster_2_1_A",
"Cluster_2_A", "Cluster_3", "Cluster_4"), class = "factor")), class = "data.frame", row.names = c(NA,
-18L))

head(df)

     value1    value2    value3     cluster
1 0.4212778 0.6874073 0.1551896   Cluster_1
2 0.6874073 0.5610995 0.1779030   Cluster_1
3 0.1551896 0.1779030 0.9515304   Cluster_1
4 0.4675764 0.5407295 0.7942978 Cluster_1_A
5 0.4675764 0.5407295 0.7942978   Cluster_1
6 0.4675764 0.5407295 0.7942978   Cluster_1

If we do the following:

df$id = as.numeric(factor(df$cluster))

head(df,10)
      value1    value2    value3     cluster id
1  0.4212778 0.6874073 0.1551896   Cluster_1  1
2  0.6874073 0.5610995 0.1779030   Cluster_1  1
3  0.1551896 0.1779030 0.9515304   Cluster_1  1
4  0.4675764 0.5407295 0.7942978 Cluster_1_A  2
5  0.4675764 0.5407295 0.7942978   Cluster_1  1
6  0.4675764 0.5407295 0.7942978   Cluster_1  1
7  0.4675764 0.5407295 0.7942978   Cluster_2  3
8  0.4675764 0.5407295 0.7942978 Cluster_2_A  5
9  0.4675764 0.5407295 0.7942978   Cluster_2  3
10 0.4675764 0.5407295 0.7942978   Cluster_2  3

You can see everytime there is an increase i.e from 1 to 2 at row 3:4 or 3 to 5 at row 7:8, it's where we want to separate them. So we do this:

df$grp = cumsum(c(0,diff(df$id)>0))

      value1    value2    value3     cluster id grp
1  0.4212778 0.6874073 0.1551896   Cluster_1  1   0
2  0.6874073 0.5610995 0.1779030   Cluster_1  1   0
3  0.1551896 0.1779030 0.9515304   Cluster_1  1   0
4  0.4675764 0.5407295 0.7942978 Cluster_1_A  2   1
5  0.4675764 0.5407295 0.7942978   Cluster_1  1   1
6  0.4675764 0.5407295 0.7942978   Cluster_1  1   1
7  0.4675764 0.5407295 0.7942978   Cluster_2  3   2
8  0.4675764 0.5407295 0.7942978 Cluster_2_A  5   3
9  0.4675764 0.5407295 0.7942978   Cluster_2  3   3

Your new id is simply:

df$new = unlist(
tapply(as.character(df$cluster),
df$grp,
function(i)rep(i[1],length(i))))

      value1    value2    value3       cluster id grp           new
1  0.4212778 0.6874073 0.1551896     Cluster_1  1   0     Cluster_1
2  0.6874073 0.5610995 0.1779030     Cluster_1  1   0     Cluster_1
3  0.1551896 0.1779030 0.9515304     Cluster_1  1   0     Cluster_1
4  0.4675764 0.5407295 0.7942978   Cluster_1_A  2   1   Cluster_1_A
5  0.4675764 0.5407295 0.7942978     Cluster_1  1   1   Cluster_1_A
6  0.4675764 0.5407295 0.7942978     Cluster_1  1   1   Cluster_1_A
7  0.4675764 0.5407295 0.7942978     Cluster_2  3   2     Cluster_2
8  0.4675764 0.5407295 0.7942978   Cluster_2_A  5   3   Cluster_2_A
9  0.4675764 0.5407295 0.7942978     Cluster_2  3   3   Cluster_2_A
10 0.4675764 0.5407295 0.7942978     Cluster_2  3   3   Cluster_2_A
11 0.4675764 0.5407295 0.7942978 Cluster_2_1_A  4   4 Cluster_2_1_A
12 0.4675764 0.5407295 0.7942978     Cluster_2  3   4 Cluster_2_1_A
13 0.4675764 0.5407295 0.7942978     Cluster_2  3   4 Cluster_2_1_A
14 0.4675764 0.5407295 0.7942978     Cluster_3  6   5     Cluster_3
15 0.4675764 0.5407295 0.7942978     Cluster_3  6   5     Cluster_3
16 0.4675764 0.5407295 0.7942978     Cluster_3  6   5     Cluster_3
17 0.4675764 0.5407295 0.7942978     Cluster_4  7   6     Cluster_4
18 0.4675764 0.5407295 0.7942978     Cluster_4  7   6     Cluster_4


问:
Setting a value to a cell in a pandas dataframe
I have the following pandas dataframe:

```<code>K = pd.DataFrame({"A":[1,2,3,4], "B":[5,6,7,8]})
</code>```

Then I set the cell in the first row and first column to 11:

```<code>K.iloc[0]["A"] = 11
</code>```

And when I check the dataframe again, I see that the value assignment is done and K.iloc[0]["A"] is equal to 11. However when I add a column to this data frame and do the same operation for a cell in the new column, the value assignment is not successful:

```<code>K["C"] = 0
K.iloc[0]["C"] = 11
</code>```

So, when I check the dataframe again, the value of K.iloc[0]["C"] is still zero. I appreciate if somebody can tell me what is going on here and how I can resolve this issue.

答:
If default index, RangeIndex is possible use DataFrame.loc, but it set index values by label 0 (what is same like position 0):

```<code>K['C'] = 0
K.loc[0, ["A", "C"]] = 11
print (K)
    A  B   C
0  11  5  11
1   2  6   0
2   3  7   0
3   4  8   0
</code>```

Reason why your solution failed is possible find in docs:

This can work at times, but it is not guaranteed to, and therefore should be avoided:

dfc['A'][0] = 111

Solution with DataFrame.iloc is possible with get positions of columns by Index.get_indexer:

```<code>print (K.columns.get_indexer(["A", "C"]))
[0 2]

K['C'] = 0
K.iloc[0, K.columns.get_indexer(["A", "C"])] = 11
print (K)
    A  B   C
0  11  5  11
1   2  6   0
2   3  7   0
3   4  8   0
</code>```

Body:
I have the following pandas dataframe:

K = pd.DataFrame({"A":[1,2,3,4], "B":[5,6,7,8]})

Then I set the cell in the first row and first column to 11:

K.iloc[0]["A"] = 11

And when I check the dataframe again, I see that the value assignment is done and K.iloc[0]["A"] is equal to 11. However when I add a column to this data frame and do the same operation for a cell in the new column, the value assignment is not successful:

K["C"] = 0
K.iloc[0]["C"] = 11

So, when I check the dataframe again, the value of K.iloc[0]["C"] is still zero. I appreciate if somebody can tell me what is going on here and how I can resolve this issue.

Body:
If default index, RangeIndex is possible use DataFrame.loc, but it set index values by label 0 (what is same like position 0):

K['C'] = 0
K.loc[0, ["A", "C"]] = 11
print (K)
    A  B   C
0  11  5  11
1   2  6   0
2   3  7   0
3   4  8   0

Reason why your solution failed is possible find in docs:

This can work at times, but it is not guaranteed to, and therefore should be avoided:

dfc['A'][0] = 111

Solution with DataFrame.iloc is possible with get positions of columns by Index.get_indexer:

print (K.columns.get_indexer(["A", "C"]))
[0 2]

K['C'] = 0
K.iloc[0, K.columns.get_indexer(["A", "C"])] = 11
print (K)
    A  B   C
0  11  5  11
1   2  6   0
2   3  7   0
3   4  8   0


问:
how to handle React axios how to handle net::ERR_CONNECTION_REFUSED
It was asked before, but if I follow the solution still in the console there is an uncouth error:-

```<code>    getExchangeAmount(){
  var url = 'http://localhost:8080/excurrency?currency='+this.state.currency+
            '&exCurrency='+this.state.excurrency+'&amount='+this.state.amount

    axios.get(url)
    .then(response => {
        // success
        this.setState({result: response.data})
    })
    .catch((error) => {
        // handle this error
        console.log('error: '+error);
    })
}
</code>```

in the console:-

GET
  http://localhost:8080/excurrency?currency=EGP&exCurrency=EGP&amount=1
  net::ERR_CONNECTION_REFUSED

The above is in red which is an error. how to avoid or catch this?

答:
Try Like this </p>

```<code>getExchangeAmount(e){
e.preventDefault();
  var url = `/excurrency?currency${this.state.currency}&exCurrency=${this.state.excurrency}&amount=${this.state.amount}`

    axios.get(url)
    .then(response => {
        // success
        this.setState({result: response.data})
    })
    .catch((error) => {
        // handle this error
        console.log('error: '+error);
    })
}
</code>```

Body:
It was asked before, but if I follow the solution still in the console there is an uncouth error:-

    getExchangeAmount(){
  var url = 'http://localhost:8080/excurrency?currency='+this.state.currency+
            '&exCurrency='+this.state.excurrency+'&amount='+this.state.amount

    axios.get(url)
    .then(response => {
        // success
        this.setState({result: response.data})
    })
    .catch((error) => {
        // handle this error
        console.log('error: '+error);
    })
}

in the console:-

GET
  http://localhost:8080/excurrency?currency=EGP&exCurrency=EGP&amount=1
  net::ERR_CONNECTION_REFUSED

The above is in red which is an error. how to avoid or catch this?

Body:
Try Like this

getExchangeAmount(e){
e.preventDefault();
  var url = `/excurrency?currency${this.state.currency}&exCurrency=${this.state.excurrency}&amount=${this.state.amount}`

    axios.get(url)
    .then(response => {
        // success
        this.setState({result: response.data})
    })
    .catch((error) => {
        // handle this error
        console.log('error: '+error);
    })
}


问:
Where are the Xcode 'behaviors' stored?
I had to start fresh with Xcode and I'm going crazy having to configure all just as I like. I have it installed in other computer and I'd like to copy the "behaviors" from there. Where are they stored?

EDIT: I'm using Xcode 10.2.1 (and I want to migrate from the same version)

答:
They are stored in the Xcode preferences file located at ~/Library/Preferences/com.apple.dt.Xcode.plist.

The key Xcode.AlertEvents (previously named Xcode.CustomAlertEvents) contains all the defined custom behaviors.

Title: Where are the Xcode 'behaviors' stored?


问:
reading JSON element using JS
I am receiving a JSON object from a PHP get request. It looks like this:

```<code>data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}
</code>```

I need to access the items within emp_type_id ("11" and "10" in this case).

I am able to access user_id just fine using data["user_id"] but can't figure out how to get the other items. I tried variations of:

```<code>eti=data["emp_type_id"];
var myVar = eti[0];
</code>```

I'll want to loop through all items in emp_type_id eventually and add them to a JS array.

答:
Try this:</p>

```<code>var eti = data.emp_type_id;
var myVar = eti[0];
</code>```

Title: reading JSON element using JS

Body:
I am receiving a JSON object from a PHP get request. It looks like this:

data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}

I need to access the items within emp_type_id ("11" and "10" in this case).

I am able to access user_id just fine using data["user_id"] but can't figure out how to get the other items. I tried variations of:

eti=data["emp_type_id"];
var myVar = eti[0];

I'll want to loop through all items in emp_type_id eventually and add them to a JS array.

Body:
Try this:

var eti = data.emp_type_id;
var myVar = eti[0];


问:
Can I discover the name of a caller procedure inside the called one?
When you have a procedure that is called by many others, can you discover inside the "called" procedure the name of the "caller procedure"?</p>

答: No. There is no "call-stack" you can query. You have to pass the name of the caller in a parameter (or use an user-defined variable). </p>


问:
Unity IAP not working in Apple Testflight
Having issues for the past days trying to make the IAP work on TestFlight for my 1st game app.
IAP works fine in Unity Editor (fake store) and also on Google Play (internal test track).

I don't receive any product prices from the apple store and the buy buttons have no effect (no callbacks on ProcessPurchase or OnPurchaseFailed since I show popup windows for both scenarios).

Below is the status of my app and IAP :

From other similar threads everything should be ok and working as TestFlight doesn't require the IAPs to be submitted nor it requires for sandbox users to be manually created.

Any hints on what to further test or how could I check logs/warnings/errors are much appreciated, thanks.

Tools used : Unity 2019.3.0 (IAP 2.0.6) and XCode 11.3.1

Update 1: OnInitializeFailed() is called with NoProductsAvailable err

答:
The reason why the initialization failed with NoProductsAvailable was because I didn't have an active agreement for paid apps, although it is testflight and there are no real money involved, you still need to have this setup.

Here is how it should look like :

Once this was solved the IAPs worked fine.


问:
How to Parse Json generic array with inheritance items
my question is not same is this question.
if i want to explain lets assume we have these classes (A, B, C).

```<code>@Data
@NoArgsConstructor
class A {
    private Integer x;
    private String type;

    public A(String type, Integer x) {
        this.type = type;
        this.x = x;
    }
}
</code>```

```<code>@Data
class B extends A {
    private Integer y;

    public B(Integer x, Integer y) {
        super("B", x);
        this.y = y;
    }
}
</code>```

```<code>@Data
class C extends A {
    private Integer z;

    public C(Integer x, Integer z) {
        super("C", x);
        this.z = z;
    }
}
</code>```

know i want to parse an array which their base classes is A. and with property named type i want to convert each item to its specific class.
something like this code.

```<code>public static void main(String[] args) {
        Gson gson = new Gson();
        List<A> list = new ArrayList<>();
        A a = new A("A", 0);
        list.add(a);
        B b = new B(1, 2);
        list.add(b);
        C c = new C(3, 4);
        list.add(c);
        String serializedJson = gson.toJson(list);
        List<? extends A> deserializedList = gson.fromJson(serializedJson, new TypeToken<List<? extends A>>() {
        }.getType());
        for (A item : deserializedList) {
            System.out.println(item.getType());
            if (item instanceof B) {
                System.out.println(((B) item).getY());

            } else if (item instanceof C) {
                System.out.println(((C) item).getZ());

            }
        }
    }
</code>```

serialized json is something like this

```<code>[{"x":0,"type":"A"},{"y":2,"x":1,"type":"B"},{"z":4,"x":3,"type":"C"}]
</code>```

in real world, i have something like this json and want to parse it.
but when i run the code y and z properties not printed and objects are not instance of B or C.
how to achieve to this goal to parse and create each item with type property.

答:
```<code>for(A item : deserializedList) {
  switch(item.getType()) {
    case "B":
      System.out.println(((B) item).getY());
    break;
    case "C":
      System.out.println(((C) item).getZ());
    break;
  }
}
</code>```

Body:
my question is not same is this question.
if i want to explain lets assume we have these classes (A, B, C).

@Data
@NoArgsConstructor
class A {
    private Integer x;
    private String type;

    public A(String type, Integer x) {
        this.type = type;
        this.x = x;
    }
}

@Data
class B extends A {
    private Integer y;

    public B(Integer x, Integer y) {
        super("B", x);
        this.y = y;
    }
}

@Data
class C extends A {
    private Integer z;

    public C(Integer x, Integer z) {
        super("C", x);
        this.z = z;
    }
}

know i want to parse an array which their base classes is A. and with property named type i want to convert each item to its specific class.
something like this code.

public static void main(String[] args) {
        Gson gson = new Gson();
        List list = new ArrayList<>();
        A a = new A("A", 0);
        list.add(a);
        B b = new B(1, 2);
        list.add(b);
        C c = new C(3, 4);
        list.add(c);
        String serializedJson = gson.toJson(list);
        List<? extends A> deserializedList = gson.fromJson(serializedJson, new TypeToken<List<? extends A>>() {
        }.getType());
        for (A item : deserializedList) {
            System.out.println(item.getType());
            if (item instanceof B) {
                System.out.println(((B) item).getY());

            } else if (item instanceof C) {
                System.out.println(((C) item).getZ());

            }
        }
    }

serialized json is something like this

[{"x":0,"type":"A"},{"y":2,"x":1,"type":"B"},{"z":4,"x":3,"type":"C"}]

in real world, i have something like this json and want to parse it.
but when i run the code y and z properties not printed and objects are not instance of B or C.
how to achieve to this goal to parse and create each item with type property.


问:
How to Save io.BytesIO pdfrw PDF into Django FileField
What I am trying to do is basically:

Get PDF from URL

Modify it via pdfrw

Store it in memory as
a BytesIO obj

Upload it into a Django FileField via
Model.objects.create(form=pdf_file, name="Some name")

My issue is that when the create() method runs, it saves all of the fields except for the form.

helpers.py

```<code>import io
import tempfile
from contextlib import contextmanager

import requests
import pdfrw

@contextmanager
def as_file(url):
    with tempfile.NamedTemporaryFile(suffix='.pdf') as tfile:
        tfile.write(requests.get(url).content)
        tfile.flush()
        yield tfile.name

def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path)

    ## PDF is modified here

    buf = io.BytesIO()
    print(buf.getbuffer().nbytes). # Prints "0"!
    pdfrw.PdfWriter().write(buf, template_pdf)
    buf.seek(0)
    return buf
</code>```

views.py

```<code>from django.core.files import File

class FormView(View):
    def get(self, request, *args, **kwargs):
        form_url = 'http://some-pdf-url.com'

        with as_file(form_url) as temp_form_path:
            submitted_form = write_fillable_pdf(temp_form_path, temp_form_path, {"name": "John Doe"})
            print(submitted_form.getbuffer().nbytes).  # Prints "994782"!
            FilledPDF.objects.create(form=File(submitted_form), name="Test PDF")
        return render(request, 'index.html', {})
</code>```

As you can see, print() gives out two different values as the BytesIO is populated, leading me to believe the increase in size means there is actually data in it. Is there a reason it is not saving properly into my django model instance? Also, if anyone knows a more efficient way to do this, please let me know!

答:
You can use ContentFile class in your code. I did modification accordingly in your view to save your file in filefield.

```<code>from django.core.files.base import ContentFile

class FormView(View):
    def get(self, request, *args, **kwargs):
        form_url = 'http://some-pdf-url.com'

        with as_file(form_url) as temp_form_path:
            submitted_form = write_fillable_pdf(temp_form_path, temp_form_path, {"name": "John Doe"})
            pdf_content = ContentFile(submitted_form.getvalue(), 'sample.pdf')
            FilledPDF.objects.create(form=pdf_content, name="Test PDF")
        return render(request, 'index.html', {})
</code>```

You can also use the save method to store file using the ContentFile class.

```<code>from django.core.files.base import ContentFile

    class FormView(View):
        def get(self, request, *args, **kwargs):
            form_url = 'http://some-pdf-url.com'

            with as_file(form_url) as temp_form_path:
                submitted_form = write_fillable_pdf(temp_form_path, temp_form_path, {"name": "John Doe"})
                pdf_content = ContentFile(submitted_form.getvalue())
                filled_pdf = FilledPDF()
                filled_pdf.name = "Test PDF"
                filled_pdf.form.save("sample.pdf", pdf_content, save=False)
                filled_pdf.save()
            return render(request, 'index.html', {})
</code>```

Body:
What I am trying to do is basically:

Get PDF from URL

Modify it via pdfrw

Store it in memory as
a BytesIO obj

Upload it into a Django FileField via
Model.objects.create(form=pdf_file, name="Some name")

My issue is that when the create() method runs, it saves all of the fields except for the form.

helpers.py

import io
import tempfile
from contextlib import contextmanager

import requests
import pdfrw

@contextmanager
def as_file(url):
    with tempfile.NamedTemporaryFile(suffix='.pdf') as tfile:
        tfile.write(requests.get(url).content)
        tfile.flush()
        yield tfile.name

def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path)

    ## PDF is modified here

    buf = io.BytesIO()
    print(buf.getbuffer().nbytes). # Prints "0"!
    pdfrw.PdfWriter().write(buf, template_pdf)
    buf.seek(0)
    return buf

views.py

from django.core.files import File

class FormView(View):
    def get(self, request, *args, **kwargs):
        form_url = 'http://some-pdf-url.com'

        with as_file(form_url) as temp_form_path:
            submitted_form = write_fillable_pdf(temp_form_path, temp_form_path, {"name": "John Doe"})
            print(submitted_form.getbuffer().nbytes).  # Prints "994782"!
            FilledPDF.objects.create(form=File(submitted_form), name="Test PDF")
        return render(request, 'index.html', {})

As you can see, print() gives out two different values as the BytesIO is populated, leading me to believe the increase in size means there is actually data in it. Is there a reason it is not saving properly into my django model instance? Also, if anyone knows a more efficient way to do this, please let me know!

Body:
You can use ContentFile class in your code. I did modification accordingly in your view to save your file in filefield.

from django.core.files.base import ContentFile

class FormView(View):
    def get(self, request, *args, **kwargs):
        form_url = 'http://some-pdf-url.com'

        with as_file(form_url) as temp_form_path:
            submitted_form = write_fillable_pdf(temp_form_path, temp_form_path, {"name": "John Doe"})
            pdf_content = ContentFile(submitted_form.getvalue(), 'sample.pdf')
            FilledPDF.objects.create(form=pdf_content, name="Test PDF")
        return render(request, 'index.html', {})

You can also use the save method to store file using the ContentFile class.

from django.core.files.base import ContentFile

    class FormView(View):
        def get(self, request, *args, **kwargs):
            form_url = 'http://some-pdf-url.com'

            with as_file(form_url) as temp_form_path:
                submitted_form = write_fillable_pdf(temp_form_path, temp_form_path, {"name": "John Doe"})
                pdf_content = ContentFile(submitted_form.getvalue())
                filled_pdf = FilledPDF()
                filled_pdf.name = "Test PDF"
                filled_pdf.form.save("sample.pdf", pdf_content, save=False)
                filled_pdf.save()
            return render(request, 'index.html', {})


问:
reactjs use object keys to generate html
I have the following object:

Now when i try to loop through it:

```<code>  {Object.keys(this.state.extras).forEach(key => (
                <div style={{'margin-top': '15px'}}>
                    <Addon data={this.state.extras[key]} addonTitle={key} type={key}
                           selectCallback={this.callbackSelectItem}
                           unSelectCallback={this.callbackUnSelectItem}/>
                </div>
            ))}
</code>```

No html is displayed.

i have also tried:

```<code>let extra;
Object.keys(this.state.extras).forEach(key => {
    extra += (<div style={{'margin-top': '15px'}}>
        <Addon data={this.state.extras[key]} addonTitle={key} type={key}
               selectCallback={this.callbackSelectItem}
               unSelectCallback={this.callbackUnSelectItem}/>
    </div>);
});
</code>```

However this returns "[object Object][object Object]"

Can anyone see what ive done wrong?

Update

The object key is extras when i sat it on the state

答:
Apart from what's mentioned in comment above by @Chris related to proper usage of extra vs extras in your component which may or may not be bug, main issue of not rendering HTML is below:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

forEach returns undefined, change it to use .map instead.

undefined would not render anything, while array of JSX would render as HTML (it will need key prop)

Furthermore forEach mutates underlying array so use it with caution.

Your code would probably need to be changed like below:

```<code>{Object.keys(this.state.extras).map(key => (
  <div style={{'margin-top': '15px'}} key={key}>
      <Addon data={this.state.extras[key]} addonTitle={key} type={key}
             selectCallback={this.callbackSelectItem}
             unSelectCallback={this.callbackUnSelectItem}/>
  </div>
))}
</code>```

Body:
I have the following object:

Now when i try to loop through it:

  {Object.keys(this.state.extras).forEach(key => (

                    <Addon data={this.state.extras[key]} addonTitle={key} type={key}
                           selectCallback={this.callbackSelectItem}
                           unSelectCallback={this.callbackUnSelectItem}/>

            ))}

No html is displayed.

i have also tried:

let extra;
Object.keys(this.state.extras).forEach(key => {
    extra += (

        <Addon data={this.state.extras[key]} addonTitle={key} type={key}
               selectCallback={this.callbackSelectItem}
               unSelectCallback={this.callbackUnSelectItem}/>

);
});

However this returns "[object Object][object Object]"

Can anyone see what ive done wrong?

Update

The object key is extras when i sat it on the state

Body:
Apart from what's mentioned in comment above by @Chris related to proper usage of extra vs extras in your component which may or may not be bug, main issue of not rendering HTML is below:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

forEach returns undefined, change it to use .map instead.

undefined would not render anything, while array of JSX would render as HTML (it will need key prop)

Furthermore forEach mutates underlying array so use it with caution.

Your code would probably need to be changed like below:

{Object.keys(this.state.extras).map(key => (
  <div style={{'margin-top': '15px'}} key={key}>
      <Addon data={this.state.extras[key]} addonTitle={key} type={key}
             selectCallback={this.callbackSelectItem}
             unSelectCallback={this.callbackUnSelectItem}/>
  </div>
))}


问:
how to calculate data inputs from textbox in python?
I am creating a calorie calculator. As i am new to python i am not familiar with the working of it.There is no error but the output is zero i cannot seem to figure out why the calculation is  not working.Also i am showing the output in a textbox.Can somebody check why it is not working</p>

```<code>class user:
        def __init__(self,window):
            self.window = window

            self.frame = Frame(self.window, bg = 'White', width=700,height=500)

            option = StringVar()
            dblcalorie = float()
            self.gain = gain = float()
            activity_level = float()
            self.age = Label (self.frame,text ='AGE :',fg ='black',font=('Georgia',14,'bold'))
            self.age_text = int
            self.agee = Entry(self.frame,textvariable = self.age_text, fg = 'black',width = 250)

            self.height = Label (self.frame, text='Height :', fg = 'black', font = ('Georgia', 14, 'bold'))
            self.height_text = int
            self.height1 = Entry (self.frame,textvariable = self.height_text, fg ='black', width = 250 )

            self.weight = Label (self.frame, text ='weight :', fg ='black', font =('Georgia', 14, 'bold'))
            self.weight_text = int
            self.weight1 = Entry (self.frame, textvariable = self.weight_text, fg ='black', width = 250)
            option.set("men")
            self.radio = Label (self.frame,text = 'Gender',width=25, font = ('Arial',14))
            self.male = Radiobutton (self.frame,text = 'Male',variable = option, value = "men")
            self.female = Radiobutton (self.frame,text = 'female',variable = option, value = "women")
            self.activity = Label(self.frame,text ="Activity:",fg ='black', font =('Georgia', 14, 'bold'))
            self.combo = ttk.Combobox(self.frame,values=["light","normal","heavy"])
            self.gainl=Label(self.frame,text='Gain:',fg ='black', font =('Georgia', 14, 'bold'))
            self.gain = Text(self.frame,width = 250, font = ('Arial',14))
            self.buttoncal = Button(self.frame,text='calculate',bg='gray',fg='gray12',font=('Georgia',14,'bold'),cursor='hand2',  command = lambda: self.calculate(activity_level))

        def gender(self):
               if self.option.get() =="men":
                    dblcalorie = (13.397 * int(self.weight_text.get())) + (4.799 * int(self.height_text.get())) - (5.677 * int(self.age_text.get())) + 88.362

               else:
                  dblcalorie = (13 * int(self.weight_text.get())) + (4 * int(self.height_text.get())) - ( 5 * int(self.age_text.get())) + 88

                return dblcalorie
        def activity(self,dblcalorie):

            if len(self.combo.get()) == 0:
                  messagebox.showinfo("ERROR", "please choose one activity level ")
            elif self.combo.get() == 'light':
                 activity_level = 1.375 * dblcalorie

            elif self.combo.get() == 'moderate':
                  activity_level = 1.55 * dblcalorie

            elif self.combo.get() == 'heavy':
                  activity_level = 1.725 * dblcalorie

            elif self.combo == 'extreme':
                  activity_level = 1.9 * dblcalorie

            return activity_level

        def calculate(self,activity_level):

               self.gain.insert(END,str(activity_level))
</code>```

答: the last def is not tabbed out far enough try that.</p>

Body:
I am creating a calorie calculator. As i am new to python i am not familiar with the working of it.There is no error but the output is zero i cannot seem to figure out why the calculation is  not working.Also i am showing the output in a textbox.Can somebody check why it is not working

class user:
        def __init__(self,window):
            self.window = window

            self.frame = Frame(self.window, bg = 'White', width=700,height=500)

            option = StringVar()
            dblcalorie = float()
            self.gain = gain = float()
            activity_level = float()
            self.age = Label (self.frame,text ='AGE :',fg ='black',font=('Georgia',14,'bold'))
            self.age_text = int
            self.agee = Entry(self.frame,textvariable = self.age_text, fg = 'black',width = 250)

            self.height = Label (self.frame, text='Height :', fg = 'black', font = ('Georgia', 14, 'bold'))
            self.height_text = int
            self.height1 = Entry (self.frame,textvariable = self.height_text, fg ='black', width = 250 )

            self.weight = Label (self.frame, text ='weight :', fg ='black', font =('Georgia', 14, 'bold'))
            self.weight_text = int
            self.weight1 = Entry (self.frame, textvariable = self.weight_text, fg ='black', width = 250)
            option.set("men")
            self.radio = Label (self.frame,text = 'Gender',width=25, font = ('Arial',14))
            self.male = Radiobutton (self.frame,text = 'Male',variable = option, value = "men")
            self.female = Radiobutton (self.frame,text = 'female',variable = option, value = "women")
            self.activity = Label(self.frame,text ="Activity:",fg ='black', font =('Georgia', 14, 'bold'))
            self.combo = ttk.Combobox(self.frame,values=["light","normal","heavy"])
            self.gainl=Label(self.frame,text='Gain:',fg ='black', font =('Georgia', 14, 'bold'))
            self.gain = Text(self.frame,width = 250, font = ('Arial',14))
            self.buttoncal = Button(self.frame,text='calculate',bg='gray',fg='gray12',font=('Georgia',14,'bold'),cursor='hand2',  command = lambda: self.calculate(activity_level))

        def gender(self):
               if self.option.get() =="men":
                    dblcalorie = (13.397 * int(self.weight_text.get())) + (4.799 * int(self.height_text.get())) - (5.677 * int(self.age_text.get())) + 88.362

               else:
                  dblcalorie = (13 * int(self.weight_text.get())) + (4 * int(self.height_text.get())) - ( 5 * int(self.age_text.get())) + 88

                return dblcalorie
        def activity(self,dblcalorie):

            if len(self.combo.get()) == 0:
                  messagebox.showinfo("ERROR", "please choose one activity level ")
            elif self.combo.get() == 'light':
                 activity_level = 1.375 * dblcalorie

            elif self.combo.get() == 'moderate':
                  activity_level = 1.55 * dblcalorie

            elif self.combo.get() == 'heavy':
                  activity_level = 1.725 * dblcalorie

            elif self.combo == 'extreme':
                  activity_level = 1.9 * dblcalorie

            return activity_level

        def calculate(self,activity_level):

               self.gain.insert(END,str(activity_level))


问:
Returning multiple case statements on one row in T-SQL
I'm using the following T-SQL statement to return some values:

```<code>CASE WHEN month(m.pcp_startdate) = 1 THEN m.pcp_value ELSE NULL END AS January,
CASE WHEN month(m.pcp_startdate) = 2 THEN m.pcp_value ELSE NULL END AS Febuary,
CASE WHEN month(m.pcp_startdate) = 3 THEN m.pcp_value ELSE NULL END AS March,
CASE WHEN month(m.pcp_startdate) = 4 THEN m.pcp_value ELSE NULL END AS April,
CASE WHEN month(m.pcp_startdate) = 5 THEN m.pcp_value ELSE NULL END AS May,
CASE WHEN month(m.pcp_startdate) = 6 THEN m.pcp_valuen ELSE NULL END AS June,
CASE WHEN month(m.pcp_startdate) = 7 THEN m.pcp_value ELSE NULL END AS July,
CASE WHEN month(m.pcp_startdate) = 8 THEN m.pcp_value ELSE NULL END AS August,
CASE WHEN month(m.pcp_startdate) = 9 THEN m.pcp_value ELSE NULL END AS September,
CASE WHEN month(m.pcp_startdate) = 10 THEN m.pcp_value ELSE NULL END AS October,
CASE WHEN month(m.pcp_startdate) = 11 THEN m.pcp_value ELSE NULL END AS November,
CASE WHEN month(m.pcp_startdate) = 12 THEN m.pcp_value ELSE NULL END AS December
</code>```

However this is returning all of these values on different rows

```<code>NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
</code>```

Is there any way to make them appear on the same row? Thanks!

答:
looks like a pivot table to me?

SELECT
    'amountOutstanding' as [val], [1] as Jan, [2] as Feb, [3] as Mar, [4] as Apr, [5] as May, [6] as Jun, [7] as Jul, [8] as Aug, [9] as Sep, [10] as Oct, [11] as Nov, [12] as Dec
FROM
( select [amount], [month] from m) as a
PIVOT
(
avg([amount])
FOR [month] in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
) as pt;
```

Body:
I'm using the following T-SQL statement to return some values:

CASE WHEN month(m.pcp_startdate) = 1 THEN m.pcp_value ELSE NULL END AS January,
CASE WHEN month(m.pcp_startdate) = 2 THEN m.pcp_value ELSE NULL END AS Febuary,
CASE WHEN month(m.pcp_startdate) = 3 THEN m.pcp_value ELSE NULL END AS March,
CASE WHEN month(m.pcp_startdate) = 4 THEN m.pcp_value ELSE NULL END AS April,
CASE WHEN month(m.pcp_startdate) = 5 THEN m.pcp_value ELSE NULL END AS May,
CASE WHEN month(m.pcp_startdate) = 6 THEN m.pcp_valuen ELSE NULL END AS June,
CASE WHEN month(m.pcp_startdate) = 7 THEN m.pcp_value ELSE NULL END AS July,
CASE WHEN month(m.pcp_startdate) = 8 THEN m.pcp_value ELSE NULL END AS August,
CASE WHEN month(m.pcp_startdate) = 9 THEN m.pcp_value ELSE NULL END AS September,
CASE WHEN month(m.pcp_startdate) = 10 THEN m.pcp_value ELSE NULL END AS October,
CASE WHEN month(m.pcp_startdate) = 11 THEN m.pcp_value ELSE NULL END AS November,
CASE WHEN month(m.pcp_startdate) = 12 THEN m.pcp_value ELSE NULL END AS December

However this is returning all of these values on different rows

NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
NULL    208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
208333.00   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL

Is there any way to make them appear on the same row? Thanks!


问:
System.out.println("Serializable: " + arrayList instanceof Serializable) is not printing 'Serializable' word
I tried to execute following simple code. System.out.println() is not printing word 'Serializable:'.
Output is true.

```<code>ArrayList<String> arrayList = new ArrayList<String>();
System.out.println("Serializable: " + arrayList instanceof Serializable);
</code>```

Can anyone expain why?

Thanks in advance.

答:
You are missing out a bracket. You should be writing like this : </p>

```<code>System.out.println("Serializable: " + (arrayList instanceof Serializable))
</code>```

Body:
I tried to execute following simple code. System.out.println() is not printing word 'Serializable:'.
Output is true.

ArrayList<String> arrayList = new ArrayList<String>();
System.out.println("Serializable: " + arrayList instanceof Serializable);

Can anyone expain why?

Thanks in advance.

Body:
You are missing out a bracket. You should be writing like this :

System.out.println("Serializable: " + (arrayList instanceof Serializable))


问:
How do I get the right date format after using get text on the folder date?
I have tried everything that I can think of to get the right date format. Can anybody help with this RPA-problem in UiPath. I have used the 'get text' activity to get the folder date and after that tried to use the

```<code>Datetime.ParseExact(Str variable,"dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture).
</code>```

It gives me the error:

Assign: String was not recognized as a valid DateTime.

Your help is much appreciated.

edit: I have now sought help from a friend who figured it out. The error was in the string, which could not be seen, because there was an invisible character in the string that I extracted through 'get text' activity. The solution is in 2 steps:

assign another variable to the exact same date and use an if statement to find out if these two strings are equal and you will find out that they are not.

Now use a regex to capture only digits and slash/hyphen which will get rid of the invisible character.

答: Try to use "dd_MM_yyyy" instead of "dd/MM/yyyy".

Body:
I have tried everything that I can think of to get the right date format. Can anybody help with this RPA-problem in UiPath. I have used the 'get text' activity to get the folder date and after that tried to use the

Datetime.ParseExact(Str variable,"dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture).

It gives me the error:

Assign: String was not recognized as a valid DateTime.

Your help is much appreciated.

edit: I have now sought help from a friend who figured it out. The error was in the string, which could not be seen, because there was an invisible character in the string that I extracted through 'get text' activity. The solution is in 2 steps:

assign another variable to the exact same date and use an if statement to find out if these two strings are equal and you will find out that they are not.

Now use a regex to capture only digits and slash/hyphen which will get rid of the invisible character.


问:
Is there any way i can check if mosquitto is indeed using my custom mosquitto.conf file instead of the default one?
The question is self explanatory

I am running mosquitto in a container and i am persisting /mosquitto using EFS so mosquitto.conf is persisting

I want to test if mosquitto is indeed using my custom mosquitto.conf instead of the default one

How do i do this ?

```<code>persistence true
persistence_location /mosquitto/data/
listener 1883
listener 9001
protocol websockets
</code>```

UPDATE

```<code>log_dest file /mosquitto/log/mosquitto.log
log_type all
connection_messages true
log_timestamp true
log_timestamp_format [%H:%M:%S]
</code>```

Adding this to mosquitto.conf worked as suggested by hardillb

答:
Mosquitto prints out the config file it is using on the second line of its log output when started.

Without changing something fundamental e.g. the port it listens on, and testing it you have assume that it is using the file at location.

Body:
The question is self explanatory

I am running mosquitto in a container and i am persisting /mosquitto using EFS so mosquitto.conf is persisting

I want to test if mosquitto is indeed using my custom mosquitto.conf instead of the default one

How do i do this ?

persistence true
persistence_location /mosquitto/data/
listener 1883
listener 9001
protocol websockets

UPDATE

log_dest file /mosquitto/log/mosquitto.log
log_type all
connection_messages true
log_timestamp true
log_timestamp_format [%H:%M:%S]

Adding this to mosquitto.conf worked as suggested by hardillb


问:
Google cloud Bigtable read multiple rows
I have a set of known rowkeys like this

```<code>h1-r1-en
h1-r1-es
h1-r1-fr
h1-r1-pt
h1-r2-en
h1-r2-es
h1-r2-fr
h1-r2-pt
</code>```

My question is, should I perform a range scan to retrieve all the rows within range h1-r* or would be better to perform one read query for each rowkey?

答:
Choosing to do a range scan vs a scan on your specific queries really depends on what you have planned for this data. If you have do a range scan, then any other data within that prefix "h1-r*" would get included and not be as performant. But if the ONLY rows starting with "h1-r" are those specific rows, then it would perform the same way and I'd recommend using a prefix scan to simplify your code.

Here are code snippets for each way and we are working on integrating these into our documentation at the moment, but you can check out more on GitHub.

Prefix scan:

```<code>try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
  Query query = Query.create(tableId).prefix("h1-r");
  ServerStream<Row> rows = dataClient.readRows(query);
  for (Row row : rows) {
    // do something
  }
} catch (IOException e) {
  System.out.println(
      "Unable to initialize service client, as a network error occurred: \n" + e.toString());
}
</code>```

Adding individual rows:

```<code>try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
  Query query = Query.create(tableId)
         .rowKey("h1-r1-en")
         .rowKey("h1-r1-es")
         .rowKey("h1-r1-fr"); // Continue adding all your rows this way.
  ServerStream<Row> rows = dataClient.readRows(query);
  for (Row row : rows) {
    // do something
  }
} catch (IOException e) {
  System.out.println(
      "Unable to initialize service client, as a network error occurred: \n" + e.toString());
}
</code>```

Body:
I have a set of known rowkeys like this

h1-r1-en
h1-r1-es
h1-r1-fr
h1-r1-pt
h1-r2-en
h1-r2-es
h1-r2-fr
h1-r2-pt

My question is, should I perform a range scan to retrieve all the rows within range h1-r* or would be better to perform one read query for each rowkey?

Body:
Choosing to do a range scan vs a scan on your specific queries really depends on what you have planned for this data. If you have do a range scan, then any other data within that prefix "h1-r*" would get included and not be as performant. But if the ONLY rows starting with "h1-r" are those specific rows, then it would perform the same way and I'd recommend using a prefix scan to simplify your code.

Here are code snippets for each way and we are working on integrating these into our documentation at the moment, but you can check out more on GitHub.

Prefix scan:

try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
  Query query = Query.create(tableId).prefix("h1-r");
  ServerStream<Row> rows = dataClient.readRows(query);
  for (Row row : rows) {
    // do something
  }
} catch (IOException e) {
  System.out.println(
      "Unable to initialize service client, as a network error occurred: \n" + e.toString());
}

Adding individual rows:

try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
  Query query = Query.create(tableId)
         .rowKey("h1-r1-en")
         .rowKey("h1-r1-es")
         .rowKey("h1-r1-fr"); // Continue adding all your rows this way.
  ServerStream<Row> rows = dataClient.readRows(query);
  for (Row row : rows) {
    // do something
  }
} catch (IOException e) {
  System.out.println(
      "Unable to initialize service client, as a network error occurred: \n" + e.toString());
}


问:
How To Get Latitude & Longitude with python
I am trying to retrieve the longitude & latitude of a physical address ,through the below script .But I am getting the error. I have already installed googlemaps.

```<code>#!/usr/bin/env python
import urllib,urllib2

"""This Programs Fetch The Address"""

from googlemaps import GoogleMaps

address='Mahatma Gandhi Rd, Shivaji Nagar, Bangalore, KA 560001'

add=GoogleMaps().address_to_latlng(address)
print add
</code>```

Output:

```<code>Traceback (most recent call last):
  File "Fetching.py", line 12, in <module>
    add=GoogleMaps().address_to_latlng(address)
  File "/usr/local/lib/python2.7/dist-packages/googlemaps.py", line 310, in address_to_latlng
    return tuple(self.geocode(address)['Placemark'][0]['Point']['coordinates'][1::-1])
  File "/usr/local/lib/python2.7/dist-packages/googlemaps.py", line 259, in geocode
    url, response = fetch_json(self._GEOCODE_QUERY_URL, params=params)
  File "/usr/local/lib/python2.7/dist-packages/googlemaps.py", line 50, in fetch_json
    response = urllib2.urlopen(request)
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 407, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 520, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 445, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 379, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 528, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
</code>```

答:
did you try to use the the library geopy ?
https://pypi.org/project/geopy/

It works for python 2.7 till 3.8.
It also work for OpenStreetMap Nominatim, Google Geocoding API (V3) and others.

Hope it can help you.

Body:
I am trying to retrieve the longitude & latitude of a physical address ,through the below script .But I am getting the error. I have already installed googlemaps.

#!/usr/bin/env python
import urllib,urllib2

"""This Programs Fetch The Address"""

from googlemaps import GoogleMaps

address='Mahatma Gandhi Rd, Shivaji Nagar, Bangalore, KA 560001'

add=GoogleMaps().address_to_latlng(address)
print add

Output:

Traceback (most recent call last):
  File "Fetching.py", line 12, in <module>
    add=GoogleMaps().address_to_latlng(address)
  File "/usr/local/lib/python2.7/dist-packages/googlemaps.py", line 310, in address_to_latlng
    return tuple(self.geocode(address)['Placemark'][0]['Point']['coordinates'][1::-1])
  File "/usr/local/lib/python2.7/dist-packages/googlemaps.py", line 259, in geocode
    url, response = fetch_json(self._GEOCODE_QUERY_URL, params=params)
  File "/usr/local/lib/python2.7/dist-packages/googlemaps.py", line 50, in fetch_json
    response = urllib2.urlopen(request)
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 407, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 520, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 445, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 379, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 528, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden


问:
Check if variable exists - Terraform template syntax
I'm trying to check if a variable exists on a template file using terraform template syntax, but I get error that This object does not have an attribute named "proxy_set_header.

```<code>$ cat nginx.conf.tmpl

%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if location.proxy_set_header }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }
</code>```

I tried with if location.proxy_set_header != "" and if location.proxy_set_header without success.

How to check if a variable exists with the String Templates?

答:
I would do something like the following, using contains and keys

```<code>%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if contains(keys(location), "proxy_set_header") }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }
</code>```

The parsed JSON essentially becomes a map which can be checked for key contents.

I tested this with the following code

```<code>data "template_file" "init" {
  template = file("${path.module}/file.template")
  vars = {
    locations = <<DOC
[
  {
    "path": "foo",
    "proxy_set_header": "foohdr"
  },
  {
    "path": "bar"
  }
]
DOC
  }
}

output "answer" {
  value = data.template_file.init.rendered
}
</code>```

and it had the following output

```<code>Outputs:

answer =
location foo {

       proxy_set_header foohdr;

}

location bar {

}

</code>```

Body:
I'm trying to check if a variable exists on a template file using terraform template syntax, but I get error that This object does not have an attribute named "proxy_set_header.

$ cat nginx.conf.tmpl

%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if location.proxy_set_header }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }

I tried with if location.proxy_set_header != "" and if location.proxy_set_header without success.

How to check if a variable exists with the String Templates?

Body:
I would do something like the following, using contains and keys

%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if contains(keys(location), "proxy_set_header") }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }

The parsed JSON essentially becomes a map which can be checked for key contents.

I tested this with the following code

data "template_file" "init" {
  template = file("${path.module}/file.template")
  vars = {
    locations = <<DOC
[
  {
    "path": "foo",
    "proxy_set_header": "foohdr"
  },
  {
    "path": "bar"
  }
]
DOC
  }
}

output "answer" {
  value = data.template_file.init.rendered
}

and it had the following output

Outputs:

answer =
location foo {

       proxy_set_header foohdr;

}

location bar {

}