问:
Import node and edge CSV using gephi toolkit in java
I need to develop a graph using gephi toolkit in Java. I have my node and edge data in CSV format. All the toolkit tutorials have syntax to import a gml or gexf format. Since I have 2 CSV files can anyone tell me the syntax of importing this csv's in Java using gephi toolkit jar?</p>

答:
It's better for you to try to import csv file by gephi-tool-kit and gephi at the same time to see if there is any problem, now I will show you the way I found to import csv file by gephi-toolkit step by step.

Here I use NetBeans IDE 8.2 with the gephi-toolkit-0.9.2-all.jar and refer to several demos from github.

After create a new Java project and a new Java class like here my test class named Transfer95, of course you also need to add the gephi-toolkit jar file to your library. According to the tutorial and javadoc of gephi-toolkit, there is much changes to use the new toolkit, it seems that the import methods can be used   to import several different types of file like gexf and csv file.

The first several lines of code are the same common code to init project and get controller or container.

```<code>//Init a project - and therefore a workspace
ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
pc.newProject();
Workspace workspace = pc.getCurrentWorkspace();

//Get controllers and models
ImportController importController = Lookup.getDefault().lookup(ImportController.class);

//Get models and controllers for this new workspace - will be useful later
GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getGraphModel();

//Import file
Container container;
try {
    File file_node = new File(getClass().getResource("/resourceason2/club_1_1995.csv").toURI());
    container = importController.importFile(file_node);
    container.getLoader().setEdgeDefault(EdgeDirectionDefault.DIRECTED);   //Force DIRECTED
    container.getLoader().setAllowAutoNode(true);  //create missing nodes
    container.getLoader().setEdgesMergeStrategy(EdgeMergeStrategy.SUM);
    container.getLoader().setAutoScale(true);

} catch (Exception ex) {
    ex.printStackTrace();
    return;
}
</code>```

here I just try to import the node csv file with the same importController method of gexf in demos of ImportExport or HeadlessSimple, and it worked, but here we also need to import edge csv file to the network, and I finally found the answer from demo of GenerateGraph which can append new container to the current workspace, so the code of import csv file after is

```<code>    //Init a project - and therefore a workspace
    ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
    pc.newProject();
    Workspace workspace = pc.getCurrentWorkspace();

    //Get controllers and models
    ImportController importController = Lookup.getDefault().lookup(ImportController.class);

    //Get models and controllers for this new workspace - will be useful later
    GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getGraphModel();

    //Import file
    Container container,container2;
    try {
        File file_node = new File(getClass().getResource("/resourceason2/club_1_1995.csv").toURI());
        container = importController.importFile(file_node);
        container.getLoader().setEdgeDefault(EdgeDirectionDefault.DIRECTED);   //Force DIRECTED
        container.getLoader().setAllowAutoNode(true);  //create missing nodes
        container.getLoader().setEdgesMergeStrategy(EdgeMergeStrategy.SUM);
        container.getLoader().setAutoScale(true);

        File file_edge = new File(getClass().getResource("/resourceason2/transfer_1_1995.csv").toURI());
        container2 = importController.importFile(file_edge);
        container2.getLoader().setEdgeDefault(EdgeDirectionDefault.DIRECTED);   //Force DIRECTED
        container2.getLoader().setAllowAutoNode(true);  //create missing nodes
        container2.getLoader().setEdgesMergeStrategy(EdgeMergeStrategy.SUM);
        container2.getLoader().setAutoScale(true);

    } catch (Exception ex) {
        ex.printStackTrace();
        return;
    }
</code>```

here we need to append the new container to the same workspace like

```<code>    //Append imported data to GraphAPI
    importController.process(container, new DefaultProcessor(), workspace);
    importController.process(container2, new AppendProcessor(), workspace); //Use AppendProcessor to append to current workspace
</code>```

and finally check if your network is correct

```<code>    //See if graph is well imported
    DirectedGraph graph = graphModel.getDirectedGraph();
    System.out.println("Nodes: " + graph.getNodeCount());
    System.out.println("Edges: " + graph.getEdgeCount());
</code>```

and that's why I advise you to test the csv file import by gephi and gephi-toolkit at the same time. And that's my dummy code,hopefully it will help you and there may be better answer.

References

Javadoc

gephi toolkit demo

gephi forum

Body:
It's better for you to try to import csv file by gephi-tool-kit and gephi at the same time to see if there is any problem, now I will show you the way I found to import csv file by gephi-toolkit step by step.

Here I use NetBeans IDE 8.2 with the gephi-toolkit-0.9.2-all.jar and refer to several demos from github.

After create a new Java project and a new Java class like here my test class named Transfer95, of course you also need to add the gephi-toolkit jar file to your library. According to the tutorial and javadoc of gephi-toolkit, there is much changes to use the new toolkit, it seems that the import methods can be used   to import several different types of file like gexf and csv file.

The first several lines of code are the same common code to init project and get controller or container.

//Init a project - and therefore a workspace
ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
pc.newProject();
Workspace workspace = pc.getCurrentWorkspace();

//Get controllers and models
ImportController importController = Lookup.getDefault().lookup(ImportController.class);

//Get models and controllers for this new workspace - will be useful later
GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getGraphModel();

//Import file
Container container;
try {
    File file_node = new File(getClass().getResource("/resourceason2/club_1_1995.csv").toURI());
    container = importController.importFile(file_node);
    container.getLoader().setEdgeDefault(EdgeDirectionDefault.DIRECTED);   //Force DIRECTED
    container.getLoader().setAllowAutoNode(true);  //create missing nodes
    container.getLoader().setEdgesMergeStrategy(EdgeMergeStrategy.SUM);
    container.getLoader().setAutoScale(true);

} catch (Exception ex) {
    ex.printStackTrace();
    return;
}

here I just try to import the node csv file with the same importController method of gexf in demos of ImportExport or HeadlessSimple, and it worked, but here we also need to import edge csv file to the network, and I finally found the answer from demo of GenerateGraph which can append new container to the current workspace, so the code of import csv file after is

    //Init a project - and therefore a workspace
    ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
    pc.newProject();
    Workspace workspace = pc.getCurrentWorkspace();

    //Get controllers and models
    ImportController importController = Lookup.getDefault().lookup(ImportController.class);

    //Get models and controllers for this new workspace - will be useful later
    GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getGraphModel();

    //Import file
    Container container,container2;
    try {
        File file_node = new File(getClass().getResource("/resourceason2/club_1_1995.csv").toURI());
        container = importController.importFile(file_node);
        container.getLoader().setEdgeDefault(EdgeDirectionDefault.DIRECTED);   //Force DIRECTED
        container.getLoader().setAllowAutoNode(true);  //create missing nodes
        container.getLoader().setEdgesMergeStrategy(EdgeMergeStrategy.SUM);
        container.getLoader().setAutoScale(true);

        File file_edge = new File(getClass().getResource("/resourceason2/transfer_1_1995.csv").toURI());
        container2 = importController.importFile(file_edge);
        container2.getLoader().setEdgeDefault(EdgeDirectionDefault.DIRECTED);   //Force DIRECTED
        container2.getLoader().setAllowAutoNode(true);  //create missing nodes
        container2.getLoader().setEdgesMergeStrategy(EdgeMergeStrategy.SUM);
        container2.getLoader().setAutoScale(true);

    } catch (Exception ex) {
        ex.printStackTrace();
        return;
    }

here we need to append the new container to the same workspace like

    //Append imported data to GraphAPI
    importController.process(container, new DefaultProcessor(), workspace);
    importController.process(container2, new AppendProcessor(), workspace); //Use AppendProcessor to append to current workspace

and finally check if your network is correct

    //See if graph is well imported
    DirectedGraph graph = graphModel.getDirectedGraph();
    System.out.println("Nodes: " + graph.getNodeCount());
    System.out.println("Edges: " + graph.getEdgeCount());

and that's why I advise you to test the csv file import by gephi and gephi-toolkit at the same time. And that's my dummy code,hopefully it will help you and there may be better answer.

References

Javadoc

gephi toolkit demo

gephi forum


来源: stackexchange

问:
JavaScript changing CSS not working inside of if statement
Here is my html :

```<code><a class="btn btn-primary btn-lg" id="signUpBtn" href="./pages/createaccount.php" onmouseover="rotateBtn()"> Sign up »</a>
</code>```

Here is the JS... the style changes don't work when I take it out of the if statement. I need the if statement to toggle back and forth between the two rotations.
Doing this to learn, want to use JS and also see how it works with jQuery

```<code>function rotateBtn() {
var isRotated = 0;
document.getElementById("signUpBtn").style.transformOrigin = "top center";
document.getElementById("signUpBtn").style.transition = "1s ease-in-out";

if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}
</code>```

答:
I think you don't need to use an if else statement, you only need to add a delay between both animation. So you may try this :

You need to make your element inline-block or block for the rotation to work.

document.getElementById("signUpBtn").style.transformOrigin = "top center";
document.getElementById("signUpBtn").style.display = "inline-block";
document.getElementById("signUpBtn").style.transition = "1s ease-in-out";

