问:
Pandas - Find increasing trend in a row of different columns
I have a dataset of milk production in India. I am trying to get the list of 5 states(if present) in which the total Milk Production increased in last 3 years through Pandas.

```<code>State        Total10-11 Total11-12  Total13-14  Total14-15  Total15-16
Andhra Pradesh    11204      12088       13007         9656      10817
Arunachal Pradesh    28         22          43           46         50
Assam               790        797         814          829        844
Bihar              6517       6643        7197         7775       8289
Chhattisgarh       1030       1118        1208         1232       1278
Goa                  60         60          68           66         54
Gujarat            9322       4089       11112        11690      12262
Haryana            6268       6661        7442         7902       8381
Himachal Pradesh   1102       1120        1151         1173       1283
</code>```

Expected output:

```<code>State
Assam
Bihar
Chhattisgarh
Haryana
Himachal Pradesh
</code>```

I want to find the states which have an increasing trend in their milk production each year. The Milk production should not have decreased in the consequent years compared to the previous years. the expected output states have the production in increasing order and there is no dip even once in their production. I am kind of stuck with this one, I tried a few methods but they are not close to the right answer. What's the solution ? Thanks in advance.

答:
If you are just looking for a trend, then I think visualization is the answer.

You could do something like this.

```<code>import matplotlib.pyplot as plt
import pandas as pd

df = df.set_index('state')
df.T.plot(figsize=(10,15))
</code>```

Or to look at them individually:

```<code>df.T.plot(figsize=(15,20), subplots=True,layout=(3,3))
</code>```

Body:
I have a dataset of milk production in India. I am trying to get the list of 5 states(if present) in which the total Milk Production increased in last 3 years through Pandas.

State        Total10-11 Total11-12  Total13-14  Total14-15  Total15-16
Andhra Pradesh    11204      12088       13007         9656      10817
Arunachal Pradesh    28         22          43           46         50
Assam               790        797         814          829        844
Bihar              6517       6643        7197         7775       8289
Chhattisgarh       1030       1118        1208         1232       1278
Goa                  60         60          68           66         54
Gujarat            9322       4089       11112        11690      12262
Haryana            6268       6661        7442         7902       8381
Himachal Pradesh   1102       1120        1151         1173       1283

Expected output:

State
Assam
Bihar
Chhattisgarh
Haryana
Himachal Pradesh

I want to find the states which have an increasing trend in their milk production each year. The Milk production should not have decreased in the consequent years compared to the previous years. the expected output states have the production in increasing order and there is no dip even once in their production. I am kind of stuck with this one, I tried a few methods but they are not close to the right answer. What's the solution ? Thanks in advance.

Body:
If you are just looking for a trend, then I think visualization is the answer.

You could do something like this.

import matplotlib.pyplot as plt
import pandas as pd

df = df.set_index('state')
df.T.plot(figsize=(10,15))

Or to look at them individually:

df.T.plot(figsize=(15,20), subplots=True,layout=(3,3))


来源: stackexchange

问:
How to ensure callback order?
Say, I have a RoR application with multiple plugins. Each of these plugins implements an after_save callback on a model. I need to create one more plugin with two more callbacks, say, start and finish. How do I ensure the following order of callback execution?

MyPlugin.start

OtherPlugin_1.after_save_1

OtherPlugin_1.after_save_X

OtherPlugin_X.after_save_1

...

MyPlugin.finish

I.e. my callback should be called before any other after_save and immediately after all other after_save callbacks have finished execution.

答:
This should be possible by using prepend: true for MyPlugin.start, as follows:

```<code>after_save :start, prepend: true
</code>```

Assuming, that no other plugin uses :prepend.

Regarding MyPlugin.finish: the only option (as far as I know) is to make sure, that the plugin is executed last (e.g., by naming it zzz).

ContentLicense: CC BY-SA 3.0

Title: How to ensure callback order?

Body:
This should be possible by using prepend: true for MyPlugin.start, as follows:

after_save :start, prepend: true

Assuming, that no other plugin uses :prepend.

Regarding MyPlugin.finish: the only option (as far as I know) is to make sure, that the plugin is executed last (e.g., by naming it zzz).


问:
Array objects values remove unwanted string
I have the following originaldata  which I would like to remove the div tags from the each objects inside it, leaving it with the content within the tags as the final result, see modifieddata.

What would be the best approach using javascript? filter and map? or something else.

```<code>originaldata = [{
        "name": "john",
        "content": "<div class="ExternalClass06EE5E42165840F48DFA193ACAD4F87A">aa</div>"
    },
    {
        "name": "mary",
        "content": "<div class="ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A">asd</div>"
    }
]

modifieddata = [{
        "name": "john",
        "content": "aa"
    },
    {
      "name": "mary",
      "content": "asd"
    }
]
</code>```

答:
Use map and createElement

```<code>var output = originaldata.map( function(item){
  var div = document.createElement("div");
  div.innerHTML = item.content;
  return { name : item.name, content : div.textContent };
});
</code>```

var originaldata = [{
"name": "john",
"content": "
aa
"
},
{
"name": "mary",
"content": "
asd
"
}];

var output = originaldata.map( function(item){
  var div = document.createElement("div");
  div.innerHTML = item.content;
  return { name : item.name, content : div.textContent };
});

console.log( output );```

Body:
I have the following originaldata  which I would like to remove the div tags from the each objects inside it, leaving it with the content within the tags as the final result, see modifieddata.

What would be the best approach using javascript? filter and map? or something else.

originaldata = [{
        "name": "john",
        "content": "
aa
"
    },
    {
        "name": "mary",
        "content": "
asd
"
    }
]

modifieddata = [{
        "name": "john",
        "content": "aa"
    },
    {
      "name": "mary",
      "content": "asd"
    }
]

Body:
Use map and createElement

var output = originaldata.map( function(item){
  var div = document.createElement("div");
  div.innerHTML = item.content;
  return { name : item.name, content : div.textContent };
});

var originaldata = [{
"name": "john",
"content": "<div class= 'ExternalClass06EE5E42165840F48DFA193ACAD4F87A'>aa</div>"
},
{
"name": "mary",
"content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A'>asd</div>"
}];

var output = originaldata.map( function(item){
  var div = document.createElement("div");
  div.innerHTML = item.content;
  return { name : item.name, content : div.textContent };
});

console.log( output );


问:
casting a pointer to struct for qsort's compare
So I'm using qsort() in c and my compare function usually consist of creating a pointer of the correct type and assigning it the value from the arguments. is it possible to just cast the pointer from the arguments without creating a new one?
if so, what am i doing wrong?

```<code>struct date_t{
    int time;
    int dob;
};

/* the old working function
int cmpfunc (const void * one, const void * two) {
    struct date_t *itemtwo=two;
    struct date_t *itemone=one;
return itemone->time-itemtwo->time;
}
*/

int cmpfunc (const void * one, const void * two) {
    return (struct date_t*)(one)->time - (struct date_t*)two->time;
}
</code>```

i'm getting :

```<code>main.c:17:30: warning: dereferencing 'void *' pointer
  return (struct date_t*)(one)->time - (struct date_t*)two->time;
                          ^~
main.c:17:30: error: request for member 'time' in something not a structure or union
</code>```

EDIT:

i got it to compile with

```<code>int cmpfunc (struct date_t *one, struct date_t *two) {
    return one->time - two->time;
}
</code>```

but still, how would i do it with casts?

答:
The type cast operator () has lower precedence than the pointer-to-member operator ->.  So this:

```<code>(struct date_t*)(one)->time
</code>```

Is the same as this:

```<code>(struct date_t*)((one)->time)
</code>```

You need to parenthesize what is casted, then you can dereference the pointer.

```<code>int cmpfunc (const void * one, const void * two) {
    return ((const struct date_t*)(one))->time - ((const struct date_t*)two)->time;
}
</code>```

Also note that the casted pointers are const to be consistent with the original pointers.

Body:
So I'm using qsort() in c and my compare function usually consist of creating a pointer of the correct type and assigning it the value from the arguments. is it possible to just cast the pointer from the arguments without creating a new one?
if so, what am i doing wrong?

struct date_t{
    int time;
    int dob;
};

/* the old working function
int cmpfunc (const void * one, const void * two) {
    struct date_t *itemtwo=two;
    struct date_t *itemone=one;
return itemone->time-itemtwo->time;
}
*/

int cmpfunc (const void * one, const void * two) {
    return (struct date_t*)(one)->time - (struct date_t*)two->time;
}

i'm getting :

main.c:17:30: warning: dereferencing 'void *' pointer
  return (struct date_t*)(one)->time - (struct date_t*)two->time;
                          ^~
main.c:17:30: error: request for member 'time' in something not a structure or union

EDIT:

i got it to compile with

int cmpfunc (struct date_t *one, struct date_t *two) {
    return one->time - two->time;
}

but still, how would i do it with casts?

Body:
The type cast operator () has lower precedence than the pointer-to-member operator ->.  So this:

(struct date_t*)(one)->time

Is the same as this:

(struct date_t*)((one)->time)

You need to parenthesize what is casted, then you can dereference the pointer.

int cmpfunc (const void * one, const void * two) {
    return ((const struct date_t*)(one))->time - ((const struct date_t*)two)->time;
}

Also note that the casted pointers are const to be consistent with the original pointers.


问:
Auto run macro in excel when "Disable all macros with notification"
In Macro Setting,  I have chosen "Disable all macros with notification" but when i open file, macro still run. I use office 2013.Can anyone help me with this issue?</p>

答:
1.) sometimes (if you have a certain group policy applied or add-in installed) settings change if you reboot your system. Check first if "disable all macros with notification" is still selected.

2.) read about the setting to make sure it is what you intend it to be ->
 here

3.) Check if the file has a digital signature by opening the VBA editor: open workbook -> press ALT + F11 -> select Tools -> select Digital Signature.
If it does have a signature simply remove it.

Cheers


答:
I would use Array.prototype.map and regexp:

```<code>const originaldata = [{
  "name": "john",
  "content": '<div class="ExternalClass06EE5E42165840F48DFA193ACAD4F87A">aa</div>'
},
{
  "name": "mary",
  "content": '<div class="ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A">asd</div>'
}];

const regex = /(<([^>]+)>)/ig;

const modifieddata = originaldata.map(item => ({
  name: item.name,
  content: item.content.replace(regex, "")
}));

console.log(modifieddata); // [{name: "john", content: "aa"}, {name: "mary", content: "asd"}]
</code>```

UPD. If the structure of your contents could be more sophisticated than just one tag wrapper, then you should think about using another approach (for example this one and that one).

Title: Array objects values remove unwanted string

Body:
I would use Array.prototype.map and regexp:

const originaldata = [{
  "name": "john",
  "content": '<div class="ExternalClass06EE5E42165840F48DFA193ACAD4F87A">aa</div>'
},
{
  "name": "mary",
  "content": '<div class="ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A">asd</div>'
}];

const regex = /(<([^>]+)>)/ig;

const modifieddata = originaldata.map(item => ({
  name: item.name,
  content: item.content.replace(regex, "")
}));

console.log(modifieddata); // [{name: "john", content: "aa"}, {name: "mary", content: "asd"}]

UPD. If the structure of your contents could be more sophisticated than just one tag wrapper, then you should think about using another approach (for example this one and that one).


问:
How to get dom element value in the page using jquery
Let say I have two fields with id "name" and "address". I want to show the actual value in the div message when I show it to user. And I did

```<code><input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />

<div style="visibility:hidden">
    <div>Your name is $(name)</div>
    <div>Your address is $(address)</div>
</div>
</code>```

I tried

```<code><div style="visibility:hidden">
    <div>Your name is <script>$("input[id=name]").val()</script></div>
    <div>Your address is <script>$("input[id=address]").val())</script></div>
</div>
</code>```

I am getting empty name and address.

Questtion is how can I fix it, is there any better approach? like

```<code><div style="visibility:hidden">
    <div>Your name is <script>GetValue(name)</script></div>
    <div>Your address is <script>GetValue(address)</</script></div>
</div>
</code>```

and use jquery to replace values?

答:
Try this:</p>

```<code><input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />
<div style="visibility:hidden">
    <div>Your name is <span id="userName"></span></div>
    <div>Your address is <span  id="userAddress"></span></div>
</div>
<script type="text/javascript">
    $(function(){
        $("#userName").text($("#name").val());
        $("#userAddress").text($("#address").val());
    });
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Let say I have two fields with id "name" and "address". I want to show the actual value in the div message when I show it to user. And I did

<input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />

Your name is $(name)

Your address is $(address)

I tried

Your name is

Your address is

I am getting empty name and address.

Questtion is how can I fix it, is there any better approach? like

Your name is

Your address is

and use jquery to replace values?

Body:
Try this:

<input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />
<div style="visibility:hidden">
    <div>Your name is <span id="userName"></span></div>
    <div>Your address is <span  id="userAddress"></span></div>
</div>
<script type="text/javascript">
    $(function(){
        $("#userName").text($("#name").val());
        $("#userAddress").text($("#address").val());
    });
</script>


问:
Metadata Parameter IPN Support for Bluesnap Payments Page?
I see that you can pass custom key/value pairs i.e Metadata params in Bluesnap's Hosted Payments Page - https://support.bluesnap.com/docs/creating-a-hosted-payments-page

Are they sent back in the IPN webhook when a transaction is successfully processed? If not - what is the workaround so that I can update my back-end system with the parameters sent in the request?

答:
No, They are not sent back in the IPN webhook when a transaction is successfully processed.
workaround you can use Reporting API to fetch the metadata fields </p>


问:
OAuth 2.0 with Implict Grant type Spring boot app
We are building an application with following tech specs decided.

Angular 4/5 [Front End]

SpringBoot Framework [BackEnd]

OAuth 2.0 [Authorization]

MySQL [Database]

Note : We ourselves are having Resource Server, Authorization Server

Flow

We provide a single instance application for multiple clients [our clients], who will have their own users. Every user will get an email to authorize some stuff for their respective clients via our application. The email link will contain client_id, record_id encrypted and encoded. When the user clicks on the link, it should go to AuthServer, authorize the client via its client_id, and pass back the token to the user agent, to make any further operations.

We went through this Github repo and implemented the same as the sample.

The AuthServer Configure code is as below:

```<code>@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
       clients.inMemory().withClient("my-trusted-client")
             .authorizedGrantTypes("password", "authorization_code",
                            "refresh_token", "implicit")
             .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
             .scopes("read", "write", "trust").resourceIds("sparklr")
             .accessTokenValiditySeconds(60).and()
             .withClient("my-client-with-registered-redirect")
      .authorizedGrantTypes("authorization_code").authorities("ROLE_CLIENT")
             .scopes("read", "trust").resourceIds("sparklr")
             .redirectUris("http://anywhere?key=value").and()
             .withClient("my-client-with-secret")
             .authorizedGrantTypes("client_credentials", "password")
                    .authorities("ROLE_CLIENT").scopes("read").resourceIds("sparklr")
             .secret("secret");

}
</code>```

We have some doubts on the values passed to the configure method.

What does .inMemory().withClient("my-trusted-client") represent here? Will this always be hardcoded? Since we would be validating each client based on the client_id received, where will we feed this to validate dynamically?

What is .withClient("my-client-with-registered-redirect") for? Even this remains constant for every client?

The author in the repo has also said that we can validate the setup via
$ curl -H "Accept: application/json" my-client-with-secret:secret@localhost:8080/oauth/token -d grant_type=client_credentials and I see my-client-with-secret:secret passed here. If this is going to be changed for different clients how can I give this value to .withClient("my-client-with-secret") and .secret("secret")

We are totally tough time understanding these concepts. Our requirement is simple, We are going to validate every client with client_id and generate a token for that client. Do we need to have any other Grant_types for this type of requirements?

Someone please point us in the right direction.

答:
First question:
In your example, the clients are hardcoded (hence the clients.inMemory()). You can configure a datasource and use that:

```<code>@Autowired
DataSource dataSource;

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.jdbc(dataSource); // Get clients from database, table = oauth_client_details
}
</code>```

You can find more info in the documentation

Second question In the example, three clients are configured:

my-trusted-client: this client can authorize using these OAuth2 flows: "password", "authorization_code", "refresh_token", "implicit"

my-client-with-registered-redirect: this client can authorize using these OAuth2 flows: "authorization_code"

my-client-with-secret: this client can authorize using these OAuth2 flows: "client_credentials"

You need to understand the difference between these flows.

Third question if you want to use other clients, you must add them in your code/database

Body:
We are building an application with following tech specs decided.

Angular 4/5 [Front End]

SpringBoot Framework [BackEnd]

OAuth 2.0 [Authorization]

MySQL [Database]

Note : We ourselves are having Resource Server, Authorization Server

Flow

We provide a single instance application for multiple clients [our clients], who will have their own users. Every user will get an email to authorize some stuff for their respective clients via our application. The email link will contain client_id, record_id encrypted and encoded. When the user clicks on the link, it should go to AuthServer, authorize the client via its client_id, and pass back the token to the user agent, to make any further operations.

We went through this Github repo and implemented the same as the sample.

The AuthServer Configure code is as below:

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
       clients.inMemory().withClient("my-trusted-client")
             .authorizedGrantTypes("password", "authorization_code",
                            "refresh_token", "implicit")
             .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
             .scopes("read", "write", "trust").resourceIds("sparklr")
             .accessTokenValiditySeconds(60).and()
             .withClient("my-client-with-registered-redirect")
      .authorizedGrantTypes("authorization_code").authorities("ROLE_CLIENT")
             .scopes("read", "trust").resourceIds("sparklr")
             .redirectUris("http://anywhere?key=value").and()
             .withClient("my-client-with-secret")
             .authorizedGrantTypes("client_credentials", "password")
                    .authorities("ROLE_CLIENT").scopes("read").resourceIds("sparklr")
             .secret("secret");

}

We have some doubts on the values passed to the configure method.

What does .inMemory().withClient("my-trusted-client") represent here? Will this always be hardcoded? Since we would be validating each client based on the client_id received, where will we feed this to validate dynamically?

What is .withClient("my-client-with-registered-redirect") for? Even this remains constant for every client?

The author in the repo has also said that we can validate the setup via
$ curl -H "Accept: application/json" my-client-with-secret:secret@localhost:8080/oauth/token -d grant_type=client_credentials and I see my-client-with-secret:secret passed here. If this is going to be changed for different clients how can I give this value to .withClient("my-client-with-secret") and .secret("secret")

We are totally tough time understanding these concepts. Our requirement is simple, We are going to validate every client with client_id and generate a token for that client. Do we need to have any other Grant_types for this type of requirements?

Someone please point us in the right direction.

Body:
First question:
In your example, the clients are hardcoded (hence the clients.inMemory()). You can configure a datasource and use that:

@Autowired
DataSource dataSource;

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.jdbc(dataSource); // Get clients from database, table = oauth_client_details
}

You can find more info in the documentation

Second question In the example, three clients are configured:

my-trusted-client: this client can authorize using these OAuth2 flows: "password", "authorization_code", "refresh_token", "implicit"

my-client-with-registered-redirect: this client can authorize using these OAuth2 flows: "authorization_code"

my-client-with-secret: this client can authorize using these OAuth2 flows: "client_credentials"

You need to understand the difference between these flows.

Third question if you want to use other clients, you must add them in your code/database


问:
Cannot assign to non-existent property when creating signal and using that
I want to create an signal so I have an qml file with name TestCreateSignal.qml
with content like this:

```<code>import QtQuick 2.0
Rectangle
{
    color: "red"
    width: 344
    height: 233
    signal sendMessage
    MouseArea
    {
        onClicked:
        {
            sendMessage();
        }
    }
}
</code>```

and i want to use this signal in another qml file with name TestUseSignal.qml

```<code>import QtQuick 2.0
Rectangle
{
    TestCreateSignal
    {
        sendMessage: //Error is at this line
        {
            console.log("message sendded");
        }
    }
}
</code>```

but i got error like this when i want to user that

qrc:/TestUseSignal.qml:5 Cannot assign to non-existent property "sendMessage"

答:
According to the docs:

An object can be notified through a signal handler whenever a
  particular signal is emitted. A signal handler is declared with the
  syntax on<Signal> where <Signal> is the name of the signal, with the
  first letter capitalized. The signal handler must be declared within
  the definition of the object that emits the signal, and the handler
  should contain the block of JavaScript code to be executed when the
  signal handler is invoked.

In your case:

```<code>TestCreateSignal
{
    onSendMessage:
    {
        console.log("message sendded");
    }
}
</code>```