function rotateBtn() {
  document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";

  setTimeout(function() {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
  },1000);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
     Sign up »</code>```

You may also do this using only CSS like this :

#signUpBtn {
  display: inline-block;
  transform-origin: top center;
  transition: 1s ease-in-out;
}

#signUpBtn:hover {
  animation: rotate 2s;
}

@keyframes rotate {
  0% {
    transform: rotateY(0deg);
  }
  50% {
    transform: rotateY(90deg);
  }
  100% {
    transform: rotateY(0deg);
    ;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
     Sign up »</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is my html :

 Sign up »

Here is the JS... the style changes don't work when I take it out of the if statement. I need the if statement to toggle back and forth between the two rotations.
Doing this to learn, want to use JS and also see how it works with jQuery

function rotateBtn() {
var isRotated = 0;
document.getElementById("signUpBtn").style.transformOrigin = "top center";
document.getElementById("signUpBtn").style.transition = "1s ease-in-out";

if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}

Body:
I think you don't need to use an if else statement, you only need to add a delay between both animation. So you may try this :

You need to make your element inline-block or block for the rotation to work.

document.getElementById("signUpBtn").style.transformOrigin = "top center";
document.getElementById("signUpBtn").style.display = "inline-block";
document.getElementById("signUpBtn").style.transition = "1s ease-in-out";

function rotateBtn() {
  document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";

  setTimeout(function() {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
  },1000);
}

<a class="btn btn-primary btn-lg" id="signUpBtn" href="./pages/createaccount.php" onmouseover="rotateBtn()">
     Sign up &raquo;</a>

You may also do this using only CSS like this :

#signUpBtn {
  display: inline-block;
  transform-origin: top center;
  transition: 1s ease-in-out;
}

#signUpBtn:hover {
  animation: rotate 2s;
}

@keyframes rotate {
  0% {
    transform: rotateY(0deg);
  }
  50% {
    transform: rotateY(90deg);
  }
  100% {
    transform: rotateY(0deg);
    ;
  }
}

<a class="btn btn-primary btn-lg" id="signUpBtn" href="./pages/createaccount.php">
     Sign up &raquo;</a>


问:
Check if Localizable.strings file is valid
I am creating Localizable.strings file programatically. I am downloading the file from server and showing the localization from that file.

But if there is some error in file then my localization don't work. It shows me the keys. If on server I edit the localization file and I added string as

```<code>"HELLO_WORLD" = Hello
</code>```

Here, the key is correct but value is not in correct format. The format should be as

```<code>"HELLO_WORLD" = "Hello";
</code>```

How can I programatically check at runtime if my Localizable.strings file does not contain any error and is valid?

答:
There are many answers but they wasn't focus on the main points is "programmatically check at runtime".
My suggestion is:

Programmatically find the path of your downloaded file program (Like .../Documents/YourApp.bundle/fr-FR.lproj/Localizable.strings)

```<code>NSString *path = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings" inDirectory:nil forLocalization:@"ja"];
</code>```

Convert it to array of strings

```<code>NSString *fileContents = [NSString stringWithContentsOfFile:localizablePath encoding:NSUTF8StringEncoding error:nil];
NSArray *allLinedStrings = [fileContents componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
</code>```

Check all line from allLinedStrings manually or with Regular Expression. Following code is an example of manually check with some simple rules:

```<code>for (NSString *line in allLinedStrings) {
    if (line.length >= 2) {
        NSString *firstTwoCharacters = [line substringToIndex:2];

        if (![firstTwoCharacters isEqualToString:@"//"]){
            if (![line containsString:@"\";"]) {
                NSLog(@"Invalid line");
            }

            NSUInteger numberOfOccurrences = [[line componentsSeparatedByString:@"\""] count];
            if (numberOfOccurrences < 4) {
                NSLog(@"Invalid line");
            }
        }
    }
    else if (line.length > 0) {
        NSLog(@"Invalid line");
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating Localizable.strings file programatically. I am downloading the file from server and showing the localization from that file.

But if there is some error in file then my localization don't work. It shows me the keys. If on server I edit the localization file and I added string as

"HELLO_WORLD" = Hello

Here, the key is correct but value is not in correct format. The format should be as

"HELLO_WORLD" = "Hello";

How can I programatically check at runtime if my Localizable.strings file does not contain any error and is valid?

Body:
There are many answers but they wasn't focus on the main points is "programmatically check at runtime".
My suggestion is:

Programmatically find the path of your downloaded file program (Like .../Documents/YourApp.bundle/fr-FR.lproj/Localizable.strings)

NSString *path = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings" inDirectory:nil forLocalization:@"ja"];

Convert it to array of strings

NSString *fileContents = [NSString stringWithContentsOfFile:localizablePath encoding:NSUTF8StringEncoding error:nil];
NSArray *allLinedStrings = [fileContents componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];

Check all line from allLinedStrings manually or with Regular Expression. Following code is an example of manually check with some simple rules:

for (NSString *line in allLinedStrings) {
    if (line.length >= 2) {
        NSString *firstTwoCharacters = [line substringToIndex:2];

        if (![firstTwoCharacters isEqualToString:@"//"]){
            if (![line containsString:@"\";"]) {
                NSLog(@"Invalid line");
            }

            NSUInteger numberOfOccurrences = [[line componentsSeparatedByString:@"\""] count];
            if (numberOfOccurrences < 4) {
                NSLog(@"Invalid line");
            }
        }
    }
    else if (line.length > 0) {
        NSLog(@"Invalid line");
    }
}


问:
Remove object from array1 where object.prop is in array2
E.g:

```<code>const array1 = [
  {id: 1, name: 'Bob', age: 29},
  {id: 2, name: 'Anne', age: 18},
  {id: 3, name: 'Dave', age: 29},
  {id: 4, name: 'Barry', age: 50},
  {id: 5, name: 'Jill', age: 35},
];

const array2 = [29, 50];
</code>```

I want to go through array1 and remove all objects where object.age is in array2. I have lodash at my disposable but their documentation confuses me...

答:
You can use Array#filter and Array#includes to get the desired result. Filter on the first array and check if the second array contains current item's age and reverse the result.

const array1 = [
  {id: 1, name: 'Bob', age: 29},
  {id: 2, name: 'Anne', age: 18},
  {id: 3, name: 'Dave', age: 29},
  {id: 4, name: 'Barry', age: 50},
  {id: 5, name: 'Jill', age: 35},
];

const array2 = [29, 50];

const mapped = array1.filter(item => !array2.includes(item.age));

console.log(mapped);```

Body:
E.g:

const array1 = [
  {id: 1, name: 'Bob', age: 29},
  {id: 2, name: 'Anne', age: 18},
  {id: 3, name: 'Dave', age: 29},
  {id: 4, name: 'Barry', age: 50},
  {id: 5, name: 'Jill', age: 35},
];

const array2 = [29, 50];

I want to go through array1 and remove all objects where object.age is in array2. I have lodash at my disposable but their documentation confuses me...


问:
How to access The Weather Company (TWC) Data using IBM Data Science Experience (DSX)
I'm using IBM Data Science Experience (DSX), https://datascience.ibm.com/. I use R with RStudio.

Is it possible to access data using R from DSX?

If not, any alternatives.

答:
Assuming you have a DSX account, you should also have an IBM Cloud account as well. If you add the Weather Company Data service inside IBM Cloud, you will then be given service credentials (i.e. username and password). With the credentials, you can then use the httr library, for example, in RStudio to make HTTP requests using the Weather Company API like:

```<code>library(httr)

r <- GET("https://<username>:<password>@twcservice.mybluemix.net:443/api/weather/v1/geocode/45.42/75.69/forecast/hourly/48hour.json?units=m&language=en-US")

content(r, "text")

[1] "{\"metadata\":{\"language\":\"en-US\",\"transaction_id\":\"1512488325604:776158712\",\"version\":\"1\",\"latitude\":45.42,\"longitude\":75.69,\"units\":\"m\",\"expire_time_gmt\":1512488925,\"status_code\":200},\"forecasts\":[{\"class\":\"fod_short_range_hourly\",\"expire_time_gmt\":1512488925,\"fcst_valid\":1512489600,\"fcst_valid_local\":\"2017-12-05T22:00:00+0600\",\"num\":1,\"day_ind\":\"N\",\"temp\":-5,\"dewpt\":-5,\"hi\":-5,\"wc\":-8,\"feels_like\":-8,\"icon_extd\":2600,\"wxman\":\"wx1210\",\"icon_code\":26,\"dow\":\"Tuesday\",\"phrase_12char\":\"Cloudy\",\"phrase_22char\":\"Cloudy\",\"phrase_32char\":\"Cloudy\",\"subphrase_pt1\":\"Cloudy\",\"subphrase_pt2\":\"\",\"subphrase_pt3\":\"\",\"pop\":0,\"precip_type\":\"snow\",\"qpf\":0.0,\"snow_qpf\":0.0,\"rh\":100,\"wspd\":6,\"wdir\":236,\"wdir_cardinal\":\"SW\",\"gust\":null,\"clds\":81,\"vis\":16.0,\"mslp\":1034.4,\"uv_index_raw\":0,\"uv_index\":0,\"uv_warning\":0,\"uv_desc\":\"Low\",\"golf_index\":null,\"golf_category\":\"\",\"... <truncated>
</code>```

This will give you a 48-hour weather forecast for Ottawa, Canada.

To get a data frame of the results use something like:

```<code>library(httr)
library(jsonlite)

r <- GET("https://<username>:<password>@twcservice.mybluemix.net:443/api/weather/v1/geocode/45.42/75.69/forecast/hourly/48hour.json?units=m&language=en-US")

weather <- content(r, "text")

wData <- fromJSON(weather)
weatherDF <- data.frame(wData)
</code>```

Some examples to show you how to use the Weather Company API on IBM Cloud is here https://console.bluemix.net/docs/services/Weather/weather_tutorials_samples.html#tutorials_samples.

Body:
Assuming you have a DSX account, you should also have an IBM Cloud account as well. If you add the Weather Company Data service inside IBM Cloud, you will then be given service credentials (i.e. username and password). With the credentials, you can then use the httr library, for example, in RStudio to make HTTP requests using the Weather Company API like:

library(httr)

r <- GET("https://<username>:<password>@twcservice.mybluemix.net:443/api/weather/v1/geocode/45.42/75.69/forecast/hourly/48hour.json?units=m&language=en-US")

content(r, "text")

[1] "{\"metadata\":{\"language\":\"en-US\",\"transaction_id\":\"1512488325604:776158712\",\"version\":\"1\",\"latitude\":45.42,\"longitude\":75.69,\"units\":\"m\",\"expire_time_gmt\":1512488925,\"status_code\":200},\"forecasts\":[{\"class\":\"fod_short_range_hourly\",\"expire_time_gmt\":1512488925,\"fcst_valid\":1512489600,\"fcst_valid_local\":\"2017-12-05T22:00:00+0600\",\"num\":1,\"day_ind\":\"N\",\"temp\":-5,\"dewpt\":-5,\"hi\":-5,\"wc\":-8,\"feels_like\":-8,\"icon_extd\":2600,\"wxman\":\"wx1210\",\"icon_code\":26,\"dow\":\"Tuesday\",\"phrase_12char\":\"Cloudy\",\"phrase_22char\":\"Cloudy\",\"phrase_32char\":\"Cloudy\",\"subphrase_pt1\":\"Cloudy\",\"subphrase_pt2\":\"\",\"subphrase_pt3\":\"\",\"pop\":0,\"precip_type\":\"snow\",\"qpf\":0.0,\"snow_qpf\":0.0,\"rh\":100,\"wspd\":6,\"wdir\":236,\"wdir_cardinal\":\"SW\",\"gust\":null,\"clds\":81,\"vis\":16.0,\"mslp\":1034.4,\"uv_index_raw\":0,\"uv_index\":0,\"uv_warning\":0,\"uv_desc\":\"Low\",\"golf_index\":null,\"golf_category\":\"\",\"... <truncated>

This will give you a 48-hour weather forecast for Ottawa, Canada.

To get a data frame of the results use something like:

library(httr)
library(jsonlite)

r <- GET("https://<username>:<password>@twcservice.mybluemix.net:443/api/weather/v1/geocode/45.42/75.69/forecast/hourly/48hour.json?units=m&language=en-US")

weather <- content(r, "text")

wData <- fromJSON(weather)
weatherDF <- data.frame(wData)

Some examples to show you how to use the Weather Company API on IBM Cloud is here https://console.bluemix.net/docs/services/Weather/weather_tutorials_samples.html#tutorials_samples.


问:
AWS Lambda Edit Code Inline shows "Loading your function..." continuously
Edit Code Inline shows "Loading your function..." continuously and never actually loads the function.

And since function does not load, you obviously can not edit it.

I think there was some kind of update today (Nov 30, 2017) to Lambda because when you click on a function to edit it, there is a new section at the top that shows CONFIGURATION and says ADD TRIGGER which was not there yesterday.

And when you scroll down to the Function Code section, it just says "Loading your function..." and never does anything else.

Anybody else seeing this odd behavior?

EDIT: Using Firefox 57 on Windows 10. I get the following warnings/errors when I check Firefox console:

WARNINGS:

window.controllers/Controllers is deprecated. Do not use it for UA detection.  ace.js:1:18479

Use of getPreventDefault() is deprecated.  Use defaultPrevented instead. globalnav-fe3b9e5995ba8d342d395cb57493ce54ac2b40bb.gz.js:2:39229

window.controllers/Controllers is deprecated. Do not use it for UA detection. environment-default.js:5987

The ‘content’ attribute of Window objects is deprecated.  Please use ‘window.top’ instead. home

ERRORS:

Unhandled promise rejection
DOMException {  }
polyfill.js:4326:11
onUnhandled/https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:4326:11
[90]https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:1786:27
onUnhandled/<
https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:4320:16
[46]https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:993:25

https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:2154:7
run
https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:2140:5
listener
https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:2144:3

Unhandled promise rejection
DOMException {  }
polyfill.js:4326:11
onUnhandled/https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:4326:11
[90]https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:1786:27
onUnhandled/<
https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:4320:16
[46]https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:993:25

https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:2154:7
run
https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:2140:5
listener
https://d3ifj4k507k5fs.cloudfront.net/ide-164cb54be56918ce7c55af08ee13c6339e8ebc5c/polyfill.js:2144:3

答:
This is happening in chrome as chrome is disabling the use of cookies from cloudfront domain.

Go to address bar and there you would see a icon that says there are some cookies blocked on this website.

Click on it.

Click on manage.

Click on Blocked.

Click on allow to couldfront domain.

Reload page.

I have tried it and it's working for me.

Edit: This could also be tried on other browsers that are facing this issue.


问:
Seed error in Laravel 5.5
I am facing seeding issue.My AddressessTableSeeder.php file is like below

```<code>use Illuminate\Database\Seeder;

class AddressessTableSeeder extends Seeder
{
    public function run()
    {
        factory(App\Address::class, 50)->create()->each(function ($u)
        {
            $u->users()->save(factory(App\User::class)->make());
        });
    }
}
</code>```

My Address.php file is like below

```<code>class Address extends Model
{
    protected $fillable = ['user_id', 'name', 'address','mobile_no','image','email'];

    public function users() {
        return $this->belongsTo(User::class);
    }
}
</code>```

I am getting error like below

答:
Use associate and create the user before associating so you can get the id before saving it

```<code>factory(App\Address::class, 50)->create()->each(function ($u)
{
    $u->users()->associate(factory(App\User::class)->create())->save();
});
</code>```

Title: Seed error in Laravel 5.5

Body:
I am facing seeding issue.My AddressessTableSeeder.php file is like below

use Illuminate\Database\Seeder;

class AddressessTableSeeder extends Seeder
{
    public function run()
    {
        factory(App\Address::class, 50)->create()->each(function ($u)
        {
            $u->users()->save(factory(App\User::class)->make());
        });
    }
}

My Address.php file is like below

class Address extends Model
{
    protected $fillable = ['user_id', 'name', 'address','mobile_no','image','email'];

    public function users() {
        return $this->belongsTo(User::class);
    }
}

I am getting error like below

Body:
Use associate and create the user before associating so you can get the id before saving it

factory(App\Address::class, 50)->create()->each(function ($u)
{
    $u->users()->associate(factory(App\User::class)->create())->save();
});


问:
Why this binary search implementation causes overflow?
In the implementation of binary search

```<code>int search(int[] A, int K) {
  int l = 0;
  int u = A.length - 1;
  int m
  while ( l <= u ) {
     m = (l+u)/2; // why this can cause overflow
     ...
  }
}
</code>```

The correct method is as follows:

```<code>m = l + (u -l )/2;
</code>```

I don't know why the updated statement has no overflow issue. Based on my understanding,
soon or later, the updated statement will also have overflow issue.

答:
The orignal may have overflow because l+u could be greater than the maximum value an int can handle (e.g. if both l and u were INT_MAX then their sum would obviously exceed INT_MAX).

The correct method can't overflow, because u-l obviously won't overflow, and l+(u-l)/2 is guaranteed to be <=u, so can't overflow either.

Body:
In the implementation of binary search

int search(int[] A, int K) {
  int l = 0;
  int u = A.length - 1;
  int m
  while ( l <= u ) {
     m = (l+u)/2; // why this can cause overflow
     ...
  }
}

The correct method is as follows:

m = l + (u -l )/2;

I don't know why the updated statement has no overflow issue. Based on my understanding,
soon or later, the updated statement will also have overflow issue.

ContentLicense: CC BY-SA 2.5


问:
How to correctly use pointers in my c program
So I turned in this code for my assignment to my teacher thinking I had completed his request that we use pointer techniques for writing our hangman assignment. He gave it back and said I used array techniques and not pointer techniques. I have struggled with learning pointers and arrays, so I am a bit confused how to fix where he said I went wrong.

These are the parts of my program he marked were array techniques and not pointer techniques:

```<code>*(q + i) = '*';

if (ch[0] == *(p + i))

*(q + i) = ch[0];
</code>```

My full program code is below (can anyone help me understand how a proper pointer technique can be implemented, I clearly don't get it - THANKS in advance):

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

void Instructions();
void PlayGame();
void PrintToLog(char *word);

int main()
{

Instructions();
PlayGame();

return 0;
getchar();
}

void Instructions()
{
printf("This is a game of hangman. Attempt to guess secret word\n");
printf("by entering a letter from a to z. The game is over once you\n");
printf("have entered 8 incorrect guesses.\n\n");
}

void PlayGame()
{
char word[] = { "hello" };
char guessed[20];
int i, incorrect_count, found;
char ch[2];
char *p, *q;

p = &word;
q = &guessed;
strcpy(guessed, word);

PrintToLog(word);

for (i = 0; i < strlen(guessed); i++)
{
    *(q + i) = '*';
}
incorrect_count = 0;

while (incorrect_count < 8 && strcmp(guessed, word) != 0)
{
    for (i = 0; i < strlen(guessed); i++)
        printf("%c ", guessed[i]);
        printf("\n");
        printf("Enter your guess:");
        gets(ch);
        found = 0;
    for (i = 0; i < strlen(word); i++){
        if (ch[0] == *(p + i))
        {
            *(q + i) = ch[0];
            found = 1;
        }
    }
    if (found == 0)
        incorrect_count++;
}

if (incorrect_count < 8)
{
    printf("\nThe word is %s. You win!", word);
    getchar();
}
else
{
    printf("\nThe correct word is %s. You lose!", word);
    getchar();
}

return 0;
}

void PrintToLog(char *word)
{
FILE *pOutput;

pOutput = fopen("MyLogFile.txt", "w+");
if (!pOutput) return;
fprintf(pOutput, "Start of game\n");
fprintf(pOutput, "This is the word player is trying to guess: %s\n", word);

fclose(pOutput);
}
</code>```

答:
First of all, p = &word; and q = &guessed; are incorrect; remove the & in both cases. word and guessed are arrays containing values of type char, which "decay" to pointers to their first items in most cases.

As an example of array decay, consider guessed:

```<code>Expression     Type
===========    ========
 guessed       char[20]
 guessed[0]    char
&guessed[0]    char *
</code>```

guessed has type char[20], or "array of 20 char values".

guessed[0] has type char and is the same as *(guessed + 0), i.e. 0 chars from the beginning of the array (which is the first item in the array).

&guessed[0] has type char * and is the same as &*(guessed + 0). Since & and * are inverse operations, they cancel each other out, resulting in &guessed[0] being the same as guessed + 0—or just guessed. The only difference between guessed and &guessed[0] is the type because the [0] indexing operation happens before the &, causing the types to differ. Array decay effectively makes guessed the same as &guessed[0] in the context of your assignment to q, so you can write either one.

The exceptions where an array variable guessed will not behave the same as &guessed[0] are:

sizeof(guessed): gets the size of the entire array

&guessed: gets a pointer to the array, with type char (*)[20]—pointer to array of 20 char values

As for your teacher's instructions, you probably need to modify the p and q pointers themselves rather than use *(x + i), which is the same as x[i].

For example:

```<code>q = guessed;
/* lines skipped */
for (i = 0; i < strlen(guessed); i++)
{
    *(q + i) = '*';
}
</code>```

becomes:

```<code>/* lines skipped */
for (q = guessed; *q != 0; q++)
{
    *q = '*';
}
</code>```

Similarly:

```<code>for (i = 0; i < strlen(word); i++){
    if (ch[0] == *(p + i))
    {
        *(q + i) = ch[0];
        found = 1;
    }
}
</code>```

can be rewritten as:

```<code>for (p = word, q = guessed; *p != 0; p++, q++)
{
    if (ch[0] == *p)
    {
        *q = ch[0];
        found = 1;
    }
}
</code>```

Body:
So I turned in this code for my assignment to my teacher thinking I had completed his request that we use pointer techniques for writing our hangman assignment. He gave it back and said I used array techniques and not pointer techniques. I have struggled with learning pointers and arrays, so I am a bit confused how to fix where he said I went wrong.

These are the parts of my program he marked were array techniques and not pointer techniques:

*(q + i) = '*';

if (ch[0] == *(p + i))

*(q + i) = ch[0];

My full program code is below (can anyone help me understand how a proper pointer technique can be implemented, I clearly don't get it - THANKS in advance):

#include<stdio.h>
#include<string.h>

void Instructions();
void PlayGame();
void PrintToLog(char *word);

int main()
{

Instructions();
PlayGame();

return 0;
getchar();
}

void Instructions()
{
printf("This is a game of hangman. Attempt to guess secret word\n");
printf("by entering a letter from a to z. The game is over once you\n");
printf("have entered 8 incorrect guesses.\n\n");
}

void PlayGame()
{
char word[] = { "hello" };
char guessed[20];
int i, incorrect_count, found;
char ch[2];
char *p, *q;

p = &word;
q = &guessed;
strcpy(guessed, word);

PrintToLog(word);

for (i = 0; i < strlen(guessed); i++)
{
    *(q + i) = '*';
}
incorrect_count = 0;

while (incorrect_count < 8 && strcmp(guessed, word) != 0)
{
    for (i = 0; i < strlen(guessed); i++)
        printf("%c ", guessed[i]);
        printf("\n");
        printf("Enter your guess:");
        gets(ch);
        found = 0;
    for (i = 0; i < strlen(word); i++){
        if (ch[0] == *(p + i))
        {
            *(q + i) = ch[0];
            found = 1;
        }
    }
    if (found == 0)
        incorrect_count++;
}

if (incorrect_count < 8)
{
    printf("\nThe word is %s. You win!", word);
    getchar();
}
else
{
    printf("\nThe correct word is %s. You lose!", word);
    getchar();
}

return 0;
}

void PrintToLog(char *word)
{
FILE *pOutput;

pOutput = fopen("MyLogFile.txt", "w+");
if (!pOutput) return;
fprintf(pOutput, "Start of game\n");
fprintf(pOutput, "This is the word player is trying to guess: %s\n", word);

fclose(pOutput);
}

Body:
First of all, p = &word; and q = &guessed; are incorrect; remove the & in both cases. word and guessed are arrays containing values of type char, which "decay" to pointers to their first items in most cases.

As an example of array decay, consider guessed:

Expression     Type
===========    ========
 guessed       char[20]
 guessed[0]    char
&guessed[0]    char *

guessed has type char[20], or "array of 20 char values".

guessed[0] has type char and is the same as *(guessed + 0), i.e. 0 chars from the beginning of the array (which is the first item in the array).

&guessed[0] has type char * and is the same as &*(guessed + 0). Since & and * are inverse operations, they cancel each other out, resulting in &guessed[0] being the same as guessed + 0—or just guessed. The only difference between guessed and &guessed[0] is the type because the [0] indexing operation happens before the &, causing the types to differ. Array decay effectively makes guessed the same as &guessed[0] in the context of your assignment to q, so you can write either one.

The exceptions where an array variable guessed will not behave the same as &guessed[0] are:

sizeof(guessed): gets the size of the entire array

&guessed: gets a pointer to the array, with type char (*)[20]—pointer to array of 20 char values

As for your teacher's instructions, you probably need to modify the p and q pointers themselves rather than use *(x + i), which is the same as x[i].

For example:

q = guessed;
/* lines skipped */
for (i = 0; i < strlen(guessed); i++)
{
    *(q + i) = '*';
}

becomes:

/* lines skipped */
for (q = guessed; *q != 0; q++)
{
    *q = '*';
}

Similarly:

for (i = 0; i < strlen(word); i++){
    if (ch[0] == *(p + i))
    {
        *(q + i) = ch[0];
        found = 1;
    }
}

can be rewritten as:

for (p = word, q = guessed; *p != 0; p++, q++)
{
    if (ch[0] == *p)
    {
        *q = ch[0];
        found = 1;
    }
}


答:
Use array.prototype.filter:

var array1 = [
  {id: 1, name: 'Bob', age: 29},
  {id: 2, name: 'Anne', age: 18},
  {id: 3, name: 'Dave', age: 29},
  {id: 4, name: 'Barry', age: 50},
  {id: 5, name: 'Jill', age: 35},
];

var array2 = [29, 50];

var array1 = array1.filter(e => !array2.includes(e.age));

console.log(array1);```

Title: Remove object from array1 where object.prop is in array2


问:
Combine multiple text rows with identical column
I need to combine rows with 1 column being the same and the rest is of type nvarchar.

TempTable

```<code>Id | Key          | Description1 | Description2
 1 | 60287F58-4631| Lorem Ipsum  | dolor sit amet
 2 | 60287F58-4631| consectetur  | adipiscing elit
 3 | 74553234-7543| Test test    | test test
</code>```

I need to get this result:

```<code>Key          | DescriptionCombined
60287F58-4631| Lorem Ipsum, dolor sit amet, consectetur, adipiscing elit
74553234-7543| Test test, test test
</code>```

I know that group by will not work because Description1 and Description2 are different between common rows. I started experimenting with for xml path(''), but this combines every row. I guess I need to first extract groups with the same key and then apply for xml path(''), but I cannot get this to work.

```<code>select ',' + t1.Description1, t1.Description2 from TempTable t1
for xml path('')
</code>```

答:
I think you can use subquery with FOR XML PATH('')

```<code>SELECT
    [Key],
    STUFF(
        (
            SELECT ', '+Description1+', '+Description2
            FROM TempTable t2
            WHERE t2.[Key]=t1.[Key]
            ORDER BY t2.Id
            FOR XML PATH('')
        ),1,2,'') DescriptionCombined
FROM (SELECT DISTINCT [Key] FROM TempTable) t1
</code>```

Body:
I need to combine rows with 1 column being the same and the rest is of type nvarchar.

TempTable

Id | Key          | Description1 | Description2
 1 | 60287F58-4631| Lorem Ipsum  | dolor sit amet
 2 | 60287F58-4631| consectetur  | adipiscing elit
 3 | 74553234-7543| Test test    | test test

I need to get this result:

Key          | DescriptionCombined
60287F58-4631| Lorem Ipsum, dolor sit amet, consectetur, adipiscing elit
74553234-7543| Test test, test test

I know that group by will not work because Description1 and Description2 are different between common rows. I started experimenting with for xml path(''), but this combines every row. I guess I need to first extract groups with the same key and then apply for xml path(''), but I cannot get this to work.

select ',' + t1.Description1, t1.Description2 from TempTable t1
for xml path('')

Body:
I think you can use subquery with FOR XML PATH('')

SELECT
    [Key],
    STUFF(
        (
            SELECT ', '+Description1+', '+Description2
            FROM TempTable t2
            WHERE t2.[Key]=t1.[Key]
            ORDER BY t2.Id
            FOR XML PATH('')
        ),1,2,'') DescriptionCombined
FROM (SELECT DISTINCT [Key] FROM TempTable) t1


问:
How to convert a DBNULL to double?
im getting a value from the database. it came out an error saying "Conversion from DBNULL to Double is not Valid." anyone, pls help me?

Public Function Total() As Double
        Dim Total As Double

```<code>    Dim strConn As String
    strConn = ConfigurationManager.ConnectionStrings("***").ToString
    Dim conn As New SqlConnection(strConn)

    Dim strSql As String
    strSql = "SELECT SUM (p.Price * c.Quantity) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID "

    Dim cmd As New SqlCommand(strSql, conn)

    cmd.Parameters.AddWithValue("@CartID", CartID)

    Dim da As New SqlDataAdapter(cmd)

    Dim ds As New DataSet

    conn.Open()

    da.Fill(ds, "CartItem")

    conn.Close()

    If (ds.Tables("CartItem").Rows.Count) <> 0 Then
        **Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
    Else
        Total = 0.0
    End If
    Return Total
End Function
</code>```

答:
You have to check if Nullable(of Double).HasValue.
total = 0.0

```<code>If (ds.Tables("CartItem").Rows.Count) <> 0 Then
     Dim sciValue As Nullable(Of Double) = DirectCast(ds.Tables("ShopCartItem").Rows(0)("Total"), Nullable(Of Double))
     If sciValue.HasValue Then
         Total = sciValue.Value
     End If
End If
</code>```

Title: How to convert a DBNULL to double?

Body:
im getting a value from the database. it came out an error saying "Conversion from DBNULL to Double is not Valid." anyone, pls help me?

Public Function Total() As Double
        Dim Total As Double

    Dim strConn As String
    strConn = ConfigurationManager.ConnectionStrings("***").ToString
    Dim conn As New SqlConnection(strConn)

    Dim strSql As String
    strSql = "SELECT SUM (p.Price * c.Quantity) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID "

    Dim cmd As New SqlCommand(strSql, conn)

    cmd.Parameters.AddWithValue("@CartID", CartID)

    Dim da As New SqlDataAdapter(cmd)

    Dim ds As New DataSet

    conn.Open()

    da.Fill(ds, "CartItem")

    conn.Close()

    If (ds.Tables("CartItem").Rows.Count) <> 0 Then
        **Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
    Else
        Total = 0.0
    End If
    Return Total
End Function

Body:
You have to check if Nullable(of Double).HasValue.
total = 0.0

If (ds.Tables("CartItem").Rows.Count) <> 0 Then
     Dim sciValue As Nullable(Of Double) = DirectCast(ds.Tables("ShopCartItem").Rows(0)("Total"), Nullable(Of Double))
     If sciValue.HasValue Then
         Total = sciValue.Value
     End If
End If


问:
Many-to-many relationship with 'through' model returning error on migration
I'm trying to implement a system which allows for two Profile model objects to be a part of a Pair model object.

Here is the Profile, followed by a Pair model:

```<code>class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                null=True, blank=True)
    pair = models.ManyToManyField('self', through='Pair',
                                   symmetrical=False,
                                   related_name='pair_to+')

class Pair(models.Model):
    requester = models.ForeignKey(Profile, related_name='pairing_requester')
    accepter = models.ForeignKey(Profile, related_name='pairing_accepter')
    requester_learns = models.CharField(max_length=60, null=True)
    requester_teaches = models.CharField(max_length=60, null=True)
</code>```

The relationship between profiles should be symmetrical, such that (profile1, profile2) are a unique object and I should not expect a (profile2, profile1) to be created.

So, per this article, I am trying to create the relationship.

Upon makemigrations, I am receiving the error:

```<code>ERRORS:
<function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x1044b47b8>: (models.E022) <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x1044b47b8> contains a lazy reference to user_profile.pair, but app 'user_profile' doesn't provide model 'pair'.
user_profile.Profile.pair: (fields.E331) Field specifies a many-to-many relation through model 'Pair', which has not been installed.
</code>```

What am I doing wrong?

答:
```<code>class Pair(models.Model):
    requester = models.ForeignKey(Profile, related_name='pairing_requester')
    accepter = models.ForeignKey(Profile, related_name='pairing_accepter')
    requester_learns = models.CharField(max_length=60, null=True)
    requester_teaches = models.CharField(max_length=60, null=True)

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                null=True, blank=True)
    pair = models.ManyToManyField('self', through='Pair',
                                   symmetrical=False,
                                   related_name='pair_to+')
</code>```

the thing that you are doing wrong is you need to mention the model before calling a relation to another model, django will create PAIR model first then will install model to the other model. so use this and before making migration drop the old migration files

Body:
I'm trying to implement a system which allows for two Profile model objects to be a part of a Pair model object.

Here is the Profile, followed by a Pair model:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                null=True, blank=True)
    pair = models.ManyToManyField('self', through='Pair',
                                   symmetrical=False,
                                   related_name='pair_to+')

class Pair(models.Model):
    requester = models.ForeignKey(Profile, related_name='pairing_requester')
    accepter = models.ForeignKey(Profile, related_name='pairing_accepter')
    requester_learns = models.CharField(max_length=60, null=True)
    requester_teaches = models.CharField(max_length=60, null=True)

The relationship between profiles should be symmetrical, such that (profile1, profile2) are a unique object and I should not expect a (profile2, profile1) to be created.

So, per this article, I am trying to create the relationship.

Upon makemigrations, I am receiving the error:

ERRORS:
<function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x1044b47b8>: (models.E022) <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x1044b47b8> contains a lazy reference to user_profile.pair, but app 'user_profile' doesn't provide model 'pair'.
user_profile.Profile.pair: (fields.E331) Field specifies a many-to-many relation through model 'Pair', which has not been installed.

What am I doing wrong?

Body:
class Pair(models.Model):
    requester = models.ForeignKey(Profile, related_name='pairing_requester')
    accepter = models.ForeignKey(Profile, related_name='pairing_accepter')
    requester_learns = models.CharField(max_length=60, null=True)
    requester_teaches = models.CharField(max_length=60, null=True)

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                null=True, blank=True)
    pair = models.ManyToManyField('self', through='Pair',
                                   symmetrical=False,
                                   related_name='pair_to+')

the thing that you are doing wrong is you need to mention the model before calling a relation to another model, django will create PAIR model first then will install model to the other model. so use this and before making migration drop the old migration files


问:
How to get returned value without await opeartor
I need to get the returned value without await operator(in below sample I need to get the "hello world" in var y without await operator). Because one method is referred to a lot of places.But my requirement is that method is executed at asynchronously for particular operations. None other time it is enough to be executed as synchronously.

If I put await in all referred places that method needs to change as async and also referred methods need to change as async and await.
Is there any possibility to get the returned value?

Please find below sample code snippet:

```<code>class Program
{
    static void Main(string[] args)
    {
        var x = getString();
    }

    public static async Task<string> getString()
    {
        var y = await GetString2();
        return y;
    }

    public static async Task<string> GetString2()
    {
        return "hello world";
    }

}
</code>```

Here is there any possibility to get "hello world" string in var y without await operator?

答:
I wouldn't use Result because If error is thrown, you'll get AggregateException. It's better to do this:

var str = GetString2().GetAwaiter().GetResult()

Body:
I need to get the returned value without await operator(in below sample I need to get the "hello world" in var y without await operator). Because one method is referred to a lot of places.But my requirement is that method is executed at asynchronously for particular operations. None other time it is enough to be executed as synchronously.

If I put await in all referred places that method needs to change as async and also referred methods need to change as async and await.
Is there any possibility to get the returned value?

Please find below sample code snippet:

class Program
{
    static void Main(string[] args)
    {
        var x = getString();
    }

    public static async Task<string> getString()
    {
        var y = await GetString2();
        return y;
    }

    public static async Task<string> GetString2()
    {
        return "hello world";
    }

}

Here is there any possibility to get "hello world" string in var y without await operator?


问:
VBA code executes with message box, but not without
I have a Sub in VBA that I need to be able to run multiple times. When I execute this piece of code to find the last row of the sheet:

```<code>Dim lastRow As Long
With ActiveSheet
lastRow = xlWs.Cells(.Rows.count, "A").End(xlUp).Row
End With
</code>```

I get

object variable or with block variable not set

when I execute it a second time, but if I add a message box before the variable set:

```<code>Dim lastRow As Long
With ActiveSheet
MsgBox xlWs.Cells(.Rows.count, "A").End(xlUp).Row
lastRow = xlWs.Cells(.Rows.count, "A").End(xlUp).Row
End With
</code>```

It works no matter how many times I run it. Has anyone run into this issue before? What is wrong with the first set of code, that is corrected with the second set?

答:
I have not tested this, but I've had this problem before.

I think the issue is that you are not qualifying .Rows.count.  Try changing it to xlWs.Rows.count.  Without it you are getting the row count of the active worksheet.

The dot operator without a preceding object points to the object defined in the With statement, even when it's inside the cells() statement, which is qualified.)

```<code>' Try This
Dim lastRow As Long
With ActiveSheet
    lastRow = xlWs.Cells(xlWs.Rows.count, "A").End(xlUp).Row
End With
</code>```

I'm not sure why you are using "With Active Sheet".  It looks like you are trying to get the last row in worksheet xlWs, which I assume is a worksheet object.

So, the code could be simplified to this:

```<code>' Better yet, try this
Dim lastRow As Long
lastRow = xlWs.Cells(xlWs.Rows.count, "A").End(xlUp).Row
</code>```

The reason the message box fixed it is because the active worksheet was changed to xlWs by doing .End(xlUp)

```<code>' This code changes the active worksheet to worksheet xlWs
' by doing .End(xlUp)
MsgBox xlWs.Cells(.Rows.count, "A").End(xlUp).Row
</code>```

Body:
I have a Sub in VBA that I need to be able to run multiple times. When I execute this piece of code to find the last row of the sheet:

Dim lastRow As Long
With ActiveSheet
lastRow = xlWs.Cells(.Rows.count, "A").End(xlUp).Row
End With

I get

object variable or with block variable not set

when I execute it a second time, but if I add a message box before the variable set:

Dim lastRow As Long
With ActiveSheet
MsgBox xlWs.Cells(.Rows.count, "A").End(xlUp).Row
lastRow = xlWs.Cells(.Rows.count, "A").End(xlUp).Row
End With

It works no matter how many times I run it. Has anyone run into this issue before? What is wrong with the first set of code, that is corrected with the second set?

Body:
I have not tested this, but I've had this problem before.

I think the issue is that you are not qualifying .Rows.count.  Try changing it to xlWs.Rows.count.  Without it you are getting the row count of the active worksheet.

The dot operator without a preceding object points to the object defined in the With statement, even when it's inside the cells() statement, which is qualified.)

' Try This
Dim lastRow As Long
With ActiveSheet
    lastRow = xlWs.Cells(xlWs.Rows.count, "A").End(xlUp).Row
End With

I'm not sure why you are using "With Active Sheet".  It looks like you are trying to get the last row in worksheet xlWs, which I assume is a worksheet object.

So, the code could be simplified to this:

' Better yet, try this
Dim lastRow As Long
lastRow = xlWs.Cells(xlWs.Rows.count, "A").End(xlUp).Row

The reason the message box fixed it is because the active worksheet was changed to xlWs by doing .End(xlUp)

' This code changes the active worksheet to worksheet xlWs
' by doing .End(xlUp)
MsgBox xlWs.Cells(.Rows.count, "A").End(xlUp).Row


问:
How does UISlider call setValue() method before self becomes available?
I'm subclassing UIControl to make a custom slider as an exercise in learning UIKit. The setValue(value:) method takes a float/double argument and animates the slider to that value. However, if the slider is not instantiated with an explicit frame, but instead sized using constraints, the setValue() method cannot be called without crashing as it requires the intrinsic width of the slider to determine where to animate the slider's thumb.

What would the proper strategy be to make sure an optional property (in this case, the width of self) becomes available before a method that has already been called is fully executed?

```<code>func addSlider() {

    slider.minimumValue = 0
    slider.maximumValue = 42
    slider.setValue(39)
    slider.addTarget(self, action: #selector(sliderAction(_:)), for: .valueChanged)
    slider.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(slider)
    slider.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    slider.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    slider.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -64).isActive = true

}
</code>```

The problem is that slider.setValue(39) requires the slider's width to make the calculation.

```<code>override func draw(_ rect: CGRect) {

    superWidth = rect.width
    drawTrack()
    drawThumb()

}

...

func setValue(_ value: Float) {

    let thumbX = CGFloat(value / maximumValue!) * (superWidth - thumbDimension)

    UIView.animate(withDuration: 1, animations: { [weak self] in
        self?.thumbLayer.frame.origin.x = thumbX
    })

}
</code>```

答:
My favorite way is

```<code>guard let widthValue = width else { return }
// use widthValue
</code>```

Or

```<code>if let widthValue = width {
    // use widthValue
}
</code>```

Both are good and have merit. The first gives you a little more control with statement. And it’s more what you’re looking for. If width doesn’t exist, return. If we unwrap widthValue then use it.

Body:
I'm subclassing UIControl to make a custom slider as an exercise in learning UIKit. The setValue(value:) method takes a float/double argument and animates the slider to that value. However, if the slider is not instantiated with an explicit frame, but instead sized using constraints, the setValue() method cannot be called without crashing as it requires the intrinsic width of the slider to determine where to animate the slider's thumb.

What would the proper strategy be to make sure an optional property (in this case, the width of self) becomes available before a method that has already been called is fully executed?

func addSlider() {

    slider.minimumValue = 0
    slider.maximumValue = 42
    slider.setValue(39)
    slider.addTarget(self, action: #selector(sliderAction(_:)), for: .valueChanged)
    slider.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(slider)
    slider.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    slider.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    slider.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -64).isActive = true

}

The problem is that slider.setValue(39) requires the slider's width to make the calculation.

override func draw(_ rect: CGRect) {

    superWidth = rect.width
    drawTrack()
    drawThumb()

}

...

func setValue(_ value: Float) {

    let thumbX = CGFloat(value / maximumValue!) * (superWidth - thumbDimension)

    UIView.animate(withDuration: 1, animations: { [weak self] in
        self?.thumbLayer.frame.origin.x = thumbX
    })

}

Body:
My favorite way is

guard let widthValue = width else { return }
// use widthValue

Or

if let widthValue = width {
    // use widthValue
}

Both are good and have merit. The first gives you a little more control with statement. And it’s more what you’re looking for. If width doesn’t exist, return. If we unwrap widthValue then use it.


问:
ec2-describe-instance-status Client.InvalidInstanceID.NotFound but I KNOW instance exists
I have setup a few of the amazon AWS CLI tools (EC2, Auto Scaling, MOnitoring and ELB). The tools are setup correctly and work perfectly. My environment vars are all set, the relevant ones to this Q being:

```<code>export EC2_REGION=eu-west-1
export EC2_URL=https://ec2.$EC2_REGION.amazonaws.com
export AWS_ELB_URL=https://elasticloadbalancing.$EC2_REGION.amazonaws.com
</code>```

When I run ec2-describe-instance-status i-XXXXXXXX for ANY of my instances, I get:

```<code>Client.InvalidInstanceID.NotFound: The instance ID 'i-XXXXXXXX' does not exist
</code>```

I KNOW the instance ID exists, I copied it out of the AWS web console, and it is in the eu-west-1 region, and my env vars are set to this region.

For the life of me I can't figure out why it will not find my instances. Is there anything glaringly obvious that I am doing incorrectly?

UPDATE: recreating x509 cert/pk solved this... for some reason.

答:
It's very simple problem. If you are getting this error

```<code>Client.InvalidInstanceID.NotFound: The instance ID 'i-XXXXXXXX' does not exist
</code>```

Then follow the steps.

Check in which country region your instance is image here

Now enter root@Indian:~# aws configure

Enter

AWS Access Key ID [****************D7M2]:

AWS Secret Access Key [****************2h3r]:

Default region name [us-east-1]:

When asked for default region, Change the region to which the instances is residing. Eg: us-east-2. Then press Enter.
  Acutally these are the list of available Region names "RegionNames"

```<code> "Regions": [
    {
        "RegionName": "ap-south-1",
        "Endpoint": "ec2.ap-south-1.amazonaws.com"
    },
    {
        "RegionName": "eu-west-2",
        "Endpoint": "ec2.eu-west-2.amazonaws.com"
    },
    {
        "RegionName": "eu-west-1",
        "Endpoint": "ec2.eu-west-1.amazonaws.com"
    },
    {
        "RegionName": "ap-northeast-2",
        "Endpoint": "ec2.ap-northeast-2.amazonaws.com"
    },
    {
        "RegionName": "ap-northeast-1",
        "Endpoint": "ec2.ap-northeast-1.amazonaws.com"
    },
    {
        "RegionName": "sa-east-1",
        "Endpoint": "ec2.sa-east-1.amazonaws.com"
    },
    {
        "RegionName": "ca-central-1",
        "Endpoint": "ec2.ca-central-1.amazonaws.com"
    },
    {
        "RegionName": "ap-southeast-1",
        "Endpoint": "ec2.ap-southeast-1.amazonaws.com"
    },
    {
        "RegionName": "ap-southeast-2",
        "Endpoint": "ec2.ap-southeast-2.amazonaws.com"
    },
    {
        "RegionName": "eu-central-1",
        "Endpoint": "ec2.eu-central-1.amazonaws.com"
    },
    {
        "RegionName": "us-east-1",
        "Endpoint": "ec2.us-east-1.amazonaws.com"
    },
    {
        "RegionName": "us-east-2",
        "Endpoint": "ec2.us-east-2.amazonaws.com"
    },
    {
        "RegionName": "us-west-1",
        "Endpoint": "ec2.us-west-1.amazonaws.com"
    },
    {
        "RegionName": "us-west-2",
        "Endpoint": "ec2.us-west-2.amazonaws.com"
    }
]
}
</code>```

Default output format [None]:

Leave the output format blank and press Enter. Now You are Done

Now in the console just type

```<code>root@Indian-3543:~# aws ec2 describe-instance --instance-id i-06343434322t
</code>```

MAKE HAPPY BE HAPPY

Body:
I have setup a few of the amazon AWS CLI tools (EC2, Auto Scaling, MOnitoring and ELB). The tools are setup correctly and work perfectly. My environment vars are all set, the relevant ones to this Q being:

export EC2_REGION=eu-west-1
export EC2_URL=https://ec2.$EC2_REGION.amazonaws.com
export AWS_ELB_URL=https://elasticloadbalancing.$EC2_REGION.amazonaws.com

When I run ec2-describe-instance-status i-XXXXXXXX for ANY of my instances, I get:

Client.InvalidInstanceID.NotFound: The instance ID 'i-XXXXXXXX' does not exist

I KNOW the instance ID exists, I copied it out of the AWS web console, and it is in the eu-west-1 region, and my env vars are set to this region.

For the life of me I can't figure out why it will not find my instances. Is there anything glaringly obvious that I am doing incorrectly?

UPDATE: recreating x509 cert/pk solved this... for some reason.

Body:
It's very simple problem. If you are getting this error

Client.InvalidInstanceID.NotFound: The instance ID 'i-XXXXXXXX' does not exist

Then follow the steps.

Check in which country region your instance is image here

Now enter root@Indian:~# aws configure

Enter

AWS Access Key ID [****************D7M2]:

AWS Secret Access Key [****************2h3r]:

Default region name [us-east-1]:

When asked for default region, Change the region to which the instances is residing. Eg: us-east-2. Then press Enter.
  Acutally these are the list of available Region names "RegionNames"

 "Regions": [
    {
        "RegionName": "ap-south-1",
        "Endpoint": "ec2.ap-south-1.amazonaws.com"
    },
    {
        "RegionName": "eu-west-2",
        "Endpoint": "ec2.eu-west-2.amazonaws.com"
    },
    {
        "RegionName": "eu-west-1",
        "Endpoint": "ec2.eu-west-1.amazonaws.com"
    },
    {
        "RegionName": "ap-northeast-2",
        "Endpoint": "ec2.ap-northeast-2.amazonaws.com"
    },
    {
        "RegionName": "ap-northeast-1",
        "Endpoint": "ec2.ap-northeast-1.amazonaws.com"
    },
    {
        "RegionName": "sa-east-1",
        "Endpoint": "ec2.sa-east-1.amazonaws.com"
    },
    {
        "RegionName": "ca-central-1",
        "Endpoint": "ec2.ca-central-1.amazonaws.com"
    },
    {
        "RegionName": "ap-southeast-1",
        "Endpoint": "ec2.ap-southeast-1.amazonaws.com"
    },
    {
        "RegionName": "ap-southeast-2",
        "Endpoint": "ec2.ap-southeast-2.amazonaws.com"
    },
    {
        "RegionName": "eu-central-1",
        "Endpoint": "ec2.eu-central-1.amazonaws.com"
    },
    {
        "RegionName": "us-east-1",
        "Endpoint": "ec2.us-east-1.amazonaws.com"
    },
    {
        "RegionName": "us-east-2",
        "Endpoint": "ec2.us-east-2.amazonaws.com"
    },
    {
        "RegionName": "us-west-1",
        "Endpoint": "ec2.us-west-1.amazonaws.com"
    },
    {
        "RegionName": "us-west-2",
        "Endpoint": "ec2.us-west-2.amazonaws.com"
    }
]
}

Default output format [None]:

Leave the output format blank and press Enter. Now You are Done

Now in the console just type

root@Indian-3543:~# aws ec2 describe-instance --instance-id i-06343434322t

MAKE HAPPY BE HAPPY


问:
Getting KeyError: '[ 1.4 nan nan 1.83] not in index'
I'm wanting to add values like my desired output below.

I am using:

```<code>#O1 Mangoes
aa = df2.AD=np.where(df3.AL.isin(df1.EW),df2.AD,np.nan)

df3['O1'] = df1[aa]

#O2 Curries
zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
print(zz)
df3['O2'] = df1[zz]
</code>```

I keep getting:

```<code>KeyError: '[ 1.4    nan   nan  1.83] not in index'
</code>```

Everything is correct aside from I want to transfer this to column O1 and O2 as well as drop NaN

I have tried to use: df = df3[pd.notnull(df3['TN'])] and write to this to excel but my output looks like:

df1

```<code>                                        EW    WE           DA
0  Persebaya Surabaya v PS Mojokerto Putra  1.40  https://www
1                                JP Voltes  3.40  https://www
2                                  pp v pp  3.10  https://www
3                                    Gagra  1.83  https://www
</code>```

df2

```<code>            AA                  AB                  AC     AD            AE
0  Today 18:00  Persebaya Surabaya  PS Mojokerto Putra   1.95  https://www.
1  Today 18:00    Davao Aguilas FC           JP Voltes   1.95  https://www.
2  Today 18:30     Adelaide United              Sydney   1.66  https://www.
3  Today 20:00                  pp                  pp  16.00  https://www.
</code>```

Desired (I get this already, save for changing to column O)

```<code>           DAT                                        G  \
0  Today 18:00  Persebaya Surabaya v PS Mojokerto Putra
1  Today 18:00             Davao Aguilas FC v JP Voltes
2  Today 18:30                 Adelaide United v Sydney
3  Today 20:00                                  pp v pp

                                        TN   O1            L1  \
0  Persebaya Surabaya v PS Mojokerto Putra  1.4  https://www.
1                                      NaN  NaN  https://www.
2                                      NaN  NaN  https://www.
3                                  pp v pp  3.10  https://www.

                                       TN2   O2           L2    D   AJ  \
0  Persebaya Surabaya v PS Mojokerto Putra  1.95  https://www  NaN  NaN
1                                      NaN  NaN  https://www  NaN  NaN
2                                      NaN  NaN  https://www  NaN  NaN
3                                  pp v pp  16  https://www  NaN  NaN

                                        AK
0  Persebaya Surabaya v PS Mojokerto Putra
1                                      NaN
2                                      NaN
3                                  pp v pp
</code>```

Full code

Code of interest:

```<code>##O  <-- Get value beside T

    cs = df2[df2.AD.isin(df1.EW)]
    df3 = df3[['AJ','AK']]
    print (cs)
</code>```

答:
You keyerror error means there are not columns with this names.

Also there is necessary same length of all dataframes and same index value, if want assign column from df3 to df2 or df1.

```<code>df2.AD = np.where(df3.AL.isin(df1.EW),df2.AD,np.nan)
#if want assign one column to another
df3['O1'] = df2.AD
</code>```

Body:
I'm wanting to add values like my desired output below.

I am using:

#O1 Mangoes
aa = df2.AD=np.where(df3.AL.isin(df1.EW),df2.AD,np.nan)

df3['O1'] = df1[aa]

#O2 Curries
zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
print(zz)
df3['O2'] = df1[zz]

I keep getting:

KeyError: '[ 1.4    nan   nan  1.83] not in index'

Everything is correct aside from I want to transfer this to column O1 and O2 as well as drop NaN

I have tried to use: df = df3[pd.notnull(df3['TN'])] and write to this to excel but my output looks like:

df1

                                        EW    WE           DA
0  Persebaya Surabaya v PS Mojokerto Putra  1.40  https://www
1                                JP Voltes  3.40  https://www
2                                  pp v pp  3.10  https://www
3                                    Gagra  1.83  https://www

df2

            AA                  AB                  AC     AD            AE
0  Today 18:00  Persebaya Surabaya  PS Mojokerto Putra   1.95  https://www.
1  Today 18:00    Davao Aguilas FC           JP Voltes   1.95  https://www.
2  Today 18:30     Adelaide United              Sydney   1.66  https://www.
3  Today 20:00                  pp                  pp  16.00  https://www.

Desired (I get this already, save for changing to column O)

           DAT                                        G  \
0  Today 18:00  Persebaya Surabaya v PS Mojokerto Putra
1  Today 18:00             Davao Aguilas FC v JP Voltes
2  Today 18:30                 Adelaide United v Sydney
3  Today 20:00                                  pp v pp

                                        TN   O1            L1  \
0  Persebaya Surabaya v PS Mojokerto Putra  1.4  https://www.
1                                      NaN  NaN  https://www.
2                                      NaN  NaN  https://www.
3                                  pp v pp  3.10  https://www.

                                       TN2   O2           L2    D   AJ  \
0  Persebaya Surabaya v PS Mojokerto Putra  1.95  https://www  NaN  NaN
1                                      NaN  NaN  https://www  NaN  NaN
2                                      NaN  NaN  https://www  NaN  NaN
3                                  pp v pp  16  https://www  NaN  NaN

                                        AK
0  Persebaya Surabaya v PS Mojokerto Putra
1                                      NaN
2                                      NaN
3                                  pp v pp

Full code

Code of interest:

##O  <-- Get value beside T

    cs = df2[df2.AD.isin(df1.EW)]
    df3 = df3[['AJ','AK']]
    print (cs)

Body:
You keyerror error means there are not columns with this names.

Also there is necessary same length of all dataframes and same index value, if want assign column from df3 to df2 or df1.

df2.AD = np.where(df3.AL.isin(df1.EW),df2.AD,np.nan)
#if want assign one column to another
df3['O1'] = df2.AD


问:
Is there a library for iPhone to work with HMAC-SHA-1 encoding
For all operation with Amazon services(S3, EC2, SimpleDB) You need to sign all resquest with HMAC-SHA-1 Signature(http://en.wikipedia.org/wiki/HMAC , http://docs.amazonwebservices.com/AWSFWS/latest/DeveloperGuide/index.html?SummaryOfAuthentication.html).

I'm working under asp.net backend and there is no problems. Problem is in the iPhone application. iPhone developer says that there is no way to use HMAC-SHA-1 encoding, and he have no rigths to implement his own algorithm. As programmer I cannot understand why there can be a problem.

So I want too know is iPhone developer right?

I've never coded for iPhone, so I don't even where to search such an information.

答:
I don't know if this is the case anymore, but there used to be restrictions on encryption algorithms and your right to distribute them to certain countries were restricted.

If this is still the case it could be that Apple don't want/can't restrict certain applications from being downloaded in these countries.

OwnerDisplayName: AlfeG

OwnerDisplayName: Fredrik Jansson


问:
Algorithm to transform one word to another through valid words
I came across this variation of edit-distance problem:

Design an algorithm which transforms a source word to a target word. for example: from head to tail, in each step, you just can replace one character, and the word must be valid. You'll be given a dictionary.

It clearly is a variation of the edit distance problem, but in edit distance I do not care about if the word is valid or not. So how do I add this requirement to edit distance.

答:
I don't think we need graph or some other complicated data structure. My idea is to load the dictionary as a HashSet and use contains() method to find out if the word exists in the dictionary or not.

Please, check this pseudocode to see my idea:

```<code>Two words are given: START and STOP.
//List is our "way" from words START to STOP, so, we add the original word to it first.
    list.add(START);
//Finish to change the word when START equals STOP.
    while(!START.equals(STOP))
//Change each letter at START to the letter to STOP one by one and check if such word exists.
    for (int i = 0, i<STOP.length, i++){
        char temp = START[i];
        START[i] = STOP[i];
//If the word exists add a new word to the list of results.
//And change another letter in the new word with the next pass of the loop.
        if dictionary.contains(START)
           list.add(START)
//If the word doesn't exist, leave it like it was and try to change another letter with the next pass of the loop.
        else START[i] = temp;}
    return list;
</code>```

As I understand my code should work like that:

Input: DAMP, LIKE

Output: DAMP, LAMP, LIMP, LIME, LIKE

Input: BACK, PICK

Output: BACK, PACK, PICK

Body:
I don't think we need graph or some other complicated data structure. My idea is to load the dictionary as a HashSet and use contains() method to find out if the word exists in the dictionary or not.

Please, check this pseudocode to see my idea:

Two words are given: START and STOP.
//List is our "way" from words START to STOP, so, we add the original word to it first.
    list.add(START);
//Finish to change the word when START equals STOP.
    while(!START.equals(STOP))
//Change each letter at START to the letter to STOP one by one and check if such word exists.
    for (int i = 0, i<STOP.length, i++){
        char temp = START[i];
        START[i] = STOP[i];
//If the word exists add a new word to the list of results.
//And change another letter in the new word with the next pass of the loop.
        if dictionary.contains(START)
           list.add(START)
//If the word doesn't exist, leave it like it was and try to change another letter with the next pass of the loop.
        else START[i] = temp;}
    return list;

As I understand my code should work like that:

Input: DAMP, LIKE

Output: DAMP, LAMP, LIMP, LIME, LIKE

Input: BACK, PICK

Output: BACK, PACK, PICK


问:
Add CSS Class to YADCF Select2 Container
I have a yadcf Select2 filter that looks like this:

```<code>{column_number : 1, filter_type: "select", select_type: "select2", style_class: "subjectFilter"}
</code>```

I used style_class to add a CSS class called subjectFilter. This class shows up in the DOM, and it is attached to the select box. However, the actual select2 dropdown doesn't obey the style (i.e. width) of the select box. Is it possible to add a class to the  tag that holds the .select-container class?

答:
If you want to manipulate the select2 container you can use the select_type_options attribute,

Here is an usage example:

{
    column_number : 2,
    select_type: 'select2',
    select_type_options: {width: '150px', minimumResultsForSearch: -1}
 }

Body:
I have a yadcf Select2 filter that looks like this:

{column_number : 1, filter_type: "select", select_type: "select2", style_class: "subjectFilter"}

I used style_class to add a CSS class called subjectFilter. This class shows up in the DOM, and it is attached to the select box. However, the actual select2 dropdown doesn't obey the style (i.e. width) of the select box. Is it possible to add a class to the  tag that holds the .select-container class?


问:
Reconciliation Automation Query
I have one database and time to time i change some part of query as per requirement.
i want to keep record of results of both before and after result of these queries in one table and want to show queries which generate difference.

For Example,
Consider following table

```<code>emp_id    country      salary
---------------------
1          usa         1000

2          uk          2500

3          uk         1200

4          usa          3500

5          usa          4000

6          uk          1100
</code>```

Now, my before query is :

Before Query:

```<code>select count(emp_id) as count,country from table where salary>2000 group by country;
</code>```

Before Result:

```<code>count     country

2      usa

1      uk
</code>```

After Query:

```<code>select count(emp_id) as count,country from table where salary<2000 group by country;
</code>```

After Query Result:

```<code>count     country

2      uk

1      usa
</code>```

My Final Result or Table I want is:

```<code>column 1  |   column 2  |    column 3   |   column 4 |

2              usa            2             uk

1              uk              1             usa
</code>```

...... but if query results are same than it shouldn't show in this table.

Thanks in advance.

答:
I believe that you can use the same approach as here.</p>

```<code>select t1.*, t2.* -- if you need specific columns without rn than you have to list them here
from
(
   select t.*, row_number() over (order by count) rn
   from
   (
     -- query #1
     select count(emp_id) as count,country from table where salary>2000 group by country;
   ) t
) t1
full join
(
   select t.*, row_number() over (order by count) rn
   from
   (
    -- query #2
    select count(emp_id) as count,country from table where salary<2000 group by country;
   ) t
) t2 on t1.rn = t2.rn
</code>```

Title: Reconciliation Automation Query

Body:
I have one database and time to time i change some part of query as per requirement.
i want to keep record of results of both before and after result of these queries in one table and want to show queries which generate difference.

For Example,
Consider following table

emp_id    country      salary
---------------------
1          usa         1000

2          uk          2500

3          uk         1200

4          usa          3500

5          usa          4000

6          uk          1100

Now, my before query is :

Before Query:

select count(emp_id) as count,country from table where salary>2000 group by country;

Before Result:

count     country

2      usa

1      uk

After Query:

select count(emp_id) as count,country from table where salary<2000 group by country;

After Query Result:

count     country

2      uk

1      usa

My Final Result or Table I want is:

column 1  |   column 2  |    column 3   |   column 4 |

2              usa            2             uk

1              uk              1             usa

...... but if query results are same than it shouldn't show in this table.

Thanks in advance.

Body:
I believe that you can use the same approach as here.

select t1.*, t2.* -- if you need specific columns without rn than you have to list them here
from
(
   select t.*, row_number() over (order by count) rn
   from
   (
     -- query #1
     select count(emp_id) as count,country from table where salary>2000 group by country;
   ) t
) t1
full join
(
   select t.*, row_number() over (order by count) rn
   from
   (
    -- query #2
    select count(emp_id) as count,country from table where salary<2000 group by country;
   ) t
) t2 on t1.rn = t2.rn


问:
Java generic array from null generic type
Consider the Array.newInstance static method as a way of creating a generic type array in Java.
What I'm failing to see how to do is create a generic array from a null generic type argument:

```<code>/**
* Creates and fills a generic array with the given item
*/
public static <T> T[] create(T item, int length)
{
   T[] result = (T[]) Array.newInstance(item.getClass(), length);

   for(int i = 0; i < length; i++)
      result[i] = item;

   return result;
}
</code>```

The above works when I call e.g. create("abc", 10); I'm getting a String[] of length 10 with "abc" in all positions of the array.
But how could I make a null string argument return a String array of length 10 and null in all positions?

e.g.

```<code>String nullStr = null;
String[] array = create(nullStr, 10); // boom! NullPointerException
</code>```

Is there perhaps a  way to get the class of "item" without using one of its members (as it's null)?

I know I can just new up an array String[] array = new String[10], but that's not the point.

Thanks

答: Well, why not change the method to take a Class object instead, and just directly pass in String.class? Java can't get the class type of null because it has no class type! Any object can be null.

Body:
Consider the Array.newInstance static method as a way of creating a generic type array in Java.
What I'm failing to see how to do is create a generic array from a null generic type argument:

/**
* Creates and fills a generic array with the given item
*/
public static <T> T[] create(T item, int length)
{
   T[] result = (T[]) Array.newInstance(item.getClass(), length);

   for(int i = 0; i < length; i++)
      result[i] = item;

   return result;
}

The above works when I call e.g. create("abc", 10); I'm getting a String[] of length 10 with "abc" in all positions of the array.
But how could I make a null string argument return a String array of length 10 and null in all positions?

e.g.

String nullStr = null;
String[] array = create(nullStr, 10); // boom! NullPointerException

Is there perhaps a  way to get the class of "item" without using one of its members (as it's null)?

I know I can just new up an array String[] array = new String[10], but that's not the point.

Thanks


问:
Cannot display todos in react-redux (property map undefined)?
I am trying to learn Redux by creating my own todo app without the flairs in Redux' official todo app example. I am having trouble displaying my todos list as I am getting TypeError: Cannot read property 'map' of undefined.

The repo can be found here. It is fairly lightweight (less components than Redux' todo-app).

This is the part that I have trouble with:

```<code>/src/components/TodoList.js

import React from 'react';

const TodoList = ({todos}) => {
  return (
    <ul>
      {todos.map(todo =>
        <li key={todo.id}>{todo.text}</li>
      )}
    </ul>
  )
}

export default TodoList;
</code>```

I also use connect on my ViewTodoList.js containers. If I understand it correctly, by doing this I should populate my todos with the store states:

```<code>/containers/ViewTodoList.js

import React from 'react';
import {connect} from 'react-redux';
import TodoList from '../components/TodoList';

const mapStateToProps = (state) => {
  todos: state.todos
}

const ViewTodoList = connect(
  mapStateToProps
)(TodoList)

export default ViewTodoList;
</code>```

I am pretty sure my Redux store has the correct state. The AddTodo can be found here.

However, for some reason TodoList component inside components/TodoList.js is not receiving the todos states inside as {todos}. I think I might have made some mistake here.

How can I properly display all todos state inside TodoList?

答:
You forgot to return the value in your mapStateToProps. It should be:

```<code>const mapStateToProps = state => ({
  todos: state.todos,
});
</code>```

Body:
I am trying to learn Redux by creating my own todo app without the flairs in Redux' official todo app example. I am having trouble displaying my todos list as I am getting TypeError: Cannot read property 'map' of undefined.

The repo can be found here. It is fairly lightweight (less components than Redux' todo-app).

This is the part that I have trouble with:

/src/components/TodoList.js

import React from 'react';

const TodoList = ({todos}) => {
  return (

      {todos.map(todo =>

{todo.text}

      )}

  )
}

export default TodoList;

I also use connect on my ViewTodoList.js containers. If I understand it correctly, by doing this I should populate my todos with the store states:

/containers/ViewTodoList.js

import React from 'react';
import {connect} from 'react-redux';
import TodoList from '../components/TodoList';

const mapStateToProps = (state) => {
  todos: state.todos
}

const ViewTodoList = connect(
  mapStateToProps
)(TodoList)

export default ViewTodoList;

I am pretty sure my Redux store has the correct state. The AddTodo can be found here.

However, for some reason TodoList component inside components/TodoList.js is not receiving the todos states inside as {todos}. I think I might have made some mistake here.

How can I properly display all todos state inside TodoList?

Body:
You forgot to return the value in your mapStateToProps. It should be:

const mapStateToProps = state => ({
  todos: state.todos,
});


问:
setDate() not working right?
Today is December 5th.

My goal is to get the first and the last day of each of the previous three months in a Google Apps Script.

According to this, setDate(0) is supposed to return the last day of the previous month.

Which it is not in my case. It returns the first day of the current month:

```<code>var d = new Date();
var dd  = d.setDate(0);
Logger.log(getFormattedDate(dd));
</code>```

This logs

```<code>20171201
</code>```

Interestingly using setDate(-1) does return the last day of the previous month (which is different to what the documentation says):

```<code> var d = new Date();
 var dd  = d.setDate(-1);
 Logger.log(getFormattedDate(dd));
</code>```

logs

```<code>20171130
</code>```

Thinking that I understood the logic behind setDate(0) and setDate(-1) I wrote my new code, assuming that the documentation is just wrong. But then I got this:

```<code> var d = new Date();

 var m_1_last  = d.setDate(-1);
 var m_1_first = d.setDate(0);
 var m_2_last  = d.setDate(-1);

 Logger.log(getFormattedDate(m_1_last));
 Logger.log(getFormattedDate(m_1_first));
 Logger.log(getFormattedDate(m_2_last));
</code>```

I would expect to get this

```<code>20171130
20171101
20171031 <--
</code>```

But I am getting this

```<code>20171130
20171101
20170930 <--
</code>```

So, if the current date is the first of the month d.setDate(-1) will not return the last day of the previous month, but of the month before that one. d.setDate(-1) will only return the last day of the previous month if the current date is after the first of the month.

Do I misunderstand something, or is this a bug?

PS:

getFormattedDate() is a helper function and works like this:

```<code>function getFormattedDate(dateInMilliseconds){
  var timeZone = AdWordsApp.currentAccount().getTimeZone();
  var d = new Date(dateInMilliseconds);
  return Utilities.formatDate(d, timeZone,'yyyyMMdd');
}
</code>```

答:
How about this answer?

d.setDate(0) means the last day of the previous month.

d.setDate(1) means the first day of the current month.

So when your script is used, the modified parameters are as follows.

Modified script :

```<code>// var d = new Date();
var d = new Date(Date.now() + (new Date().getTimezoneOffset() / 60) * 60 * 60 * 1000); // Modified

var m_1_last  = d.setDate(0);
var m_1_first = d.setDate(1);
var m_2_last  = d.setDate(0);

Logger.log(getFormattedDate(m_1_last));
Logger.log(getFormattedDate(m_1_first));
Logger.log(getFormattedDate(m_2_last));
</code>```

Result :

```<code>20171130
20171101
20171031
</code>```

Note :

In order to test this, I used var timeZone = Session.getScriptTimeZone(); instead of var timeZone = AdWordsApp.currentAccount().getTimeZone();.

If I misunderstand your question, I'm sorry.

Edit :

How about modifying the offset of timezone, when new Date() is retrieved? Can you try to modify as follows?

From :

```<code>var d = new Date();
</code>```

To :

```<code>var d = new Date(Date.now() + (new Date().getTimezoneOffset() / 60) * 60 * 60 * 1000);
</code>```

Reference :

getTimezoneOffset()

Title: setDate() not working right?

Body:
Today is December 5th.

My goal is to get the first and the last day of each of the previous three months in a Google Apps Script.

According to this, setDate(0) is supposed to return the last day of the previous month.

Which it is not in my case. It returns the first day of the current month:

var d = new Date();
var dd  = d.setDate(0);
Logger.log(getFormattedDate(dd));

This logs

20171201

Interestingly using setDate(-1) does return the last day of the previous month (which is different to what the documentation says):

 var d = new Date();
 var dd  = d.setDate(-1);
 Logger.log(getFormattedDate(dd));

logs

20171130

Thinking that I understood the logic behind setDate(0) and setDate(-1) I wrote my new code, assuming that the documentation is just wrong. But then I got this:

 var d = new Date();

 var m_1_last  = d.setDate(-1);
 var m_1_first = d.setDate(0);
 var m_2_last  = d.setDate(-1);

 Logger.log(getFormattedDate(m_1_last));
 Logger.log(getFormattedDate(m_1_first));
 Logger.log(getFormattedDate(m_2_last));

I would expect to get this

20171130
20171101
20171031 <--

But I am getting this

20171130
20171101
20170930 <--

So, if the current date is the first of the month d.setDate(-1) will not return the last day of the previous month, but of the month before that one. d.setDate(-1) will only return the last day of the previous month if the current date is after the first of the month.

Do I misunderstand something, or is this a bug?

PS:

getFormattedDate() is a helper function and works like this:

function getFormattedDate(dateInMilliseconds){
  var timeZone = AdWordsApp.currentAccount().getTimeZone();
  var d = new Date(dateInMilliseconds);
  return Utilities.formatDate(d, timeZone,'yyyyMMdd');
}

Body:
How about this answer?

d.setDate(0) means the last day of the previous month.

d.setDate(1) means the first day of the current month.

So when your script is used, the modified parameters are as follows.

Modified script :

// var d = new Date();
var d = new Date(Date.now() + (new Date().getTimezoneOffset() / 60) * 60 * 60 * 1000); // Modified

var m_1_last  = d.setDate(0);
var m_1_first = d.setDate(1);
var m_2_last  = d.setDate(0);

Logger.log(getFormattedDate(m_1_last));
Logger.log(getFormattedDate(m_1_first));
Logger.log(getFormattedDate(m_2_last));

Result :

20171130
20171101
20171031

Note :

In order to test this, I used var timeZone = Session.getScriptTimeZone(); instead of var timeZone = AdWordsApp.currentAccount().getTimeZone();.

If I misunderstand your question, I'm sorry.

Edit :

How about modifying the offset of timezone, when new Date() is retrieved? Can you try to modify as follows?

From :

var d = new Date();

To :

var d = new Date(Date.now() + (new Date().getTimezoneOffset() / 60) * 60 * 60 * 1000);

Reference :

getTimezoneOffset()


问:
Content type check for uploading APK file in JAVA
How to check if user is actually uploading APK file in java.

By checking only the extension of file user can rename any file(Eg:TXT file) to apk and upload.

I tried to check the contentType of the particular file as shown below:

```<code>if(apkFile.getContentType().equals("application/vnd.android.package-archive"))
</code>```

But here the problem is when upload from some browser the content type comes as application/vnd.android.package-archive but for some others its application/octet-stream.

What is the proper way to check this?

答:
Apache tika parser can detect your file type if you changed the file type extension by renaming.Though parse method a bit expensive. After parsing the file, file metadata are stored in MetaData object. However you can follow the code

```<code>import org.apache.tika.metadata.Metadata;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.parser.AutoDetectParser;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class Test {

    public static void main(String[] args) {
        File file = null;
        InputStream is = null;
        String contentType = null;

        try {
            //suppose f.apk file you renamed it f.txt
            file = new File("path\\to\\your\\file\\f.txt");
            is = new FileInputStream(file);

            Metadata metadata = new Metadata();
            BodyContentHandler handler = new BodyContentHandler();
            AutoDetectParser parser = new AutoDetectParser();

            try {
                // This step takes some time.
                parser.parse(is, handler, metadata);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                is.close();
            }

            contentType = metadata.get("Content-Type");
            System.out.println("Content Type = " + contentType);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
</code>```

Required maven dependency

```<code><dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-core</artifactId>
    <version>1.16</version>
</dependency>
<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>1.16</version>
</dependency>
</code>```

Body:
How to check if user is actually uploading APK file in java.

By checking only the extension of file user can rename any file(Eg:TXT file) to apk and upload.

I tried to check the contentType of the particular file as shown below:

if(apkFile.getContentType().equals("application/vnd.android.package-archive"))

But here the problem is when upload from some browser the content type comes as application/vnd.android.package-archive but for some others its application/octet-stream.

What is the proper way to check this?

Body:
Apache tika parser can detect your file type if you changed the file type extension by renaming.Though parse method a bit expensive. After parsing the file, file metadata are stored in MetaData object. However you can follow the code

import org.apache.tika.metadata.Metadata;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.parser.AutoDetectParser;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class Test {

    public static void main(String[] args) {
        File file = null;
        InputStream is = null;
        String contentType = null;

        try {
            //suppose f.apk file you renamed it f.txt
            file = new File("path\\to\\your\\file\\f.txt");
            is = new FileInputStream(file);

            Metadata metadata = new Metadata();
            BodyContentHandler handler = new BodyContentHandler();
            AutoDetectParser parser = new AutoDetectParser();

            try {
                // This step takes some time.
                parser.parse(is, handler, metadata);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                is.close();
            }

            contentType = metadata.get("Content-Type");
            System.out.println("Content Type = " + contentType);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Required maven dependency

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-core</artifactId>
    <version>1.16</version>
</dependency>
<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>1.16</version>
</dependency>


问:
Calculations based on Region and Cluster query SQL
I've table like this:

```<code>Cluster | Region | Value | Volume
---------------------------------
 West   |   AA   |  7500 |   2
 West   |   AB   |  9000 |   1
 West   |   AC   |  2200 |   2
 West   |   AC   |  7200 |   3
</code>```

Get sum of value and volume based on cluster, become value 25900 and volume 8. Get sum of value and volume based on region, become value (7500,9000,9400) and volume (2,1,5). Then value and volume based on region divided by value and volume based on cluster. Data should be like this:

```<code>Region | Growth Value | Growth Volume
-------------------------------------
  AA   |     29,0     |      25
  AB   |     34,7     |     12,5
  AC   |     36,3     |     62,5
</code>```

SQL Fiddle: http://sqlfiddle.com/#!15/5a908/27

答:
We can try doing two separate aggregations, one at the cluster level and one at the region level.  Then join them and take the quotients you want to see.

```<code>WITH cluster AS (
    SELECT "Cluster", SUM("Value") AS c_value, SUM("Volume") AS c_volume
    FROM cals
    GROUP BY "Cluster"
),
region AS (
    SELECT "Cluster", "Region",
        SUM("Value") AS r_value, SUM("Volume") AS r_volume
    FROM cals
    GROUP BY "Cluster", "Region"
)

SELECT
    r."Region",
    r."Cluster",
    ROUND(100.0*r.r_value / c.c_value, 1) AS growth_value,
    ROUND(100.0*r.r_volume / c.c_volume, 1) AS growth_volume
FROM region r
INNER JOIN cluster c
    ON r."Cluster" = c."Cluster"
ORDER BY
    r."Region";
</code>```

Demo

Body:
I've table like this:

Cluster | Region | Value | Volume
---------------------------------
 West   |   AA   |  7500 |   2
 West   |   AB   |  9000 |   1
 West   |   AC   |  2200 |   2
 West   |   AC   |  7200 |   3

Get sum of value and volume based on cluster, become value 25900 and volume 8. Get sum of value and volume based on region, become value (7500,9000,9400) and volume (2,1,5). Then value and volume based on region divided by value and volume based on cluster. Data should be like this:

Region | Growth Value | Growth Volume
-------------------------------------
  AA   |     29,0     |      25
  AB   |     34,7     |     12,5
  AC   |     36,3     |     62,5

SQL Fiddle: http://sqlfiddle.com/#!15/5a908/27

Body:
We can try doing two separate aggregations, one at the cluster level and one at the region level.  Then join them and take the quotients you want to see.

WITH cluster AS (
    SELECT "Cluster", SUM("Value") AS c_value, SUM("Volume") AS c_volume
    FROM cals
    GROUP BY "Cluster"
),
region AS (
    SELECT "Cluster", "Region",
        SUM("Value") AS r_value, SUM("Volume") AS r_volume
    FROM cals
    GROUP BY "Cluster", "Region"
)

SELECT
    r."Region",
    r."Cluster",
    ROUND(100.0*r.r_value / c.c_value, 1) AS growth_value,
    ROUND(100.0*r.r_volume / c.c_volume, 1) AS growth_volume
FROM region r
INNER JOIN cluster c
    ON r."Cluster" = c."Cluster"
ORDER BY
    r."Region";

Demo