Body:
I want to create an signal so I have an qml file with name TestCreateSignal.qml
with content like this:

import QtQuick 2.0
Rectangle
{
    color: "red"
    width: 344
    height: 233
    signal sendMessage
    MouseArea
    {
        onClicked:
        {
            sendMessage();
        }
    }
}

and i want to use this signal in another qml file with name TestUseSignal.qml

import QtQuick 2.0
Rectangle
{
    TestCreateSignal
    {
        sendMessage: //Error is at this line
        {
            console.log("message sendded");
        }
    }
}

but i got error like this when i want to user that

qrc:/TestUseSignal.qml:5 Cannot assign to non-existent property "sendMessage"

Body:
According to the docs:

An object can be notified through a signal handler whenever a
  particular signal is emitted. A signal handler is declared with the
  syntax on<Signal> where <Signal> is the name of the signal, with the
  first letter capitalized. The signal handler must be declared within
  the definition of the object that emits the signal, and the handler
  should contain the block of JavaScript code to be executed when the
  signal handler is invoked.

In your case:

TestCreateSignal
{
    onSendMessage:
    {
        console.log("message sendded");
    }
}


问:
Very simple code, not working
I am trying to elicit two responses depending on user input, and can't get it to work. It just keeps printing "Correct, seems you're smarter than I thought...". Any help would be much appreciated, thank you

```<code>print ("Welcome to UTOPIA")

river= ""
while not river:
    river = input ("\n\n\n\nYou come across a raging river, what do you do? ")

if river == "swim" or "swim through it":
    print ("Correct, seems you're smarter than I thought...")

elif river == "walk through it" or "walk through":
    print ("You cant walk through such a big river... silly!")

else:
    print ("Well, sensible suggestions now...")
</code>```

答:
Because you're doing

```<code>if river == "swim" or "swim through it":
    # ...
</code>```

which is not correct code.
Essentially you're saying "If river is swim or string "swim through it" " which doesn't make sense.

You're looking for

```<code>if river == "swim" or river == "swim through it"
</code>```

Title: Very simple code, not working

Body:
I am trying to elicit two responses depending on user input, and can't get it to work. It just keeps printing "Correct, seems you're smarter than I thought...". Any help would be much appreciated, thank you

print ("Welcome to UTOPIA")

river= ""
while not river:
    river = input ("\n\n\n\nYou come across a raging river, what do you do? ")

if river == "swim" or "swim through it":
    print ("Correct, seems you're smarter than I thought...")

elif river == "walk through it" or "walk through":
    print ("You cant walk through such a big river... silly!")

else:
    print ("Well, sensible suggestions now...")

Body:
Because you're doing

if river == "swim" or "swim through it":
    # ...

which is not correct code.
Essentially you're saying "If river is swim or string "swim through it" " which doesn't make sense.

You're looking for

if river == "swim" or river == "swim through it"


问:
TypeScript, Angular 5 - nested dependencies of imported javascript modules do not resolve
I am attempting to import a javascript library into my angular5/ts application, and while I can get the library itself to load, its nested dependencies fail.

This results in functions that depend on nested dependencies fail.

I have installed the library dependencies via npm, as well as any available typescript definition files. While debugging the library functions, I can see that the injected dependencies are 'undefined'. It also appears that the 'require' keyword is undefined.

I am using import * as xyz from 'library' syntax, which is working in that it is loading the library itself. Just not the dependencies.

The crux of the issue seems to be the imported javascript module uses requirejs for dependency management. All of those dependencies are returned as null. How can we resolve those dependencies and make this library work?

答:
You can import any library
e.g Very popular lodash

```<code>import * as _ from 'lodash';
</code>```

Use in your component

```<code>filter(){
  return _.filter(array, callback)
}
</code>```

Body:
You can import any library
e.g Very popular lodash

import * as _ from 'lodash';

Use in your component

filter(){
  return _.filter(array, callback)
}


问:
Java parsing last part of a string
I have three strings.

```<code>0:0:0-0:0:1
0:0:0-3:0:0-1:2:0
0:0:0-3:0:0-3:2:0-3:2:1
</code>```

I am trying to do an exercise where I am parsing the string to output only the last part after the -, i.e. respectively:

```<code>0:0:1
1:2:0
3:2:1
</code>```

I have tried of doing it by getting all the characters from the end of the string up until -5, but that won't always work (if the numbers are more then 1 integer). lastStateVisited is my string

```<code>lastStateVisited = lastStateVisited.substring(lastStateVisited.length() - 5);
</code>```

I thought of splitting the string in an array and getting the last element of the array, but it seems inefficient.

```<code>String[] result = lastStateVisited.split("[-]");
lastStateVisited = result[result.length - 1];
</code>```

What is a way I could do this? Thanks

答:
Try this:</p>

```<code>String l = "your-string";
int temp = l.lastIndexOf('-');
String lastPart = l.substring(temp+1);
</code>```

Title: Java parsing last part of a string

Body:
I have three strings.

0:0:0-0:0:1
0:0:0-3:0:0-1:2:0
0:0:0-3:0:0-3:2:0-3:2:1

I am trying to do an exercise where I am parsing the string to output only the last part after the -, i.e. respectively:

0:0:1
1:2:0
3:2:1

I have tried of doing it by getting all the characters from the end of the string up until -5, but that won't always work (if the numbers are more then 1 integer). lastStateVisited is my string

lastStateVisited = lastStateVisited.substring(lastStateVisited.length() - 5);

I thought of splitting the string in an array and getting the last element of the array, but it seems inefficient.

String[] result = lastStateVisited.split("[-]");
lastStateVisited = result[result.length - 1];

What is a way I could do this? Thanks

Body:
Try this:

String l = "your-string";
int temp = l.lastIndexOf('-');
String lastPart = l.substring(temp+1);


问:
Dead code in while loop java
If dead codes are illegal in java, why does the following code compile fine without any compile time error : </p>

```<code>int i= 5;

while (i<2) {
  //some code here
}
</code>```

<p>Since the while condition is not getting satisfied, it will never go into the loop, so I assume this should be dead code. But it is getting compiled perfectly. </p>

答:
Java has a very tightly defined set of rules for defining reachability at compile time. (Note that a program can never know in full generality.)

Your case is not one of those, so compilation passes.

(It would be annoying if the reachability rules were constantly changing as that would cause code to break on successive version updates.)

Title: Dead code in while loop java

Body:
If dead codes are illegal in java, why does the following code compile fine without any compile time error :

int i= 5;

while (i<2) {
  //some code here
}

Since the while condition is not getting satisfied, it will never go into the loop, so I assume this should be dead code. But it is getting compiled perfectly.


问:
c# show/hide controls depending on user properties
In my application each user has one clientid but multiple roles.

For example user John has clientid=1 and roles=userx, userz

What I want to achieve is to hide or show controls of my application regarding the user's clientid and role

I have this array in my DB:

```<code>[dbo].[MyMenus](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [controlid] [nvarchar](500) NULL,
    [clientid_available] [nvarchar](50) NULL,
    [clientid_hidden] [nvarchar](50) NULL,
    [role_available] [nvarchar](500) NULL,
    [role_hidden] [nvarchar](500) NULL
</code>```

Where clientid_available, clientid_hidden, role_available, role_hidden contain values separated by comma. If a control has clientid_available then clientid_hidden is null and vice versa. Same thing for role_available and role_hidden

Example: 0 | Control1 | 0,1 | null | userx | null Which means that Control will be visible to users with clientid 0,1 and users in userx role

Here is my code until now:

```<code>var hiddenControls = from c in dc.MyMenus
                                 where c.clientid_hidden != null || c.role_hidden != null
                                 select c;

            var visibleControls = from c in dc.MyMenus
                                  where c.clientid_available != null || c.clientid_available != null
                                  select c;

foreach (var c in hiddenControls)
                {
                    if (c.clientid_hidden != null)
                    {
                        if (c.clientid_hidden.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }

foreach (var c in visibleControls)
                {
                    if (c.clientid_available != null)
                    {
                        if (c.clientid_available.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }
</code>```

But I dont know the logic for the role handling. Because role_available, role_hidden can have multiple values separated by ',' and current user can have multiple roles Roles.GetRolesForUser(HttpContext.Current.User.ToString())

答:
You might use:

```<code>Roles.IsUserInRole

 try
  {
    if (!Roles.IsUserInRole(User.Identity.Name, "Administrators"))
    {
      Msg.Text = "You are not authorized to view user roles.";
      UsersListBox.Visible = false;
      return;
    }
  }
  catch (HttpException e)
  {
    Msg.Text = "There is no current logged on user. Role membership cannot be verified.";
    return;
  }
</code>```

Roles.IsUserInRole Method (String)

https://msdn.microsoft.com/en-us/library/4z6b5d42(v=vs.110).aspx

Body:
In my application each user has one clientid but multiple roles.

For example user John has clientid=1 and roles=userx, userz

What I want to achieve is to hide or show controls of my application regarding the user's clientid and role

I have this array in my DB:

[dbo].[MyMenus](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [controlid] [nvarchar](500) NULL,
    [clientid_available] [nvarchar](50) NULL,
    [clientid_hidden] [nvarchar](50) NULL,
    [role_available] [nvarchar](500) NULL,
    [role_hidden] [nvarchar](500) NULL

Where clientid_available, clientid_hidden, role_available, role_hidden contain values separated by comma. If a control has clientid_available then clientid_hidden is null and vice versa. Same thing for role_available and role_hidden

Example: 0 | Control1 | 0,1 | null | userx | null Which means that Control will be visible to users with clientid 0,1 and users in userx role

Here is my code until now:

var hiddenControls = from c in dc.MyMenus
                                 where c.clientid_hidden != null || c.role_hidden != null
                                 select c;

            var visibleControls = from c in dc.MyMenus
                                  where c.clientid_available != null || c.clientid_available != null
                                  select c;

foreach (var c in hiddenControls)
                {
                    if (c.clientid_hidden != null)
                    {
                        if (c.clientid_hidden.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }

foreach (var c in visibleControls)
                {
                    if (c.clientid_available != null)
                    {
                        if (c.clientid_available.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }

But I dont know the logic for the role handling. Because role_available, role_hidden can have multiple values separated by ',' and current user can have multiple roles Roles.GetRolesForUser(HttpContext.Current.User.ToString())

Body:
You might use:

Roles.IsUserInRole

 try
  {
    if (!Roles.IsUserInRole(User.Identity.Name, "Administrators"))
    {
      Msg.Text = "You are not authorized to view user roles.";
      UsersListBox.Visible = false;
      return;
    }
  }
  catch (HttpException e)
  {
    Msg.Text = "There is no current logged on user. Role membership cannot be verified.";
    return;
  }

Roles.IsUserInRole Method (String)

https://msdn.microsoft.com/en-us/library/4z6b5d42(v=vs.110).aspx


问:
How to Setup a Scheme environment to use with Simply Scheme book?
I am working through the book simply scheme (Harvey, Wright). I want to setup an environment that works well with the code in the book and is easy going for beginners.</p>

答:
It looks like DrRacket should do it.
Make sure to add

```<code>#lang racket
</code>```

At the top of your file.

Body:
It looks like DrRacket should do it.
Make sure to add

#lang racket

At the top of your file.


问:
Logical algorithm to generate paths
I'm trying to develop an algorithm to create a symfony template service.
I want to check if a template exists in a subset of paths, ordered.

Given an array of parameter like this (already ordered like I want):

```<code>$params = ['O', 'U', 'W', 'P']
</code>```

How can I output this array?

```<code>$urls = [
    'O/U/W/P/template',
    'O/U/W/template',
    'O/U/P/template',
    'O/U/template',
    'O/W/P/template',
    'O/W/template',
    'O/P/template',
    'O/template',
    'U/W/P/template',
    'U/W/template',
    'U/P/template',
    'U/template',
    'W/P/template',
    'W/template',
    'P/template',
    'template'
];
</code>```

I can perform for a little list of parameters (like everyone can do it I suppose) with a code like this :

```<code>private function getPaths($template, $params)
{
    $urls           = [];
    $alreadyPerform = [];
    $paramsCounter = count($params);

    for ($i = 0; $i < $paramsCounter; $i++) {
        for ($j = 0; $j < $paramsCounter; $j++) {
            if ($i !== $j && !in_array($params[$j], $alreadyPerform, true)) {
                $urls[] = sprintf(
                    '/%s/%s/%s.html.twig', $params[$i], $params[$j], $template
                );
            }
        }
        $alreadyPerform[] = $params[$i];
        $urls[] = sprintf('/%s/%s.html.twig', $params[$i], $template);
    }
    $urls[] = sprintf('%s.html.twig', $template);

    return $urls;
}
</code>```

This function work like I wanted until today (max 3 parameters), but I want to add one parameters today, maybe more after.

Thank you very much for your help !

Cheers.

答:
Consider using the following package:

https://github.com/drupol/phpermutations

Just a very basic example of what it can do:

```<code>$permutations = new \drupol\phpermutations\Generators\Permutations(['A', 'B', 'C'], 2);
foreach ($permutations->generator() as $permutation) {
    echo implode('/', $permutation);
    echo "\n";
}

A/B
B/A
A/C
C/A
B/C
C/B
</code>```

Title: Logical algorithm to generate paths

Body:
I'm trying to develop an algorithm to create a symfony template service.
I want to check if a template exists in a subset of paths, ordered.

Given an array of parameter like this (already ordered like I want):

$params = ['O', 'U', 'W', 'P']

How can I output this array?

$urls = [
    'O/U/W/P/template',
    'O/U/W/template',
    'O/U/P/template',
    'O/U/template',
    'O/W/P/template',
    'O/W/template',
    'O/P/template',
    'O/template',
    'U/W/P/template',
    'U/W/template',
    'U/P/template',
    'U/template',
    'W/P/template',
    'W/template',
    'P/template',
    'template'
];

I can perform for a little list of parameters (like everyone can do it I suppose) with a code like this :

private function getPaths($template, $params)
{
    $urls           = [];
    $alreadyPerform = [];
    $paramsCounter = count($params);

    for ($i = 0; $i < $paramsCounter; $i++) {
        for ($j = 0; $j < $paramsCounter; $j++) {
            if ($i !== $j && !in_array($params[$j], $alreadyPerform, true)) {
                $urls[] = sprintf(
                    '/%s/%s/%s.html.twig', $params[$i], $params[$j], $template
                );
            }
        }
        $alreadyPerform[] = $params[$i];
        $urls[] = sprintf('/%s/%s.html.twig', $params[$i], $template);
    }
    $urls[] = sprintf('%s.html.twig', $template);

    return $urls;
}

This function work like I wanted until today (max 3 parameters), but I want to add one parameters today, maybe more after.

Thank you very much for your help !

Cheers.

Body:
Consider using the following package:

https://github.com/drupol/phpermutations

Just a very basic example of what it can do:

$permutations = new \drupol\phpermutations\Generators\Permutations(['A', 'B', 'C'], 2);
foreach ($permutations->generator() as $permutation) {
    echo implode('/', $permutation);
    echo "\n";
}

A/B
B/A
A/C
C/A
B/C
C/B


答:
Java cannot determine the value of a variable in general without simply running the program. If it runs your program, it risks failing to terminate. So there is no general way to determine whether or not that loop will always run or not. There will always be cases that the compiler gets wrong, so it uses basic heuristics to handle the easy cases and leaves it at that.

Further reading

Title: Dead code in while loop java


问:
Given a string of a million numbers, return all repeating 3 digit numbers
I had an interview with a hedge fund company in New York a few months ago and unfortunately, I did not get the internship offer as a data/software engineer. (They also asked the solution to be in Python.)

I pretty much screwed up on the first interview problem...

Question: Given a string of a million numbers (Pi for example), write
  a function/program that returns all repeating 3 digit numbers and number of
  repetition greater than 1

For example: if the string was: 123412345123456 then the function/program would return:

```<code>123 - 3 times
234 - 3 times
345 - 2 times
</code>```

They did not give me the solution after I failed the interview, but they did tell me that the time complexity for the solution was constant of 1000 since all the possible outcomes are between:

000 --> 999

Now that I'm thinking about it, I don't think it's possible to come up with a constant time algorithm. Is it?

Body:
I had an interview with a hedge fund company in New York a few months ago and unfortunately, I did not get the internship offer as a data/software engineer. (They also asked the solution to be in Python.)

I pretty much screwed up on the first interview problem...

Question: Given a string of a million numbers (Pi for example), write
  a function/program that returns all repeating 3 digit numbers and number of
  repetition greater than 1

For example: if the string was: 123412345123456 then the function/program would return:

123 - 3 times
234 - 3 times
345 - 2 times

They did not give me the solution after I failed the interview, but they did tell me that the time complexity for the solution was constant of 1000 since all the possible outcomes are between:

000 --> 999

Now that I'm thinking about it, I don't think it's possible to come up with a constant time algorithm. Is it?

Body:
inputStr = '123456123138276237284287434628736482376487234682734682736487263482736487236482634'

count = {}
for i in range(len(inputStr) - 2):
    subNum = int(inputStr[i:i+3])
    if subNum not in count:
        count[subNum] = 1
    else:
        count[subNum] += 1

print count


问:
How to set a value for a selectize.js input?
I have a form from which I would like to copy some default values into the inputs.  The form inputs are using the selectize.js plugin.  I would like to set some of the form values programatically.  The standard way of doing this:

```<code>$("#my_input").val("My Default Value");
</code>```

does not work.

I have tried something like this but it does not work either.

```<code>var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue("My Default Value");
</code>```

Any ideas?  It's got to be easy :)  I'm missing it.

答:
I had a similar problem. My data is provided by a remote server. I want some value to be entered in the selectize box, but it is not sure in advance whether this value is a valid one on the server.

So I want the value to be entered in the box, and I want selectize to show the possible options just if like the user had entered the value.

I ended up using this hack (which it is probably unsupported):

```<code>var $selectize = $("#my_input").selectize(/* settings with load*/);
var selectize = $select[0].selectize;
// get the search from the remote server
selectize.onSearchChange('my value');
// enter the input in the input field
$selectize.parent().find('input').val('my value');
// focus on the input field, to make the options visible
$selectize.parent().find('input').focus();
</code>```

Body:
I have a form from which I would like to copy some default values into the inputs.  The form inputs are using the selectize.js plugin.  I would like to set some of the form values programatically.  The standard way of doing this:

$("#my_input").val("My Default Value");

does not work.

I have tried something like this but it does not work either.

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue("My Default Value");

Any ideas?  It's got to be easy :)  I'm missing it.

Body:
I had a similar problem. My data is provided by a remote server. I want some value to be entered in the selectize box, but it is not sure in advance whether this value is a valid one on the server.

So I want the value to be entered in the box, and I want selectize to show the possible options just if like the user had entered the value.

I ended up using this hack (which it is probably unsupported):

var $selectize = $("#my_input").selectize(/* settings with load*/);
var selectize = $select[0].selectize;
// get the search from the remote server
selectize.onSearchChange('my value');
// enter the input in the input field
$selectize.parent().find('input').val('my value');
// focus on the input field, to make the options visible
$selectize.parent().find('input').focus();


问:
How to set title in WPF without refresh all window page

Hi !
I have a WPF application and I want to set the title of the window page without refresh the all page, because in this page I have two buttons that list a DataRow belong the Title when I press it.

```<code>void refreshStatusBar()
    {

            this.Title= "Holaaa";

    }
</code>```

WPF class:

```<code><Height=.... Title="Prueba"...> the initial value
</code>```

The problem is when I press a button (next or back) I need to set the Title of the page and never change when I call to refreshStatusBar() in the btNext or btBack method.

I tryed to binding the Title, but don´t work. Always show the same value, the initial:

```<code>Title="{Binding Path="windowTitleBar"}"

public String windowTitleBar {get; set;}

void refreshStatusBar(){
   windowTitleBar="Holaaa";
 }
</code>```

I want the title change when I press some button. I don´t have pages inside the window page, just show one thing or another thing.

I tryed too:

```<code>Title="{Binding Path=windowTitleBar, RelativeSource={RelativeSource Mode=Self}}"
</code>```

and don´t work neither.

Please, any solution to fix it?

Sorry for my english !

Thanks !

答:
This works for me without a binding:

```<code>public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();

        this.Title = "Hellooo";
    }

    void RefreshStatusBar()
    {
        this.Title = "Holaaa";
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        RefreshStatusBar();
    }
}
</code>```

If you want to use a binding, set it up like you did with Title="{Binding Path=WindowTitleBar, RelativeSource={RelativeSource Mode=Self}}"

But as it is, WPF has no way of knowing when your property value changes. You can implement INotifyPropertyChanged to solve this:

```<code>public partial class MainWindow : Window, INotifyPropertyChanged
{
    private string _windowTitleBar = "Hellooo";

    public MainWindow()
    {
        this.WindowTitleBar = "Hellooo";

        InitializeComponent();

    }

    public string WindowTitleBar
    {
        get { return _windowTitleBar; }
        set
        {
            _windowTitleBar = value;
            OnPropertyChanged("WindowTitleBar");
        }
    }

    void RefreshStatusBar()
    {
        this.WindowTitleBar = "Holaaa";
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if(PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        RefreshStatusBar();
    }
}
</code>```

Edit:

I just noticed you said "Page". I've never used Pages, but it looks like to set the title of the window containing your page, you have to set the WindowTitle property. Unfortunately it's not a DependencyProperty so you can't use a binding. You can set it directly, though:

```<code>void RefreshStatusBar()
{
    this.WindowTitle = "Holaaa";
}
</code>```

Body:
Hi !
I have a WPF application and I want to set the title of the window page without refresh the all page, because in this page I have two buttons that list a DataRow belong the Title when I press it.

void refreshStatusBar()
    {

            this.Title= "Holaaa";

    }

WPF class:

<Height=.... Title="Prueba"...> the initial value

The problem is when I press a button (next or back) I need to set the Title of the page and never change when I call to refreshStatusBar() in the btNext or btBack method.

I tryed to binding the Title, but don´t work. Always show the same value, the initial:

Title="{Binding Path="windowTitleBar"}"

public String windowTitleBar {get; set;}

void refreshStatusBar(){
   windowTitleBar="Holaaa";
 }

I want the title change when I press some button. I don´t have pages inside the window page, just show one thing or another thing.

I tryed too:

Title="{Binding Path=windowTitleBar, RelativeSource={RelativeSource Mode=Self}}"

and don´t work neither.

Please, any solution to fix it?

Sorry for my english !

Thanks !

Body:
This works for me without a binding:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();

        this.Title = "Hellooo";
    }

    void RefreshStatusBar()
    {
        this.Title = "Holaaa";
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        RefreshStatusBar();
    }
}

If you want to use a binding, set it up like you did with Title="{Binding Path=WindowTitleBar, RelativeSource={RelativeSource Mode=Self}}"

But as it is, WPF has no way of knowing when your property value changes. You can implement INotifyPropertyChanged to solve this:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private string _windowTitleBar = "Hellooo";

    public MainWindow()
    {
        this.WindowTitleBar = "Hellooo";

        InitializeComponent();

    }

    public string WindowTitleBar
    {
        get { return _windowTitleBar; }
        set
        {
            _windowTitleBar = value;
            OnPropertyChanged("WindowTitleBar");
        }
    }

    void RefreshStatusBar()
    {
        this.WindowTitleBar = "Holaaa";
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if(PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        RefreshStatusBar();
    }
}

Edit:

I just noticed you said "Page". I've never used Pages, but it looks like to set the title of the window containing your page, you have to set the WindowTitle property. Unfortunately it's not a DependencyProperty so you can't use a binding. You can set it directly, though:

void RefreshStatusBar()
{
    this.WindowTitle = "Holaaa";
}


问:
Do not receive certain PHP error messages
I am running Apache/PHP locally, and do receive errors in many cases, like uninitialized variables - but I have noticed a few cases where I do not receive error messages and am wondering if this is normal OR if I am missing out on anything,

```<code><?php

ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);

$1a = "Hello world!";
echo $1a;

?>
</code>```

Also producing no error:

```<code><?php

ini_set('display_errors', 'On');
error_reporting(E_ALL);

function a()
{
 $b = 5;
 echo $b;
}}

a();

?>
</code>```

Does this script product PHP errors as it should for you? If so, I am wondering why I receive none. This is not an error I am likely to make, but there have been other times where I receive a blank page like above, where I would like some sort of feedback.

答:
Open up php.ini, and CTRL-F for display_errors - is it set to on? When I installed php I used ini_set(); to try and see errors and it didn't work, but editing the php.ini file worked.

Edit: I looked at your phpinfo() output on the page you posted, and it's set to off. Turn it on if you can. If I recall correctly, you have to restart apache after you edit it.

Edit2: In your php.ini file, error_reporting should be set to E_ALL & ~E_NOTICE (default), E_ALL | E_STRICT (development), or E_ALL & ~E_DEPRECATED (production). Honestly, that's all gibberish to me - but if it helps, mine is set to E_ALL & ~E_DEPRECATED, and I recieved errors from your code.

Body:
I am running Apache/PHP locally, and do receive errors in many cases, like uninitialized variables - but I have noticed a few cases where I do not receive error messages and am wondering if this is normal OR if I am missing out on anything,

<?php

ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);

$1a = "Hello world!";
echo $1a;

?>

Also producing no error:

<?php

ini_set('display_errors', 'On');
error_reporting(E_ALL);

function a()
{
 $b = 5;
 echo $b;
}}

a();

?>

Does this script product PHP errors as it should for you? If so, I am wondering why I receive none. This is not an error I am likely to make, but there have been other times where I receive a blank page like above, where I would like some sort of feedback.


问:
ExtJS 6 Usage of Ext.data.Model.toUrl() method
In my application, I use Ext.app.BaseController.redirectTo() and route change events to switch between UIs. A number of interfaces at each opening should be associated with a specific set of data.

I've noticed Ext.data.Model.toUrl() method (used internally by controller's .redirectTo() method), but I do not see associated method for getting model back by URL. Of course, it's trivial to handle the URL manually and find the corresponding model, but I want to know if there is a standard mechanism for this "out of the box"?

答:
There doesn't seem to be. And it makes sense. I personally override the toUrl method in most cases, and it would be "impossible" to create an associated method that will reverse the result of any override.

Even in the API Docs they presume that this method will be overridden:

By default this just returns the name of the Model class followed by
  the instance ID


问:
casting a pointer to struct for qsort's compare
So I'm using qsort() in c and my compare function usually consist of creating a pointer of the correct type and assigning it the value from the arguments. is it possible to just cast the pointer from the arguments without creating a new one?
if so, what am i doing wrong?

```<code>struct date_t{
    int time;
    int dob;
};

/* the old working function
int cmpfunc (const void * one, const void * two) {
    struct date_t *itemtwo=two;
    struct date_t *itemone=one;
return itemone->time-itemtwo->time;
}
*/

int cmpfunc (const void * one, const void * two) {
    return (struct date_t*)(one)->time - (struct date_t*)two->time;
}
</code>```

i'm getting :

```<code>main.c:17:30: warning: dereferencing 'void *' pointer
  return (struct date_t*)(one)->time - (struct date_t*)two->time;
                          ^~
main.c:17:30: error: request for member 'time' in something not a structure or union
</code>```

EDIT:

i got it to compile with

```<code>int cmpfunc (struct date_t *one, struct date_t *two) {
    return one->time - two->time;
}
</code>```

but still, how would i do it with casts?

答:
According to the handy precedence table, the cast operation has a lower precedence than the structure member access operator ->. So when doing (struct date_t*)(one)->time, first the member time is accessed (and failed, as one is a void* and has no such a member). And only then the cast is performed on the result. Instead you should force the precedence by using parentheses in appropriate places like:

```<code>... ((struct date_t*)one)->time ...
</code>```

Body:
So I'm using qsort() in c and my compare function usually consist of creating a pointer of the correct type and assigning it the value from the arguments. is it possible to just cast the pointer from the arguments without creating a new one?
if so, what am i doing wrong?

struct date_t{
    int time;
    int dob;
};

/* the old working function
int cmpfunc (const void * one, const void * two) {
    struct date_t *itemtwo=two;
    struct date_t *itemone=one;
return itemone->time-itemtwo->time;
}
*/

int cmpfunc (const void * one, const void * two) {
    return (struct date_t*)(one)->time - (struct date_t*)two->time;
}

i'm getting :

main.c:17:30: warning: dereferencing 'void *' pointer
  return (struct date_t*)(one)->time - (struct date_t*)two->time;
                          ^~
main.c:17:30: error: request for member 'time' in something not a structure or union

EDIT:

i got it to compile with

int cmpfunc (struct date_t *one, struct date_t *two) {
    return one->time - two->time;
}

but still, how would i do it with casts?

Body:
According to the handy precedence table, the cast operation has a lower precedence than the structure member access operator ->. So when doing (struct date_t*)(one)->time, first the member time is accessed (and failed, as one is a void* and has no such a member). And only then the cast is performed on the result. Instead you should force the precedence by using parentheses in appropriate places like:

... ((struct date_t*)one)->time ...


问:
Listen to promise as a stream
I have been reading about Observables. One thing I read about, is its ability to listen like a stream. I tried this using the following code.

```<code>const Rx = require('rxjs/Rx');
Promise = require('bluebird');

let i = 0;

function calculate() {
    return new Promise((resolve, reject) => {
        setInterval(() => {
            console.log(++i);
            resolve(i);
        }, 5000);
    })
}

let source = Rx.Observable.fromPromise(calculate());

source.subscribe(
    next => {
        console.log(next, ' next ');
    },
    err => {
        console.error(err)
    },
    () => {
        console.log('done!');
    }
)
</code>```

But it didn't work like a stream. So the output looks something like:

```<code>1
1 ' next '
done!
2
3
</code>```

How do I continue listening to the promise? Is this one of the problem Observable really solve?

答:
Observable.fromPromise is thought to convert a Promise to an Observable. As promises only can resolve once, this stream will always only output 1 item.

You can't enhance a promise functionality by wraping a stream over it. If the promise can only yield 1 value, only 1 value will get yielded in the resulting observable.

In your specific example, there's Observable.interval(n) which emits 1 item every n milliseconds. Else, for a more custom observable:

```<code>Rx.Observable.create(obs => {
    let i=0;
    setInterval(() => {
        obs.next(++i);
    }, 1000);
});
</code>```

When you create an observable, you get an Observer instance that represents the observer that just subscribed to your stream. Notice that each new observer will create a new context (so in my example, each observer will have his i counter).

Title: Listen to promise as a stream

Body:
I have been reading about Observables. One thing I read about, is its ability to listen like a stream. I tried this using the following code.

const Rx = require('rxjs/Rx');
Promise = require('bluebird');

let i = 0;

function calculate() {
    return new Promise((resolve, reject) => {
        setInterval(() => {
            console.log(++i);
            resolve(i);
        }, 5000);
    })
}

let source = Rx.Observable.fromPromise(calculate());

source.subscribe(
    next => {
        console.log(next, ' next ');
    },
    err => {
        console.error(err)
    },
    () => {
        console.log('done!');
    }
)

But it didn't work like a stream. So the output looks something like:

1
1 ' next '
done!
2
3

How do I continue listening to the promise? Is this one of the problem Observable really solve?

Body:
Observable.fromPromise is thought to convert a Promise to an Observable. As promises only can resolve once, this stream will always only output 1 item.

You can't enhance a promise functionality by wraping a stream over it. If the promise can only yield 1 value, only 1 value will get yielded in the resulting observable.

In your specific example, there's Observable.interval(n) which emits 1 item every n milliseconds. Else, for a more custom observable:

Rx.Observable.create(obs => {
    let i=0;
    setInterval(() => {
        obs.next(++i);
    }, 1000);
});

When you create an observable, you get an Observer instance that represents the observer that just subscribed to your stream. Notice that each new observer will create a new context (so in my example, each observer will have his i counter).


问:
Google map change polyline strokeweight when zoom change
How can change polyline strokeweight when zoom change like Uber

The Polyline width change when the camera zoom change

答:
You can add listener to listen the onCameraIdle event. This event happens each time the camera finished movement. Inside this listener you can calculate a width of the line according to the camera zoom.

I've created a simple example that executes sample directions request to get a sample polyline and draws this polyline on map. The onCameraIdle listener recalculates the polyline width. Please have a look at sample code:

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnCameraIdleListener {

    private GoogleMap mMap;
    private Polyline mPoly;

    private String TAG = MapsActivity.class.getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        LatLng pos = new LatLng(41.381087,2.176731);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 16));

        mMap.getUiSettings().setZoomControlsEnabled(true);

        //Get sample polyline and draw it
        List<LatLng> path = this.getSamplePoly();
        if (path.size() > 0) {
            PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(this.getLineWidth());
            mPoly = mMap.addPolyline(opts);
        }

        //Set listener for camera idle event
        mMap.setOnCameraIdleListener(this);
    }

    @Override
    public void onCameraIdle() {
        mPoly.setWidth(this.getLineWidth());
    }

    //Defines a width of polyline as some function of zoom
    private int getLineWidth() {
        float zoom = mMap.getCameraPosition().zoom;
        float a = (zoom-12>0 ? (zoom-12)*(zoom-12) : 1);
        return Math.round(a);
    }

    //Executes directions request to get sample polyline
    private List<LatLng> getSamplePoly () {
        List<LatLng> path = new ArrayList();

        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey("YOUR_API_KEY")
                .build();

        DirectionsApiRequest req = DirectionsApi.getDirections(context, "41.381624,2.176058", "41.380503,2.177116");
        try {
            DirectionsResult res = req.await();

            //Loop through legs and steps to get encoded polylines of each step
            if (res.routes != null && res.routes.length > 0) {
                DirectionsRoute route = res.routes[0];

                if (route.legs !=null) {
                    for(int i=0; i<route.legs.length; i++) {
                        DirectionsLeg leg = route.legs[i];
                        if (leg.steps != null) {
                            for (int j=0; j<leg.steps.length;j++){
                                DirectionsStep step = leg.steps[j];
                                if (step.steps != null && step.steps.length >0) {
                                    for (int k=0; k<step.steps.length;k++){
                                        DirectionsStep step1 = step.steps[k];
                                        EncodedPolyline points1 = step1.polyline;
                                        if (points1 != null) {
                                            //Decode polyline and add points to list of route coordinates
                                            List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
                                            for (com.google.maps.model.LatLng coord1 : coords1) {
                                                path.add(new LatLng(coord1.lat, coord1.lng));
                                            }
                                        }
                                    }
                                } else {
                                    EncodedPolyline points = step.polyline;
                                    if (points != null) {
                                        //Decode polyline and add points to list of route coordinates
                                        List<com.google.maps.model.LatLng> coords = points.decodePath();
                                        for (com.google.maps.model.LatLng coord : coords) {
                                            path.add(new LatLng(coord.lat, coord.lng));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch(Exception ex) {
            Log.e(TAG, ex.getLocalizedMessage());
        }

        return path;
    }
}
</code>```

You can download this example from the github repository:

https://github.com/xomena-so/so45566330

Don't forget replace API keys with yours.

I hope this helps!

Body:
You can add listener to listen the onCameraIdle event. This event happens each time the camera finished movement. Inside this listener you can calculate a width of the line according to the camera zoom.

I've created a simple example that executes sample directions request to get a sample polyline and draws this polyline on map. The onCameraIdle listener recalculates the polyline width. Please have a look at sample code:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnCameraIdleListener {

    private GoogleMap mMap;
    private Polyline mPoly;

    private String TAG = MapsActivity.class.getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        LatLng pos = new LatLng(41.381087,2.176731);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 16));

        mMap.getUiSettings().setZoomControlsEnabled(true);

        //Get sample polyline and draw it
        List<LatLng> path = this.getSamplePoly();
        if (path.size() > 0) {
            PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(this.getLineWidth());
            mPoly = mMap.addPolyline(opts);
        }

        //Set listener for camera idle event
        mMap.setOnCameraIdleListener(this);
    }

    @Override
    public void onCameraIdle() {
        mPoly.setWidth(this.getLineWidth());
    }

    //Defines a width of polyline as some function of zoom
    private int getLineWidth() {
        float zoom = mMap.getCameraPosition().zoom;
        float a = (zoom-12>0 ? (zoom-12)*(zoom-12) : 1);
        return Math.round(a);
    }

    //Executes directions request to get sample polyline
    private List<LatLng> getSamplePoly () {
        List<LatLng> path = new ArrayList();

        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey("YOUR_API_KEY")
                .build();

        DirectionsApiRequest req = DirectionsApi.getDirections(context, "41.381624,2.176058", "41.380503,2.177116");
        try {
            DirectionsResult res = req.await();

            //Loop through legs and steps to get encoded polylines of each step
            if (res.routes != null && res.routes.length > 0) {
                DirectionsRoute route = res.routes[0];

                if (route.legs !=null) {
                    for(int i=0; i<route.legs.length; i++) {
                        DirectionsLeg leg = route.legs[i];
                        if (leg.steps != null) {
                            for (int j=0; j<leg.steps.length;j++){
                                DirectionsStep step = leg.steps[j];
                                if (step.steps != null && step.steps.length >0) {
                                    for (int k=0; k<step.steps.length;k++){
                                        DirectionsStep step1 = step.steps[k];
                                        EncodedPolyline points1 = step1.polyline;
                                        if (points1 != null) {
                                            //Decode polyline and add points to list of route coordinates
                                            List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
                                            for (com.google.maps.model.LatLng coord1 : coords1) {
                                                path.add(new LatLng(coord1.lat, coord1.lng));
                                            }
                                        }
                                    }
                                } else {
                                    EncodedPolyline points = step.polyline;
                                    if (points != null) {
                                        //Decode polyline and add points to list of route coordinates
                                        List<com.google.maps.model.LatLng> coords = points.decodePath();
                                        for (com.google.maps.model.LatLng coord : coords) {
                                            path.add(new LatLng(coord.lat, coord.lng));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch(Exception ex) {
            Log.e(TAG, ex.getLocalizedMessage());
        }

        return path;
    }
}

You can download this example from the github repository:

https://github.com/xomena-so/so45566330

Don't forget replace API keys with yours.

I hope this helps!


问:
Why append don't work, pass by reference?
I have writtern the below codes

```<code>a = [1,2,3]
b = a.append(4)
</code>```

Why there is nothing inside b?

答:
append returns None, That's why there is nothing in b. Your list a will be modified and added 4.

If you realy want to add 4 in b then you can try a + [4]

Body:
I have writtern the below codes

a = [1,2,3]
b = a.append(4)

Why there is nothing inside b?


问:
Java8: Implement multiple conditional statements with stream API
I have a code block that redirects a Cassandra query to different Cassandra tables based on the available parameters such that I check multiple logical conditions inside multiple if conditions. I'm trying my hand at java 8 and looking to reduce these conditions to lambda expressions. Here's how the code currently looks,

```<code>String processTable(String cid, String postcode, String[] ratingvalue, String ratingType) {

    String table = "";
    if (postcode != null && ratingvalue == null) {
        table = cassconf.getTable1();
    }
    if (postcode != null && ratingvalue != null) {
        table = cassconf.getTable2();
    }
    if (cid != null && ratingvalue == null) {
        table = cassconf.getTable3();
    }
    if (cid != null && ratingvalue != null) {
        table = cassconf.getTable4();
    }
    if (cid != null && postcode != null && ratingvalue == null) {
        table = cassconf.getTable5();
    }
    if (cid != null && postcode != null & ratingvalue != null) {
        table = cassconf.getTable6();
    }
    return table;

}
</code>```

My problem is even if I store the arguments in a map and filter the unavailable values from the stream, I don't know how to return the final value of the table based on these 6 different conditions.

答:
Considering that ratingvalue can only be null or non-null, you can simplify the code by writing effectively unconditional statements as such:

```<code>String processTable(String cid, String postcode, String[] ratingvalue, String ratingType) {
    if (cid != null)
        if(postcode != null)
            return ratingvalue == null? cassconf.getTable5(): cassconf.getTable6();
        else
            return ratingvalue == null? cassconf.getTable3(): cassconf.getTable4();
    if(postcode != null)
        return ratingvalue == null? cassconf.getTable1(): cassconf.getTable2();
    return "";
}
</code>```

Testing the conditions with precedence first is also more efficient than testing all conditions in reversed order and overwriting results of previous evaluations.

You could also write the entire evaluation as a single condition:

```<code>String processTable(String cid, String postcode, String[] ratingvalue, String ratingType) {
    return cid != null?
        postcode != null? ratingvalue == null? cassconf.getTable5(): cassconf.getTable6():
                          ratingvalue == null? cassconf.getTable3(): cassconf.getTable4():
        postcode != null? ratingvalue == null? cassconf.getTable1(): cassconf.getTable2():
                          "";
}
</code>```

An alternative is to use a map lookup:

```<code>String processTable(String cid, String postcode, String[] ratingvalue, String ratingType) {
    final int hasCID = 1, hasPostcode = 2, hasRatingValue = 4;
    Map<Integer, Supplier<String>> map = new HashMap<>();
    map.put(hasCID|hasPostcode, cassconf::getTable5);
    map.put(hasCID|hasPostcode|hasRatingValue, cassconf::getTable6);
    map.put(hasCID, cassconf::getTable3);
    map.put(hasCID|hasRatingValue, cassconf::getTable4);
    map.put(hasPostcode, cassconf::getTable2);
    map.put(hasPostcode|hasRatingValue, cassconf::getTable1);

    return map.getOrDefault(
        (cid!=null? hasCID: 0) | (postcode!=null? hasPostcode: 0)
                               | (ratingvalue!=null? hasRatingValue: 0),
        () -> "").get();
}
</code>```

The key point of this alternative is that, depending on what cassconf is or when it will be initialized, the map may be prepared at an earlier stage and processTable could be simplified to the return map.getOrDefault… operation.

Body:
I have a code block that redirects a Cassandra query to different Cassandra tables based on the available parameters such that I check multiple logical conditions inside multiple if conditions. I'm trying my hand at java 8 and looking to reduce these conditions to lambda expressions. Here's how the code currently looks,

String processTable(String cid, String postcode, String[] ratingvalue, String ratingType) {

    String table = "";
    if (postcode != null && ratingvalue == null) {
        table = cassconf.getTable1();
    }
    if (postcode != null && ratingvalue != null) {
        table = cassconf.getTable2();
    }
    if (cid != null && ratingvalue == null) {
        table = cassconf.getTable3();
    }
    if (cid != null && ratingvalue != null) {
        table = cassconf.getTable4();
    }
    if (cid != null && postcode != null && ratingvalue == null) {
        table = cassconf.getTable5();
    }
    if (cid != null && postcode != null & ratingvalue != null) {
        table = cassconf.getTable6();
    }
    return table;

}

My problem is even if I store the arguments in a map and filter the unavailable values from the stream, I don't know how to return the final value of the table based on these 6 different conditions.

Body:
Considering that ratingvalue can only be null or non-null, you can simplify the code by writing effectively unconditional statements as such:

String processTable(String cid, String postcode, String[] ratingvalue, String ratingType) {
    if (cid != null)
        if(postcode != null)
            return ratingvalue == null? cassconf.getTable5(): cassconf.getTable6();
        else
            return ratingvalue == null? cassconf.getTable3(): cassconf.getTable4();
    if(postcode != null)
        return ratingvalue == null? cassconf.getTable1(): cassconf.getTable2();
    return "";
}

Testing the conditions with precedence first is also more efficient than testing all conditions in reversed order and overwriting results of previous evaluations.

You could also write the entire evaluation as a single condition:

String processTable(String cid, String postcode, String[] ratingvalue, String ratingType) {
    return cid != null?
        postcode != null? ratingvalue == null? cassconf.getTable5(): cassconf.getTable6():
                          ratingvalue == null? cassconf.getTable3(): cassconf.getTable4():
        postcode != null? ratingvalue == null? cassconf.getTable1(): cassconf.getTable2():
                          "";
}

An alternative is to use a map lookup:

String processTable(String cid, String postcode, String[] ratingvalue, String ratingType) {
    final int hasCID = 1, hasPostcode = 2, hasRatingValue = 4;
    Map<Integer, Supplier<String>> map = new HashMap<>();
    map.put(hasCID|hasPostcode, cassconf::getTable5);
    map.put(hasCID|hasPostcode|hasRatingValue, cassconf::getTable6);
    map.put(hasCID, cassconf::getTable3);
    map.put(hasCID|hasRatingValue, cassconf::getTable4);
    map.put(hasPostcode, cassconf::getTable2);
    map.put(hasPostcode|hasRatingValue, cassconf::getTable1);

    return map.getOrDefault(
        (cid!=null? hasCID: 0) | (postcode!=null? hasPostcode: 0)
                               | (ratingvalue!=null? hasRatingValue: 0),
        () -> "").get();
}

The key point of this alternative is that, depending on what cassconf is or when it will be initialized, the map may be prepared at an earlier stage and processTable could be simplified to the return map.getOrDefault… operation.


问:
Adding Table Columns to a Group by clause - Ruby on Rails - Postgresql
I am trying to use Heroku and apparently Postgresql is a lot more strict than SQL for aggregate functions. When I am pushing to Heroku I am getting an error stating the below.

On another question I asked I received some guidance that said I should just add the columns to my group by clause and I am not sure how to do that. See the full error below and the PostsControll#index.

```<code>SELECT posts.*, count(*) as vote_total FROM "posts"   INNER JOIN "votes" ON votes.post_id = posts.id   GROUP BY votes.post_id ORDER BY created_at DESC LIMIT 5 OFFSET 0):
</code>```

PostsController

```<code>def index
    @tag_counts = Tag.count(:group => :tag_name,
       :order => 'count_all DESC', :limit => 20)
       conditions, joins = {}, :votes

    @ugtag_counts = Ugtag.count(:group => :ugctag_name,
       :order => 'count_all DESC', :limit => 20)
       conditions, joins = {}, :votes

    @vote_counts = Vote.count(:group => :post_title,
          :order => 'count_all DESC', :limit => 20)
          conditions, joins = {}, :votes

       unless(params[:tag_name] || "").empty?
         conditions = ["tags.tag_name = ? ", params[:tag_name]]
         joins = [:tags, :votes]
       end
       @posts=Post.paginate(
                 :select => "posts.*, count(*) as vote_total",
                 :joins => joins,
                 :conditions=> conditions,
                 :group => "votes.post_id",
                 :order => "created_at DESC",
                 :page => params[:page], :per_page => 5)
        @popular_posts=Post.paginate(
                 :select => "posts.*, count(*) as vote_total",
                 :joins => joins,
                 :conditions=> conditions,
                 :group => "votes.post_id",
                 :order => "vote_total DESC",
                 :page => params[:page], :per_page => 3)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
      format.json { render :json => @posts }
      format.atom
    end
  end
</code>```

答:
I came up with a variation which involves creating the table name join fiends dynamically rather than at compile time

model_columns = Model.column_names.collect do |c| "#{Model.table_name}.#{c}" end.join(",")

Body:
I am trying to use Heroku and apparently Postgresql is a lot more strict than SQL for aggregate functions. When I am pushing to Heroku I am getting an error stating the below.

On another question I asked I received some guidance that said I should just add the columns to my group by clause and I am not sure how to do that. See the full error below and the PostsControll#index.

SELECT posts.*, count(*) as vote_total FROM "posts"   INNER JOIN "votes" ON votes.post_id = posts.id   GROUP BY votes.post_id ORDER BY created_at DESC LIMIT 5 OFFSET 0):

PostsController

def index
    @tag_counts = Tag.count(:group => :tag_name,
       :order => 'count_all DESC', :limit => 20)
       conditions, joins = {}, :votes

    @ugtag_counts = Ugtag.count(:group => :ugctag_name,
       :order => 'count_all DESC', :limit => 20)
       conditions, joins = {}, :votes

    @vote_counts = Vote.count(:group => :post_title,
          :order => 'count_all DESC', :limit => 20)
          conditions, joins = {}, :votes

       unless(params[:tag_name] || "").empty?
         conditions = ["tags.tag_name = ? ", params[:tag_name]]
         joins = [:tags, :votes]
       end
       @posts=Post.paginate(
                 :select => "posts.*, count(*) as vote_total",
                 :joins => joins,
                 :conditions=> conditions,
                 :group => "votes.post_id",
                 :order => "created_at DESC",
                 :page => params[:page], :per_page => 5)
        @popular_posts=Post.paginate(
                 :select => "posts.*, count(*) as vote_total",
                 :joins => joins,
                 :conditions=> conditions,
                 :group => "votes.post_id",
                 :order => "vote_total DESC",
                 :page => params[:page], :per_page => 3)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
      format.json { render :json => @posts }
      format.atom
    end
  end


问:
NameError: name '`Timevalue`' is not defined
I store data in csv file  as follwing:

```<code>row = dict_items([('Time ': '2017-12-01T13:54:04'), ('Energy [kWh]': '0.01'), ('Voltage [V]': '221.64'), ('Current [A]': '0.08')])
</code>```

Now i want to store it like that:

```<code>('Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01'),
('Time ': '2017-12-01T13:54:04','Voltage [V]': '221.64'),
('Time ': '2017-12-01T13:54:04','Current [A]': '0.08')])
</code>```

so i wrote this code bellow and i define

```<code>    Device=""
    Value=""
    for key, value in row.items():
        print(row.items())
        if key == 'Time':
            Timevalue = value
            print(Zeitvalue)
        Device = key
        Value = value
        doc = {'Device':Device, 'Measure':Value , 'Time':Timevalue }
</code>```

i got this error:
NameError: name 'Timevalue' is not defined
How can i make the Timevalue variable globale to avoid this Problem?
Thank you

答:
That ('Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01') syntax is not valid Python. Assuming you actually want a list of dictionaries, it's not too hard to perform that conversion.

You first need to grab the time stamp so it can be combined with each of the other items, and then you can drop it from the dict to make it easier to copy the remaining items to the new structure. Note that this modifies the original dict passed to the function. If you don't want that, you can either make a copy of the passed-in dict, or put an if test in the loop that copies the data to the new structure so that the time item is skipped.

```<code>def convert(old):
    time_key = 'Time '
    # Save the time
    time_item = (time_key, old[time_key])
    # Add remove it
    del old[time_key]
    # Copy remaining items to new dicts and save them in a list
    return [dict([time_item, item]) for item in old.items()]

row = {
    'Time ': '2017-12-01T13:54:04',
    'Energy [kWh]': '0.01',
    'Voltage [V]': '221.64',
    'Current [A]': '0.08',
}

new_data = convert(row)
for d in new_data:
    print(d)
</code>```

output

```<code>{'Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01'}
{'Time ': '2017-12-01T13:54:04', 'Voltage [V]': '221.64'}
{'Time ': '2017-12-01T13:54:04', 'Current [A]': '0.08'}
</code>```

Here's how to do it if you don't want to mutate or copy the original dict:

```<code>def convert(old):
    time_key = 'Time '
    # Save the time
    time_item = (time_key, old[time_key])
    # Copy other items to new dicts and save them in a list
    return [dict([time_item, (key, val)])
        for key, val in old.items() if key != time_key]
</code>```

Note that this is less efficient because it has to test every key to ensure it's not the time key.

To save the data in a list of OrderedDicts, we need to change the logic slightly. We also need to create the OrderedDicts properly so that the items are in the desired order.

```<code>from collections import OrderedDict
from pprint import pprint

def convert(row):
    time_key = 'Time '
    time_value = row[time_key]
    new_data = []
    for key, val in row.items():
        if key == time_key:
            continue
        new_data.append(OrderedDict(Device=key, Measure=val, Time=time_value))
    return new_data

row = {
    'Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01',
    'Voltage [V]': '221.64', 'Current [A]': '0.08'
}

new_data = convert(row)
pprint(new_data)
</code>```

output

```<code>[OrderedDict([('Device', 'Energy [kWh]'),
              ('Measure', '0.01'),
              ('Time', '2017-12-01T13:54:04')]),
 OrderedDict([('Device', 'Voltage [V]'),
              ('Measure', '221.64'),
              ('Time', '2017-12-01T13:54:04')]),
 OrderedDict([('Device', 'Current [A]'),
              ('Measure', '0.08'),
              ('Time', '2017-12-01T13:54:04')])]
</code>```

Body:
I store data in csv file  as follwing:

row = dict_items([('Time ': '2017-12-01T13:54:04'), ('Energy [kWh]': '0.01'), ('Voltage [V]': '221.64'), ('Current [A]': '0.08')])

Now i want to store it like that:

('Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01'),
('Time ': '2017-12-01T13:54:04','Voltage [V]': '221.64'),
('Time ': '2017-12-01T13:54:04','Current [A]': '0.08')])

so i wrote this code bellow and i define

    Device=""
    Value=""
    for key, value in row.items():
        print(row.items())
        if key == 'Time':
            Timevalue = value
            print(Zeitvalue)
        Device = key
        Value = value
        doc = {'Device':Device, 'Measure':Value , 'Time':Timevalue }

i got this error:
NameError: name 'Timevalue' is not defined
How can i make the Timevalue variable globale to avoid this Problem?
Thank you

Body:
That ('Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01') syntax is not valid Python. Assuming you actually want a list of dictionaries, it's not too hard to perform that conversion.

You first need to grab the time stamp so it can be combined with each of the other items, and then you can drop it from the dict to make it easier to copy the remaining items to the new structure. Note that this modifies the original dict passed to the function. If you don't want that, you can either make a copy of the passed-in dict, or put an if test in the loop that copies the data to the new structure so that the time item is skipped.

def convert(old):
    time_key = 'Time '
    # Save the time
    time_item = (time_key, old[time_key])
    # Add remove it
    del old[time_key]
    # Copy remaining items to new dicts and save them in a list
    return [dict([time_item, item]) for item in old.items()]

row = {
    'Time ': '2017-12-01T13:54:04',
    'Energy [kWh]': '0.01',
    'Voltage [V]': '221.64',
    'Current [A]': '0.08',
}

new_data = convert(row)
for d in new_data:
    print(d)

output

{'Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01'}
{'Time ': '2017-12-01T13:54:04', 'Voltage [V]': '221.64'}
{'Time ': '2017-12-01T13:54:04', 'Current [A]': '0.08'}

Here's how to do it if you don't want to mutate or copy the original dict:

def convert(old):
    time_key = 'Time '
    # Save the time
    time_item = (time_key, old[time_key])
    # Copy other items to new dicts and save them in a list
    return [dict([time_item, (key, val)])
        for key, val in old.items() if key != time_key]

Note that this is less efficient because it has to test every key to ensure it's not the time key.

To save the data in a list of OrderedDicts, we need to change the logic slightly. We also need to create the OrderedDicts properly so that the items are in the desired order.

from collections import OrderedDict
from pprint import pprint

def convert(row):
    time_key = 'Time '
    time_value = row[time_key]
    new_data = []
    for key, val in row.items():
        if key == time_key:
            continue
        new_data.append(OrderedDict(Device=key, Measure=val, Time=time_value))
    return new_data

row = {
    'Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01',
    'Voltage [V]': '221.64', 'Current [A]': '0.08'
}

new_data = convert(row)
pprint(new_data)

output

[OrderedDict([('Device', 'Energy [kWh]'),
              ('Measure', '0.01'),
              ('Time', '2017-12-01T13:54:04')]),
 OrderedDict([('Device', 'Voltage [V]'),
              ('Measure', '221.64'),
              ('Time', '2017-12-01T13:54:04')]),
 OrderedDict([('Device', 'Current [A]'),
              ('Measure', '0.08'),
              ('Time', '2017-12-01T13:54:04')])]


问:
Sencha ext.js, create form on the fly
I'm trying to follow the tutorial of extjs about adding a form on click.

Now the "twist" is that I directly wish to create a more structured approach. So I'm using Ext.define to create both a grid and a form, for the grid.

The grid:

```<code>Ext.define('MyApp.view.main.EmployeeGrid', {
    extend: 'Ext.grid.Grid',
    xtype: 'employee-grid',

    title: 'Employee Directory',
    iconCls: 'x-fa fa-users',
    listeners: {
        itemtap: function() {
            console.log("test");
            Ext.create("MyApp.view.main.FormPanel", {});
        }
    },
    store: {
        data: [{
            "firstName": "Jean",
            "lastName": "Grey",
            "phoneNumber": "(372) 792-6728"
        }]
    },

    columns: [{
        text: 'First Name',
        dataIndex: 'firstName',
        flex: 1
    }, {
        text: 'Last Name',
        dataIndex: 'lastName',
        flex: 1
    }, {
        text: 'Phone Number',
        dataIndex: 'phoneNumber',
        flex: 1
    }]
});
</code>```

the form:

```<code>Ext.define("MyApp.view.main.FormPanel", {
    extend: "Ext.form.Panel",
    xtype: 'form-panel',
    title: 'Update Record',
    floating: true,
    centered: true,
    width: 300,
    modal: true,
    items: [{
        xtype: 'textfield',
        name: 'firstname',
        label: 'First Name'
    }, {
        xtype: 'toolbar',
        docked: 'bottom',
        items: ['->', {
            xtype: 'button',
            text: 'Submit',
            iconCls: 'x-fa fa-check',
            handler: function() {
                this.up('formpanel').destroy();
            }
        }, {
            xtype: 'button',
            text: 'Cancel',
            iconCls: 'x-fa fa-close',
            handler: function() {
                this.up('formpanel').destroy();
            }
        }]
    }]
});
</code>```

The problematic code is under the listeners: ... in the MyApp.view.main.EmployeeGrid class. The console is entry is logged, so I know the function is executed. However no form is shown. - What is the correct approach here?

答:
Yes, as you said, no form is shown, because a newly created form is not shown by default.

Two solutions:

You can add to the form autoShow: true OR

You can add execute the show function on the created form: Ext.create(...).show()

However, I would recommend that you reuse the form, so instantiate a new one only once, store it on your grid, and reuse it for subsequent calls:

```<code>itemtap: function(view, index, target, record) {
    if(!this.myForm) this.myForm = Ext.create("Ext.form.Panel", {});
    this.myForm.loadRecord(record);
    this.myForm.show();
}
</code>```

For this to work, you may have to set closeAction: 'hide' on the form.

In at least some versions of ExtJS 6, it seemed to me as if IE exhibited memory leaks on component instantiation, so one should create as few new components as possible.

Title: Sencha ext.js, create form on the fly

Body:
I'm trying to follow the tutorial of extjs about adding a form on click.

Now the "twist" is that I directly wish to create a more structured approach. So I'm using Ext.define to create both a grid and a form, for the grid.

The grid:

Ext.define('MyApp.view.main.EmployeeGrid', {
    extend: 'Ext.grid.Grid',
    xtype: 'employee-grid',

    title: 'Employee Directory',
    iconCls: 'x-fa fa-users',
    listeners: {
        itemtap: function() {
            console.log("test");
            Ext.create("MyApp.view.main.FormPanel", {});
        }
    },
    store: {
        data: [{
            "firstName": "Jean",
            "lastName": "Grey",
            "phoneNumber": "(372) 792-6728"
        }]
    },

    columns: [{
        text: 'First Name',
        dataIndex: 'firstName',
        flex: 1
    }, {
        text: 'Last Name',
        dataIndex: 'lastName',
        flex: 1
    }, {
        text: 'Phone Number',
        dataIndex: 'phoneNumber',
        flex: 1
    }]
});

the form:

Ext.define("MyApp.view.main.FormPanel", {
    extend: "Ext.form.Panel",
    xtype: 'form-panel',
    title: 'Update Record',
    floating: true,
    centered: true,
    width: 300,
    modal: true,
    items: [{
        xtype: 'textfield',
        name: 'firstname',
        label: 'First Name'
    }, {
        xtype: 'toolbar',
        docked: 'bottom',
        items: ['->', {
            xtype: 'button',
            text: 'Submit',
            iconCls: 'x-fa fa-check',
            handler: function() {
                this.up('formpanel').destroy();
            }
        }, {
            xtype: 'button',
            text: 'Cancel',
            iconCls: 'x-fa fa-close',
            handler: function() {
                this.up('formpanel').destroy();
            }
        }]
    }]
});

The problematic code is under the listeners: ... in the MyApp.view.main.EmployeeGrid class. The console is entry is logged, so I know the function is executed. However no form is shown. - What is the correct approach here?

Body:
Yes, as you said, no form is shown, because a newly created form is not shown by default.

Two solutions:

You can add to the form autoShow: true OR

You can add execute the show function on the created form: Ext.create(...).show()

However, I would recommend that you reuse the form, so instantiate a new one only once, store it on your grid, and reuse it for subsequent calls:

itemtap: function(view, index, target, record) {
    if(!this.myForm) this.myForm = Ext.create("Ext.form.Panel", {});
    this.myForm.loadRecord(record);
    this.myForm.show();
}

For this to work, you may have to set closeAction: 'hide' on the form.

In at least some versions of ExtJS 6, it seemed to me as if IE exhibited memory leaks on component instantiation, so one should create as few new components as possible.