问:
Return an array where the new elements are the sum of sum of distances between indices with same value in a given array
For each index in a given array I want to find the sum of sum of the distances between that index and other indices which have the same value in a given array.

So for [1,2,1,1,2,3], we would have [5,3,3,4,3,0] because

for index 0) |2-0|+|3-0| = 5, for index 1) |4-1| = 3 ,... , for index 3) |3-0|+|3-2| = 4,... etc..

Here is my attempt which gets TLE for arrays of length near 10000.

How can I make my solution more efficient?

```<code>def getDistanceMetrics(arr):
    if len(arr) > 10**5 or len(arr) < 1:
        return -1
    for z in range(len(arr)):
        if arr[z] > 10**9 or arr[z] < 1:
            return -1

    # Write your code here
    hm = collections.defaultdict(set)

    for i,value in enumerate(arr):
        hm[value].add(i)

    ans = []

    for j,val in enumerate(arr):
        tmp = 0
        for element in hm[val]:
            tmp += (j-element) if (j-element) >= 0 else element - j
        ans.append(tmp)

    return ans
</code>```

I would also appreciate knowing as to why and where my answer is slow, because to me it looks like O(n), which seems as good as you could do here.

答:
for every element in array, you iterate over its hm once.

thus, in the worst case if we have lots of numbers with the same value (say n), for every element, you will iterate over the whole array, which is O(n^2)

Body:
For each index in a given array I want to find the sum of sum of the distances between that index and other indices which have the same value in a given array.

So for [1,2,1,1,2,3], we would have [5,3,3,4,3,0] because

for index 0) |2-0|+|3-0| = 5, for index 1) |4-1| = 3 ,... , for index 3) |3-0|+|3-2| = 4,... etc..

Here is my attempt which gets TLE for arrays of length near 10000.

How can I make my solution more efficient?

def getDistanceMetrics(arr):
    if len(arr) > 10**5 or len(arr) < 1:
        return -1
    for z in range(len(arr)):
        if arr[z] > 10**9 or arr[z] < 1:
            return -1

    # Write your code here
    hm = collections.defaultdict(set)

    for i,value in enumerate(arr):
        hm[value].add(i)

    ans = []

    for j,val in enumerate(arr):
        tmp = 0
        for element in hm[val]:
            tmp += (j-element) if (j-element) >= 0 else element - j
        ans.append(tmp)

    return ans

I would also appreciate knowing as to why and where my answer is slow, because to me it looks like O(n), which seems as good as you could do here.


来源: stackexchange

问:
How do I add the like facebook button to a silverlight application?
I'm new to silverlight 4 development.
I need the facebook I like button to be integrated integrated on my website application?

Can someone tell me how to do that?

Can I download a library that will provide me a user control that is visible in my toolbox, and thus I will be able to just drag and drop this item on my page?
If not, how can I implement this functionality?

答:
You can just download a like button image from here and use the Facebook SDK to like the page.

I haven't tried it myself but it should be possible.

Another approach will be to use the Javascript API and call it from silverlight.

Here's how: http://www.dotnetspider.com/tutorials/Silverlight-Tutorial-321.aspx

http://www.switchonthecode.com/tutorials/silverlight-and-javascript-interaction

http://www.mostlydevelopers.com/blog/post/2008/08/11/Call-Javascript-Method-from-Silverlight-and-Vice-Versa.aspx

ContentLicense: CC BY-SA 3.0


问:
How to search in JSON with Javascript fast?
I have a lemmatization nested dictionaries, like

```<code>{
{"abbreviate": ["abbreviated","abbreviates","abbreviating"]},
{"abdicate": ["abdicated","abdicates","abdicating"]}
}
</code>```

I want to fast search inside values to get the according key (find abbreviated → output abbreviate). Fast - because the file is about 6MB. This search will be used in a Chrome extension, so i would strongly prefer Javascript, not Python.

What are technics to accomplish such search?

答:
It seems to me that you need to convert an object to a form for quick hash search:

```<code>{
    abbreviated: 'abbreviate',
    abbreviates: 'abbreviate',
    abbreviating: 'abbreviate',
    abdicated: 'abdicate',
    abdicates: 'abdicate',
    abdicating: 'abdicate',
};
</code>```

const data = {
    abbreviate: ['abbreviated', 'abbreviates', 'abbreviating'],
    abdicate: ['abdicated', 'abdicates', 'abdicating'],
};

const dictionary = Object.keys(data).reduce((dict, key) => {
    const records = data[key];
    const obj = records.reduce((acc, val) => ({ ...acc, [val]: key }), {});

    return { ...dict, ...obj };
}, {});

console.log(dictionary['abbreviated']);```

ContentLicense: CC BY-SA 4.0

Body:
I have a lemmatization nested dictionaries, like

{
{"abbreviate": ["abbreviated","abbreviates","abbreviating"]},
{"abdicate": ["abdicated","abdicates","abdicating"]}
}

I want to fast search inside values to get the according key (find abbreviated → output abbreviate). Fast - because the file is about 6MB. This search will be used in a Chrome extension, so i would strongly prefer Javascript, not Python.

What are technics to accomplish such search?

Body:
It seems to me that you need to convert an object to a form for quick hash search:

{
    abbreviated: 'abbreviate',
    abbreviates: 'abbreviate',
    abbreviating: 'abbreviate',
    abdicated: 'abdicate',
    abdicates: 'abdicate',
    abdicating: 'abdicate',
};

const data = {
    abbreviate: ['abbreviated', 'abbreviates', 'abbreviating'],
    abdicate: ['abdicated', 'abdicates', 'abdicating'],
};

const dictionary = Object.keys(data).reduce((dict, key) => {
    const records = data[key];
    const obj = records.reduce((acc, val) => ({ ...acc, [val]: key }), {});

    return { ...dict, ...obj };
}, {});

console.log(dictionary['abbreviated']);


问:
How to set up a health check on an individual GCE - Internal IP
I want to create an uptime health check for an application running on GCE with Internal IP.

I've noticed that Uptime checks in GCP only supports external IP and health checks only support a GCE with Load Balancer or a Managed Instance group.

Is there a any other GCP way to create a health check? I'm not sure if Cloud functions help.

答: As per my research with GCP team, private uptime check EAP is about to release in upcoming month  which might address your issue , as presently its in alpha stage so need to whitelist your project to use this alpha feature.</p>


问:
Specific Image not appearing in website unless I rename it?
I am learning HTML. I made a website for my photography and have some photos on my home page as the background, using:

background-image: url("images/homepage/IMAGE_NAME.jpg")

However, I noticed there is one specific image, named "DSC_0251.jpg", that does not display unless I rename it. I thought it was the underscore or the capital letter D causing it to not display, but I have other images in the same folder, that are named similarly, such as "DSC_0704small.jpg". They both start with a capital letter and have and underscore, the latter having even more than the former. However, "DSC_0251.jpg" will not display, until I renamed it, even just calling it "1.jpg" worked. I did not change the size of the image, it is 1.4mb, and everything else is exactly the same.

In other words, this line of code works:

background-image: url("images/homepage/DSC_0067.jpg")

but this line does not:

background-image: url("images/homepage/DSC_0251.jpg")

I used Filezilla to upload the files, and I thought maybe it was because I dragged and dropped the image to the server folder directly from the location on my computer, rather than navigating to the location within Filezilla and dragging and dropping it that way, but I tried it with another similarly sized and named photo, but that one worked. I want to keep the name the same so I know what it is, and plus it's a problem that needs a solution anyway, if it comes up again. Thank you!

答:
If it is a Linux system, try checking the permissions of the file! I had a similar issue where my css and images, didn't load after copying to the new machine, for the same reason. As for windows, I don't work with them!
Just a noobie...</p>


问:
How to fix Google Cloud Messaging Registration error: SERVICE_NOT_AVAILABLE?
I encountered a strange problem - I've been using GCM in my application for quite a long time and everything works perfectly. However, before a release to Google Play I changed my application package name from com.android.testapp to com.android.recognition and after this GCM stopped working. At first I got en error GCM sender id not set on constructor and fixed it by overriding getSenderIds(Context context), but now I can't get a registration ID. Here are the messages from logcat:

How can I fix this? When I switched to a new package I changed everything in the manifest file to the new package:

```<code><receiver
        android:name="com.google.android.gcm.GCMBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="com.android.recognition" />
        </intent-filter>
    </receiver>
</code>```

So what is the problem behind this? Can renaming the application package cause this or is there another reason?

答:
In my case, this happened because my mobile phone does not have a SIM card inside it.

I guess that having the sim card sets the Automatic time on the device, which resolves this.

Body:
I encountered a strange problem - I've been using GCM in my application for quite a long time and everything works perfectly. However, before a release to Google Play I changed my application package name from com.android.testapp to com.android.recognition and after this GCM stopped working. At first I got en error GCM sender id not set on constructor and fixed it by overriding getSenderIds(Context context), but now I can't get a registration ID. Here are the messages from logcat:

How can I fix this? When I switched to a new package I changed everything in the manifest file to the new package:

<receiver
        android:name="com.google.android.gcm.GCMBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="com.android.recognition" />
        </intent-filter>
    </receiver>

So what is the problem behind this? Can renaming the application package cause this or is there another reason?


问:
How to filter dataframe from multiple condition and replacing differnt value in Dataframe Column in python?
I have a Dataframe

```<code>PROD   TYPE  QUANTI CONFI avail  req
 wood   i     20     100   1000  800
 tv     u     30     100   500   600
 tabl   i     50     100   300   200
 rmt    z     40     100   50    100
 zet    y     60     100   200   400
 rm     t     60     100   300   500
 rt     f     80     100   500   200
 dud    i     40     100   900   800
</code>```

I want to keep Column "CONFI" to 100 if avail- req >80

"CONFI" to 10 if column "TYPE" is "i" (if it satisfy the condition ) and "CONFI" to 0 if it does not.

( Means"TYPE"== "i" could either be 10 or 0)

And rest to zero if it doesn't meet any condition

```<code>PROD   TYPE  QUANTI CONFI avail  req
 wood   i     20     10   1000   800
 tv     u     30     100   700   600
 tabl   i     50     0     300   250
 rmt    z     40     0     50    100
 zet    y     60     100   200   400
 rm     t     60     0     300   500
 rt     f     80     100   500   200
 dud    i     40     10    900   800
</code>```

Body:
I have a Dataframe

PROD   TYPE  QUANTI CONFI avail  req
 wood   i     20     100   1000  800
 tv     u     30     100   500   600
 tabl   i     50     100   300   200
 rmt    z     40     100   50    100
 zet    y     60     100   200   400
 rm     t     60     100   300   500
 rt     f     80     100   500   200
 dud    i     40     100   900   800

I want to keep Column "CONFI" to 100 if avail- req >80

"CONFI" to 10 if column "TYPE" is "i" (if it satisfy the condition ) and "CONFI" to 0 if it does not.

( Means"TYPE"== "i" could either be 10 or 0)

And rest to zero if it doesn't meet any condition

PROD   TYPE  QUANTI CONFI avail  req
 wood   i     20     10   1000   800
 tv     u     30     100   700   600
 tabl   i     50     0     300   250
 rmt    z     40     0     50    100
 zet    y     60     100   200   400
 rm     t     60     0     300   500
 rt     f     80     100   500   200
 dud    i     40     10    900   800

Body:
IIUC use:

m1 = (df.avail - df.req) > 80
m2 = df.TYPE == 'i'

df['CONFI'] = np.where(m2, 10, np.where(m1, 100, 0))
print (df)
   PROD TYPE  QUANTI  CONFI  avail  req
0  wood    i      20     10   1000  800
1    tv    u      30    100    700  600
2  tabl    i      50     10    300  200
3   rmt    z      40      0     50  100
4   zet    y      60      0    200  400
5    rm    t      60      0    300  500
6    rt    f      80    100    500  200
7   dud    i      40     10    900  800

Solution with numpy.select:

df['CONFI1'] = np.select([m2,m1], [10,100], 0)


问:
What is the difference between signed and unsigned variables?
I have seen these mentioned in the context of C and C++, but what is the difference between signed and unsigned variables? </p>

答:
Unsigned variables are variables which are internally represented without a mathematical sign (plus or minus) can store 'zero' or positive values only. Let us say the unsigned variable is n bits in size, then it can represent 2^n (2 power n) values - 0 through (2^n -1). A signed variable on the other hand, 'loses' one bit for representing the sign, so it can store values from -(2^(n-1) -1) through (2^(n-1)) including zero. Thus, a signed variable can store positive values, negative values and zero.

P.S.:

Internally, the mathematical sign may be represented in one's complement form, two's complement form or with a sign bit (eg: 0 -> +, 1-> -)

All these methods effectively divide the range of representable values in n bits (2^n) into three parts, positive, negative and zero.

This is just my two cents worth.

I hope this helps.

OwnerDisplayName: batbrat

ContentLicense: CC BY-SA 2.5


问:
Reading a text file word by word in C
I am trying to learn file I/O operations in C. My aim is storing all the words to a string array from a text file.

I tried to write a code that reads text file char by char and creates words from those chars. What I want to do is accessing to a word with line and word index. Would you help me about this?

This is my code.

```<code>char words[MAX_LINE][MAX_WORDS][MAX_CHAR];
int i=1, j=1, k=1;

FILE* ptrbook;
if((ptrbook = fopen("trial.txt", "r")) == NULL)
{
    printf("Failed to open the file %s\n", filename);
}
else
{
    while((words[i][j][k] = getc(ptrbook)) != EOF)
    {
        while((words[i][j][k] = getc(ptrbook)) != '\n')
        {
            while((words[i][j][k] = getc(ptrbook)) != ' ')
            {
                words[i][j][k] = getc(ptrbook);
                k++;
            }
            if((words[i][j][k] = getc(ptrbook)) == ' ' )
            {
                j++;
                k=1;
            }
            if((words[i][j][k] = getc(ptrbook)) == '\n')
            {
                i++;
                j=1;
                k=1;
            }
        }
    }
}
printf("%s\n", words[1][1]);
</code>```

答:
Try to call getc(ptrbook) only once per loop and store the result temporarly. Than you can check for the splitting characters such as white space and line breaks. Currently you are jumping in each while loop from character to character, which is not what you want here.

Do something like this:

```<code>int c;
while((c = getc(ptrbook)) != EOF){
    if(c == ' ')
        j++;
    else if(c == '\n')
        i++;
    else
        words[i][j][k++] = c;
}
</code>```

Title: Reading a text file word by word in C

Body:
I am trying to learn file I/O operations in C. My aim is storing all the words to a string array from a text file.

I tried to write a code that reads text file char by char and creates words from those chars. What I want to do is accessing to a word with line and word index. Would you help me about this?

This is my code.

char words[MAX_LINE][MAX_WORDS][MAX_CHAR];
int i=1, j=1, k=1;

FILE* ptrbook;
if((ptrbook = fopen("trial.txt", "r")) == NULL)
{
    printf("Failed to open the file %s\n", filename);
}
else
{
    while((words[i][j][k] = getc(ptrbook)) != EOF)
    {
        while((words[i][j][k] = getc(ptrbook)) != '\n')
        {
            while((words[i][j][k] = getc(ptrbook)) != ' ')
            {
                words[i][j][k] = getc(ptrbook);
                k++;
            }
            if((words[i][j][k] = getc(ptrbook)) == ' ' )
            {
                j++;
                k=1;
            }
            if((words[i][j][k] = getc(ptrbook)) == '\n')
            {
                i++;
                j=1;
                k=1;
            }
        }
    }
}
printf("%s\n", words[1][1]);

Body:
Try to call getc(ptrbook) only once per loop and store the result temporarly. Than you can check for the splitting characters such as white space and line breaks. Currently you are jumping in each while loop from character to character, which is not what you want here.

Do something like this:

int c;
while((c = getc(ptrbook)) != EOF){
    if(c == ' ')
        j++;
    else if(c == '\n')
        i++;
    else
        words[i][j][k++] = c;
}


问:
I need advice with my password generator python script
I need help with my code. I wrote a script that generates a password. However, when I added 'while-loop' it doesn't seem to work well. The code worked without 'while-loop'.
Additionally, I was thinking to store the password that was generated into a database, like SQLite. Here is the code:
Thanks!</p>

```<code>import random
import string

let = string.ascii_letters
num = string.digits
pun = string.punctuation

while True:
    name = str(input('Enter Yes to initiate | type END to exit: ').lower())

    if name == 'end':
        print('Thanks!')
        break

    else:
        if name == 'yes':

            def get_passcode_lenght():
                length = input("How long do you want your password? ")
                return int(length)

            def passcode_generator(cbl,length=4):
                showpass = user_choice_combo(cbl)
                showpass = list(showpass)
                random.shuffle(showpass)

                random_passcode = random.choices(showpass, k=length)
                random_passcode = ''.join(random_passcode)
                return random_passcode

            def passcode_combo_choice():

                digits = (input("Do you want digits? | Yes or No: ")).lower()
                letters = (input("Do you want letters? | Yes or No: ")).lower()
                puncts = (input("Do you want punctuations? | Yes or No: ")).lower()
                Yes = True
                No = False

                try:
                    digits = eval(digits.title())
                    letters = eval(letters.title())
                    puncts = eval(puncts.title())
                    return [digits, letters, puncts]
                except NameError:
                    print("Invalid value. Use either Yes or No")
                    print("Invalidity returns a default, try again to regenerate")
                return [Yes, Yes, Yes]

            def user_choice_combo(choice_list):
                string_constant = ''
                string_constant += num if choice_list[0] else ''
                string_constant += let if choice_list[1] else ''
                string_constant += pun if choice_list[2] else ''
                return string_constant

if __name__ == '__main__':
    length = get_passcode_lenght()
    choice_list = passcode_combo_choice()
    password = passcode_generator(choice_list, length)
    print(password)
</code>```

答:
I think you are confused about function definition vs function usage. def my_fun defines a function so that you can later use it. To execute that function you'll need to call it with my_fun(). So your code should look more like this:

```<code>def get_passcode_length():
    ....

....
if name == 'yes':
    get_passcode_length()
    ....
</code>```

Body:
I need help with my code. I wrote a script that generates a password. However, when I added 'while-loop' it doesn't seem to work well. The code worked without 'while-loop'.
Additionally, I was thinking to store the password that was generated into a database, like SQLite. Here is the code:
Thanks!

import random
import string

let = string.ascii_letters
num = string.digits
pun = string.punctuation

while True:
    name = str(input('Enter Yes to initiate | type END to exit: ').lower())

    if name == 'end':
        print('Thanks!')
        break

    else:
        if name == 'yes':

            def get_passcode_lenght():
                length = input("How long do you want your password? ")
                return int(length)

            def passcode_generator(cbl,length=4):
                showpass = user_choice_combo(cbl)
                showpass = list(showpass)
                random.shuffle(showpass)

                random_passcode = random.choices(showpass, k=length)
                random_passcode = ''.join(random_passcode)
                return random_passcode

            def passcode_combo_choice():

                digits = (input("Do you want digits? | Yes or No: ")).lower()
                letters = (input("Do you want letters? | Yes or No: ")).lower()
                puncts = (input("Do you want punctuations? | Yes or No: ")).lower()
                Yes = True
                No = False

                try:
                    digits = eval(digits.title())
                    letters = eval(letters.title())
                    puncts = eval(puncts.title())
                    return [digits, letters, puncts]
                except NameError:
                    print("Invalid value. Use either Yes or No")
                    print("Invalidity returns a default, try again to regenerate")
                return [Yes, Yes, Yes]

            def user_choice_combo(choice_list):
                string_constant = ''
                string_constant += num if choice_list[0] else ''
                string_constant += let if choice_list[1] else ''
                string_constant += pun if choice_list[2] else ''
                return string_constant

if __name__ == '__main__':
    length = get_passcode_lenght()
    choice_list = passcode_combo_choice()
    password = passcode_generator(choice_list, length)
    print(password)

Body:
I think you are confused about function definition vs function usage. def my_fun defines a function so that you can later use it. To execute that function you'll need to call it with my_fun(). So your code should look more like this:

def get_passcode_length():
    ....

....
if name == 'yes':
    get_passcode_length()
    ....


问:
How to mapping an Object with ArrayList with Retrofit2?
I have trying to make this call works, but always the return is null (and the problem isn't on API). If I try to make a Call  (Object with ArrayList), the callback is successful but the body is null. How I mapping this with Retrofit2 (I'm new with Retrofit2)? This is my service:

```<code>  @GET("farms/abstract")
  Call<Farm> getFarmList(@Header("Authorization") String token);
</code>```

The API response:

```<code>{
    "farms": [
        {
            "id": "0fc2b30c-4500-c399-4171-e2809373e281",
            "name": "Areado"
        },
        {
            "id": "81041a28-1193-4310-b616-fabcabdf63d1",
            "name": "Fazenda 3"
        }
    ]
}
</code>```

I use jsonschema2pojo.org to make my classes:

```<code>public class Farm {
    @SerializedName("farms")
    @Expose
    private List<FarmList> farms;

    public Farm() {
    }

    public List<FarmList> getFarms() {
        return farms;
    }

    public void setFarms(List<FarmList> farms) {
        this.farms = farms;
    }

    @Override
    public String toString() {
        return "Farm{" +
                "farms=" + farms +
                '}';
    }
}
</code>```

My FarmList.class:

```<code>public class FarmList {

    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("name")
    @Expose
    private String name;

    public FarmList() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "FarmList{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}
</code>```

RetrofitConfig:

```<code>public class RetrofitConfig {
    private final Retrofit retrofit;

    public RetrofitConfig() {
        this.retrofit = new Retrofit.Builder()
                /*URL API*/
                .baseUrl("API_URL")

                .addConverterFactory(GsonConverterFactory.create())

                .build();
    }

    public LoginService getLogin() {
        return this.retrofit.create(LoginService.class);
    }

    public FarmService getFarm() {
        return this.retrofit.create(FarmService.class);
    }

    public FarmService getFarmList() {
        return this.retrofit.create(FarmService.class);
    }
}
</code>```

答:
I have tested with mocky.io http://www.mocky.io/v2/5ed4f4b23300006500f7a5e0.
and it's working fine, seems your header created a problem. Make your API call like below

```<code>@Headers("Content-Type: application/json")
@GET("farms/abstract")
Call<Farm> getFarmList();
</code>```

And create a Function for Auth In your RetrofitConfig like below

```<code> public static Retrofit createServiceWithAuth(Context mContext,String token) {

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new AuthorizationInterceptor(token))
                .build();

        this.retrofit = new Retrofit.Builder()
                .baseUrl("API_URL")
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();

        return  this.retrofit;
    }

</code>```

Add this Class

```<code>public class AuthorizationInterceptor implements Interceptor {

    private String authorizationKey;

    public AuthorizationInterceptor() {

    }

    public AuthorizationInterceptor(String token) {
        this.authorizationKey = token;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        final Request request = chain.request().newBuilder()
                .addHeader("token",authorizationKey)
                .build();

        return chain.proceed(request);
    }

    public String getAuthorizationKey() {
        return authorizationKey;
    }

    public void setAuthorizationKey(String authorizationKey) {
        this.authorizationKey = authorizationKey;
    }
</code>```

Body:
I have trying to make this call works, but always the return is null (and the problem isn't on API). If I try to make a Call  (Object with ArrayList), the callback is successful but the body is null. How I mapping this with Retrofit2 (I'm new with Retrofit2)? This is my service:

  @GET("farms/abstract")
  Call<Farm> getFarmList(@Header("Authorization") String token);

The API response:

{
    "farms": [
        {
            "id": "0fc2b30c-4500-c399-4171-e2809373e281",
            "name": "Areado"
        },
        {
            "id": "81041a28-1193-4310-b616-fabcabdf63d1",
            "name": "Fazenda 3"
        }
    ]
}

I use jsonschema2pojo.org to make my classes:

public class Farm {
    @SerializedName("farms")
    @Expose
    private List<FarmList> farms;

    public Farm() {
    }

    public List<FarmList> getFarms() {
        return farms;
    }

    public void setFarms(List<FarmList> farms) {
        this.farms = farms;
    }

    @Override
    public String toString() {
        return "Farm{" +
                "farms=" + farms +
                '}';
    }
}

My FarmList.class:

public class FarmList {

    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("name")
    @Expose
    private String name;

    public FarmList() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "FarmList{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

RetrofitConfig:

public class RetrofitConfig {
    private final Retrofit retrofit;

    public RetrofitConfig() {
        this.retrofit = new Retrofit.Builder()
                /*URL API*/
                .baseUrl("API_URL")

                .addConverterFactory(GsonConverterFactory.create())

                .build();
    }

    public LoginService getLogin() {
        return this.retrofit.create(LoginService.class);
    }

    public FarmService getFarm() {
        return this.retrofit.create(FarmService.class);
    }

    public FarmService getFarmList() {
        return this.retrofit.create(FarmService.class);
    }
}

Body:
I have tested with mocky.io http://www.mocky.io/v2/5ed4f4b23300006500f7a5e0.
and it's working fine, seems your header created a problem. Make your API call like below

@Headers("Content-Type: application/json")
@GET("farms/abstract")
Call<Farm> getFarmList();

And create a Function for Auth In your RetrofitConfig like below

 public static Retrofit createServiceWithAuth(Context mContext,String token) {

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new AuthorizationInterceptor(token))
                .build();

        this.retrofit = new Retrofit.Builder()
                .baseUrl("API_URL")
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();

        return  this.retrofit;
    }

Add this Class

public class AuthorizationInterceptor implements Interceptor {

    private String authorizationKey;

    public AuthorizationInterceptor() {

    }

    public AuthorizationInterceptor(String token) {
        this.authorizationKey = token;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        final Request request = chain.request().newBuilder()
                .addHeader("token",authorizationKey)
                .build();

        return chain.proceed(request);
    }

    public String getAuthorizationKey() {
        return authorizationKey;
    }

    public void setAuthorizationKey(String authorizationKey) {
        this.authorizationKey = authorizationKey;
    }


问:
Load items from API in reverse order
I have a react native app that is retrieving APIs.

However, instead of retrieving from item[0] to item[93], I wanted to reverse it so that it presents the data from item[93] at the top, followed by item[92], etc.

Hence, I tried to include this in my flatlist:

```<code>inverted={true}
</code>```

However, in doing so, when i load the app, it will still load from [0], but keep including the next items above it over and over.

How do I also load the info from item[93] to item[0]?

Thanks so much!

My flatlist looks like that:

```<code>return (
      <View style={styles.background}>
        <FlatList
          data={this.state.dataSource}
          keyExtractor={this._keyExtractor}
          inverted={true}
          renderItem={({ item }) => (

            <Card>
              <CardItem>
                <View style={styles.container}>
                  <Image style={styles.profilepic}
                    source={{
                      uri: item.links.mission_patch
                      // from API docs
                    }}
                  />
                </View>
                <View style={styles.userinfo}>
                  <Text style={styles.content}>
                    Flight Number: {item.flight_number}
                    Mission Name: {item.mission_name}
                    {item.details}
                  </Text>
                </View>
              </CardItem>
            </Card>
          )}
        />
      </View>
    );
  }
}
</code>```

答:
You can try the Array.reverse() like so:

<FlatList
  data={this.state.dataSource.reverse()}
//
```

Title: Load items from API in reverse order

Body:
I have a react native app that is retrieving APIs.

However, instead of retrieving from item[0] to item[93], I wanted to reverse it so that it presents the data from item[93] at the top, followed by item[92], etc.

Hence, I tried to include this in my flatlist:

inverted={true}

However, in doing so, when i load the app, it will still load from [0], but keep including the next items above it over and over.

How do I also load the info from item[93] to item[0]?

Thanks so much!

My flatlist looks like that:

return (
      <View style={styles.background}>
        <FlatList
          data={this.state.dataSource}
          keyExtractor={this._keyExtractor}
          inverted={true}
          renderItem={({ item }) => (

            <Card>
              <CardItem>
                <View style={styles.container}>
                  <Image style={styles.profilepic}
                    source={{
                      uri: item.links.mission_patch
                      // from API docs
                    }}
                  />
                </View>
                <View style={styles.userinfo}>
                  <Text style={styles.content}>
                    Flight Number: {item.flight_number}
                    Mission Name: {item.mission_name}
                    {item.details}
                  </Text>
                </View>
              </CardItem>
            </Card>
          )}
        />
      </View>
    );
  }
}


问:
Fixing the 'Use of unassigned local variable' with a null assignment. Why?
With a piece of code like this, the compiler complains on c.MyProperty:

```<code>MyClass c;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // "Use of unassigned local variable 'c'".
</code>```

Yet it doesn't complain if you assign a null to c in initialization:

```<code>MyClass c = null;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // no complains this time.
</code>```

So, why does this work?  If c wasn't assigned a null and the compiler hypothetically allowed it, wouldn't the same exception be thrown at c.MyProperty, Object reference not set to an instance of an object?

答:
Think of it this way, the compiler is not telling you that it is going to throw a null reference and therefore it can't compile, but rather that one of the conditions aren't met that are required to compile, i.e. that it has to be definitely assigned.

According to the spec null is a c# literal: "The  null-literal can be implicitly converted to a reference type or nullable type"

As well as in terms of assignments: (taken from the spec)

Start of quote taken from the spec

5.3.3 Precise rules for determining definite assignment
In order to determine that each used variable is definitely assigned, the compiler must use a process that is equivalent to the one described in this section.

The compiler processes the body of each function member that has one or more initially unassigned variables. For each initially unassigned variable v, the compiler determines a definite assignment state for v at each of the following points in the function member:

·         At the beginning of each statement

·         At the end point (§8.1) of each statement

·         On each arc which transfers control to another statement or to the end point of a statement

·         At the beginning of each expression

·         At the end of each expression

End of quote

So even though null is not actually pointing to an object in memory, it does fulfill the requirements of being definitely assigned and that is why the compiler allows it.

Body:
With a piece of code like this, the compiler complains on c.MyProperty:

MyClass c;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // "Use of unassigned local variable 'c'".

Yet it doesn't complain if you assign a null to c in initialization:

MyClass c = null;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // no complains this time.

So, why does this work?  If c wasn't assigned a null and the compiler hypothetically allowed it, wouldn't the same exception be thrown at c.MyProperty, Object reference not set to an instance of an object?


问:
Linux syscalls: PTRACE_O_TRACECLONE causes indefinite hanging
I have a binary from which I need to intercept a certain syscall--in this case unlinkat--and make it do nothing. I have the following code which works fine for a single process; however, with PTRACE_O_TRACECLONE added to the ptrace opts, after the tracee makes a call to clone, the waitpid call hangs forever. I've been pulling my hair out for days on different parts of the internet, to the point where I was going through the source of strace, and had in fact straced strace to see what the strace I had straced was ptracing.

Here's the source--I removed some stuff to make it as minimal as possible for readability.

```<code>#define _POSIX_C_SOURCE 200112L

// std (i think)
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// linux
#include <sys/ptrace.h>
#include <sys/reg.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <unistd.h>

#define OPTS PTRACE_O_TRACESYSGOOD // | PTRACE_O_TRACECLONE | PTRACE_O_TRACEVFORK | PTRACE_O_TRACEFORK
#define WOPTS 0

/* The TRACEE. Executes the process we want to target with PTRACE_TRACEME */
int do_child(int argc, char **argv) {
    char *args[argc + 1];
    memcpy(args, argv, argc * sizeof(char *));
    args[argc] = NULL;

    ptrace(PTRACE_TRACEME);
    kill(getpid(), SIGSTOP);
    return execvp(args[0], args);
}

/* Waits for the next syscall and checks to see if the process has been exited */
int wait_for_syscall(pid_t child) {
    int status;
    while (1) {
        ptrace(PTRACE_SYSCALL, child, 0, 0);
        waitpid(child, &status, WOPTS); // <--- THIS CALL HANGS FOREVER AFTER CLONE
        if (WIFSTOPPED(status) && WSTOPSIG(status) & 0x80)
            return 0;
        if (WIFEXITED(status))
            return 1;
    }
    return -1; // unreachable
}

/* The TRACER. Takes the pid of the child process that we just started and actually does the
    PTRACE stuff by passing signals back and forth to that process. */
int do_trace(pid_t child) {
    int status, syscall;
    waitpid(child, &status, WOPTS);
    ptrace(PTRACE_SETOPTIONS, child, 0, (unsigned long)OPTS);
    while (1) {
        // ptrace(PTRACE_SYSCALL) really needs to be called twice, first is before entry second is after exit, but idgaf
        if (wait_for_syscall(child) != 0) {
            break;
        }
        syscall = ptrace(PTRACE_PEEKUSER, child, sizeof(long) * ORIG_RAX);
        switch (syscall) {
            case SYS_clone:
                fprintf(stderr, "DEBUG: clone detected\n");
                break;
            case SYS_unlinkat:
                fprintf(stderr, "DEBUG: unlinkat detected\n");
                ptrace(PTRACE_POKEUSER, child, sizeof(long) * RAX, 0);
                break;
        }
    }

    return 0;
}

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s prog args\n", argv[0]);
        exit(1);
    }

    pid_t child = fork();
    if (child == 0) {
        return do_child(argc - 1, argv + 1);
    } else {
        return do_trace(child);
    }
    return 0;
}
</code>```

Just as a disclaimer, I am NOT a C developer, these days I mainly write Python, so a lot of this was just copied and pasted from different tutorials I found and I basically added/removed random shit until gcc didn't give me that many warnings.

Based on what I've read, I suspect the issue is something about raising signals to the processes involved and waiting for a SIGTRAP, I just have no real intuition on what to do at that level.

答:
The solution was using libseccomp instead.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <seccomp.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>

int do_child(int argc, char **argv)
{
    char *args[argc + 1];
    memcpy(args, argv, argc * sizeof(char *));
    args[argc] = NULL;

    return execvp(args[0], args);
}

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s prog args\n", argv[0]);
        exit(1);
    }

    // Init the filter
    scmp_filter_ctx ctx;
    ctx = seccomp_init(SCMP_ACT_ALLOW); // default allow

    // setup basic whitelist
    seccomp_rule_add(ctx, SCMP_ACT_ERRNO(0), SCMP_SYS(unlinkat), 0);

    // build and load the filter
    seccomp_load(ctx);

    pid_t child = fork();
    if (child == 0)
    {
        return do_child(argc - 1, argv + 1);
    }

    return 0;
}
</code>```

Body:
I have a binary from which I need to intercept a certain syscall--in this case unlinkat--and make it do nothing. I have the following code which works fine for a single process; however, with PTRACE_O_TRACECLONE added to the ptrace opts, after the tracee makes a call to clone, the waitpid call hangs forever. I've been pulling my hair out for days on different parts of the internet, to the point where I was going through the source of strace, and had in fact straced strace to see what the strace I had straced was ptracing.

Here's the source--I removed some stuff to make it as minimal as possible for readability.

#define _POSIX_C_SOURCE 200112L

// std (i think)
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// linux
#include <sys/ptrace.h>
#include <sys/reg.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <unistd.h>

#define OPTS PTRACE_O_TRACESYSGOOD // | PTRACE_O_TRACECLONE | PTRACE_O_TRACEVFORK | PTRACE_O_TRACEFORK
#define WOPTS 0

/* The TRACEE. Executes the process we want to target with PTRACE_TRACEME */
int do_child(int argc, char **argv) {
    char *args[argc + 1];
    memcpy(args, argv, argc * sizeof(char *));
    args[argc] = NULL;

    ptrace(PTRACE_TRACEME);
    kill(getpid(), SIGSTOP);
    return execvp(args[0], args);
}

/* Waits for the next syscall and checks to see if the process has been exited */
int wait_for_syscall(pid_t child) {
    int status;
    while (1) {
        ptrace(PTRACE_SYSCALL, child, 0, 0);
        waitpid(child, &status, WOPTS); // <--- THIS CALL HANGS FOREVER AFTER CLONE
        if (WIFSTOPPED(status) && WSTOPSIG(status) & 0x80)
            return 0;
        if (WIFEXITED(status))
            return 1;
    }
    return -1; // unreachable
}

/* The TRACER. Takes the pid of the child process that we just started and actually does the
    PTRACE stuff by passing signals back and forth to that process. */
int do_trace(pid_t child) {
    int status, syscall;
    waitpid(child, &status, WOPTS);
    ptrace(PTRACE_SETOPTIONS, child, 0, (unsigned long)OPTS);
    while (1) {
        // ptrace(PTRACE_SYSCALL) really needs to be called twice, first is before entry second is after exit, but idgaf
        if (wait_for_syscall(child) != 0) {
            break;
        }
        syscall = ptrace(PTRACE_PEEKUSER, child, sizeof(long) * ORIG_RAX);
        switch (syscall) {
            case SYS_clone:
                fprintf(stderr, "DEBUG: clone detected\n");
                break;
            case SYS_unlinkat:
                fprintf(stderr, "DEBUG: unlinkat detected\n");
                ptrace(PTRACE_POKEUSER, child, sizeof(long) * RAX, 0);
                break;
        }
    }

    return 0;
}

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s prog args\n", argv[0]);
        exit(1);
    }

    pid_t child = fork();
    if (child == 0) {
        return do_child(argc - 1, argv + 1);
    } else {
        return do_trace(child);
    }
    return 0;
}

Just as a disclaimer, I am NOT a C developer, these days I mainly write Python, so a lot of this was just copied and pasted from different tutorials I found and I basically added/removed random shit until gcc didn't give me that many warnings.

Based on what I've read, I suspect the issue is something about raising signals to the processes involved and waiting for a SIGTRAP, I just have no real intuition on what to do at that level.

Body:
The solution was using libseccomp instead.

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <seccomp.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>

int do_child(int argc, char **argv)
{
    char *args[argc + 1];
    memcpy(args, argv, argc * sizeof(char *));
    args[argc] = NULL;

    return execvp(args[0], args);
}

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s prog args\n", argv[0]);
        exit(1);
    }

    // Init the filter
    scmp_filter_ctx ctx;
    ctx = seccomp_init(SCMP_ACT_ALLOW); // default allow

    // setup basic whitelist
    seccomp_rule_add(ctx, SCMP_ACT_ERRNO(0), SCMP_SYS(unlinkat), 0);

    // build and load the filter
    seccomp_load(ctx);

    pid_t child = fork();
    if (child == 0)
    {
        return do_child(argc - 1, argv + 1);
    }

    return 0;
}


问:
Recover docker container's run arguments
I often find myself in need of re-creating container with minor modifications to arguments used to docker run container originally (things like changing published ports, network, memory amount).

Now I am making images and running them in place of old containers.

This works fine but I don't always have original params to docker run saved and sometimes (esp. when there are lot of things to define) it becomes pain to recover them.

Is there any way to recover docker run arguments from existing container?

答:
Sorry for being a couple of years late, but I had a similar question and no satisfying answer yet, so I still needed to find my way out.

I've found two sources addressing the issue:

A gist

To run, save this to a file, e.g. run.tpl and do docker inspect --format "$(<run.tpl)" name_or_id_of_running_container

A docker image

Quick run:
$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock nexdrew/rekcod <container>

Both solutions are quite simple to use, but the second one failed to generate the command for an Nginx container because they did not manage to have it quoted like this "nginx" "-g" "daemon off;"

So, I focused on the first solution, which is a golang template intended to feed the --format parameter of docker inspect. I liked it because it was kind of simple, elegant, and no other tool needed.

I've made some improvements in my forked gist and notified the original author about it.


问:
How to run a python script in django server using a button
I want to run my script (makes changes to my database and creates users on another website using an API) whenever a user presses the button on my website. So far i have tried these solutions but they are not working for me.

How can i trigger a Python script in background from HTML tag button, in Django?

Run python script in Django website when clicking on button submit

The view

```<code>def external(request):
    out = run([sys.executable, 'C:\\Users\\hafiz\\PycharmProjects\\DotsPrototype\\proto\\moodle.py'], shell=False, stdout=PIPE)
    print(out.stdout)
    return render(request, 'proto/index.html', {'data1': out.stdout})

The error

  return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'DotsPrototype'
b''
.
.
.
/external/vendor/jquery/jquery.min.js
</code>```

答: You need to create a view that will handle the POST request on button click. The view will have the logic to call your script. Not sure if you creating REST APIs or a monolithic application. In both the cases, the approach remains the same.</p>

Body:
I want to run my script (makes changes to my database and creates users on another website using an API) whenever a user presses the button on my website. So far i have tried these solutions but they are not working for me.

How can i trigger a Python script in background from HTML tag button, in Django?

Run python script in Django website when clicking on button submit

The view

def external(request):
    out = run([sys.executable, 'C:\\Users\\hafiz\\PycharmProjects\\DotsPrototype\\proto\\moodle.py'], shell=False, stdout=PIPE)
    print(out.stdout)
    return render(request, 'proto/index.html', {'data1': out.stdout})

The error

  return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'DotsPrototype'
b''
.
.
.
/external/vendor/jquery/jquery.min.js


问:
Firebase Authentication handler doesn't get called
I am trying to authenticate users through Firebase and use their assigned userIDs to store profile pictures. Here in the code I have assigned userID with default nil in the beginning of class, and am reassigning to fetched result after a user is created. However, when I try to access userID from a few lines below I get a nil exception, that is the userID never got changed. After debugging I realized that this is because the handler never gets called, however I have no idea why. Any help is appreciated.

答:
Maybe you are not keeping the reference for the auth object and this is why your call back closure is not being called. It's hard to check why is not being called without more context, but maybe you could give it a try.

class YourCalss {
  private let auth = Auth.auth()

  func yourMethod() {
    auth.createUser(withEmail: ..., password: ...)
  }
}
```

Give it a shot. I hope this could somehow helpful :)

Body:
Maybe you are not keeping the reference for the auth object and this is why your call back closure is not being called. It's hard to check why is not being called without more context, but maybe you could give it a try.

class YourCalss {
  private let auth = Auth.auth()

  func yourMethod() {
    auth.createUser(withEmail: ..., password: ...)
  }
}

Give it a shot. I hope this could somehow helpful :)


问:
Regex expression to fetch correct value in python
I have below repeated pattern of data in a text file(info.txt). I need to read only 5 components from each block

SENDER

RECEIVER

OBJ_CLASS

JOBN_PAR

CONVTAB

```<code>SENDER=DEMO RECEIVER=REC OBJ_CLASS=message
  JOBN_PAR=JOB.NAME "ROLLBACK=NO" "CONVTAB=message_to_convert_document.cfg" "REST=NO"
  EVN_TYPE=USER
  JOB_SEQU=N
  JOB_PRIO=0
  TIME_WINDOW=
  HC_DIRECTION=1
  POP_ENABLE=Y
</code>```

I have written below python code to read the above pattern of data, It reads all the values until 2nd Line and attaches the values to JOBN_PAR and CONVTAB, while I want only value corresponding to the CONVTAB="" and JOBN_PAR="" in my output

```<code>import re
with open("info.txt", "r") as f:
    s = f.read().replace('"','')

field_labels = [
                'SENDER',
                'RECEIVER',
                'OBJ_CLASS',
                'JOBN_PAR',
                'CONVTAB'
                ]

pat = '=(.*)\s*'.join(field_labels) + '=(.*)\s'
pat = re.compile(pat)

print(pat)
data = pat.findall(s)
print(data)
</code>```

Outcome

[('DEMO ', 'REC ', 'message', 'JOB.NAME ROLLBACK=NO ',
  'message_to_convert_document.cfg  REST=NO')]

Expected Output
[('DEMO ', 'REC ', 'message', 'JOB.NAME', 'message_to_convert_document.cfg')]

答:
Using lambda expression generate regex string and then compile it as below.
Its giving correct output</p>

```<code>pattern = '.*?'.join(list(map(lambda x: '(?:' + x + r'=(.*?)\s+)', field_labels)))
patternReg = re.compile(pattern, re.DOTALL)
</code>```

Body:
I have below repeated pattern of data in a text file(info.txt). I need to read only 5 components from each block

SENDER

RECEIVER

OBJ_CLASS

JOBN_PAR

CONVTAB

SENDER=DEMO RECEIVER=REC OBJ_CLASS=message
  JOBN_PAR=JOB.NAME "ROLLBACK=NO" "CONVTAB=message_to_convert_document.cfg" "REST=NO"
  EVN_TYPE=USER
  JOB_SEQU=N
  JOB_PRIO=0
  TIME_WINDOW=
  HC_DIRECTION=1
  POP_ENABLE=Y

I have written below python code to read the above pattern of data, It reads all the values until 2nd Line and attaches the values to JOBN_PAR and CONVTAB, while I want only value corresponding to the CONVTAB="" and JOBN_PAR="" in my output

import re
with open("info.txt", "r") as f:
    s = f.read().replace('"','')

field_labels = [
                'SENDER',
                'RECEIVER',
                'OBJ_CLASS',
                'JOBN_PAR',
                'CONVTAB'
                ]

pat = '=(.*)\s*'.join(field_labels) + '=(.*)\s'
pat = re.compile(pat)

print(pat)
data = pat.findall(s)
print(data)

Outcome

[('DEMO ', 'REC ', 'message', 'JOB.NAME ROLLBACK=NO ',
  'message_to_convert_document.cfg  REST=NO')]

Expected Output
[('DEMO ', 'REC ', 'message', 'JOB.NAME', 'message_to_convert_document.cfg')]

Body:
Using lambda expression generate regex string and then compile it as below.
Its giving correct output

pattern = '.*?'.join(list(map(lambda x: '(?:' + x + r'=(.*?)\s+)', field_labels)))
patternReg = re.compile(pattern, re.DOTALL)


问:
Compiling C/C++ in VS Code
I'm trying to compile C/C++ code in VS Code using cl (installed via visual studio 2019). I've set up the json files like the MS website suggests,

https://code.visualstudio.com/docs/cpp/config-msvc,

but I still get the error:

```<code>cl.exe : The term 'cl.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
</code>```

Here are my json files:

```<code>{
"configurations": [
    {
        "name": "Win32",
        "includePath": [
            "${workspaceFolder}/**"
        ],
        "defines": [
            "_DEBUG",
            "UNICODE",
            "_UNICODE"
        ],
        "windowsSdkVersion": "10.0.17763.0",
        "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.21.27702/bin/Hostx64/x64/cl.exe",
        "cStandard": "c11",
        "cppStandard": "c++17",
        "intelliSenseMode": "msvc-x64"
    }
],
"version": 4
</code>```

}

```<code>{
"version": "2.0.0",
"tasks": [
    {
        "label": "msvc build",
        "type": "shell",
        "command": "cl.exe",
        "args": [
            "/EHsc",
            "/Zi",
            "/Fe:",
            "helloworld.exe",
            "test.c"
        ],
        "group":  {
            "kind": "build",
            "isDefault": true
        },
        "presentation": {
            "reveal":"always"
        },
        "problemMatcher": "$msCompile"
    }
]
</code>```

}

答:
What worked for me:

Following this guide, I made this change in task.json:

```<code>{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "cl.exe build active file",
            "command": "build.bat", //calling build.bat instead
            "args": [
                "/Zi",
                "/EHsc",
                "/Fe:",
                "${fileDirname}\\${fileBasenameNoExtension}.exe",
                "${file}"
            ],
            "problemMatcher": [
                "$msCompile"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}
</code>```

Then my build.bat (sDevCmd.bat is called when the developer terminal is opened):

```<code>call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Tools\VsDevCmd.bat"
echo Building...
cl.exe %*
</code>```

Then Ctrl + Shift + B.

Title: Compiling C/C++ in VS Code

Body:
I'm trying to compile C/C++ code in VS Code using cl (installed via visual studio 2019). I've set up the json files like the MS website suggests,

https://code.visualstudio.com/docs/cpp/config-msvc,

but I still get the error:

cl.exe : The term 'cl.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Here are my json files:

{
"configurations": [
    {
        "name": "Win32",
        "includePath": [
            "${workspaceFolder}/**"
        ],
        "defines": [
            "_DEBUG",
            "UNICODE",
            "_UNICODE"
        ],
        "windowsSdkVersion": "10.0.17763.0",
        "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.21.27702/bin/Hostx64/x64/cl.exe",
        "cStandard": "c11",
        "cppStandard": "c++17",
        "intelliSenseMode": "msvc-x64"
    }
],
"version": 4

}

{
"version": "2.0.0",
"tasks": [
    {
        "label": "msvc build",
        "type": "shell",
        "command": "cl.exe",
        "args": [
            "/EHsc",
            "/Zi",
            "/Fe:",
            "helloworld.exe",
            "test.c"
        ],
        "group":  {
            "kind": "build",
            "isDefault": true
        },
        "presentation": {
            "reveal":"always"
        },
        "problemMatcher": "$msCompile"
    }
]

}

Body:
What worked for me:

Following this guide, I made this change in task.json:

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "cl.exe build active file",
            "command": "build.bat", //calling build.bat instead
            "args": [
                "/Zi",
                "/EHsc",
                "/Fe:",
                "${fileDirname}\\${fileBasenameNoExtension}.exe",
                "${file}"
            ],
            "problemMatcher": [
                "$msCompile"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Then my build.bat (sDevCmd.bat is called when the developer terminal is opened):

call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Tools\VsDevCmd.bat"
echo Building...
cl.exe %*

Then Ctrl + Shift + B.


问:
Heroku giving H10 error with npx create-react-app
I am creating a react app using npx create-react-app, however, no matter what I do, heroku gives me an H10 error back. Is there a way to get a more detailed error message? And how do I get the app up and running? Here is my package.json file.

```<code>{
  "name": "portfolio",
  "version": "0.1.0",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "DONTEXECUTEbuild": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "engines": {
    "node": "12.16.1"
  }
}
</code>```

And this is my Procfile

```<code>web:npm start
</code>```

Edit 1:

I tried running heroku restart and installing https://github.com/mars/create-react-app-buildpack.git buildpack.

Edit 2:
This is the error message I get:

```<code>2020-04-12T10:12:16.885382+00:00 heroku[web.1]: State changed from crashed to starting
2020-04-12T10:12:27.041455+00:00 app[web.1]:
2020-04-12T10:12:27.041478+00:00 app[web.1]: > portfolio@0.1.0 start /app
2020-04-12T10:12:27.041478+00:00 app[web.1]: > react-scripts start
2020-04-12T10:12:27.041478+00:00 app[web.1]:
2020-04-12T10:12:29.005933+00:00 app[web.1]: ℹ ｢wds｣: Project is running at http://172.18.174.102/
2020-04-12T10:12:29.006390+00:00 app[web.1]: ℹ ｢wds｣: webpack output is served from
2020-04-12T10:12:29.006491+00:00 app[web.1]: ℹ ｢wds｣: Content not from webpack is served from /app/public
2020-04-12T10:12:29.006574+00:00 app[web.1]: ℹ ｢wds｣: 404s will fallback to /
2020-04-12T10:12:29.006803+00:00 app[web.1]: Starting the development server...
2020-04-12T10:12:29.006804+00:00 app[web.1]:
2020-04-12T10:12:29.112722+00:00 heroku[web.1]: State changed from starting to crashed
</code>```

答:
Try changing the version of React in package.json. I changed react version to 16.12.0,
react-dom to 16.12.0, react-router-dom to 5.1.2 and react scripts to 3.2.0.. It worked fine afterwards. Another option is to change create react app webpack config in heroku settings.</p>

Body:
I am creating a react app using npx create-react-app, however, no matter what I do, heroku gives me an H10 error back. Is there a way to get a more detailed error message? And how do I get the app up and running? Here is my package.json file.

{
  "name": "portfolio",
  "version": "0.1.0",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "DONTEXECUTEbuild": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "engines": {
    "node": "12.16.1"
  }
}

And this is my Procfile

web:npm start

Edit 1:

I tried running heroku restart and installing https://github.com/mars/create-react-app-buildpack.git buildpack.

Edit 2:
This is the error message I get:

2020-04-12T10:12:16.885382+00:00 heroku[web.1]: State changed from crashed to starting
2020-04-12T10:12:27.041455+00:00 app[web.1]:
2020-04-12T10:12:27.041478+00:00 app[web.1]: > portfolio@0.1.0 start /app
2020-04-12T10:12:27.041478+00:00 app[web.1]: > react-scripts start
2020-04-12T10:12:27.041478+00:00 app[web.1]:
2020-04-12T10:12:29.005933+00:00 app[web.1]: ℹ ｢wds｣: Project is running at http://172.18.174.102/
2020-04-12T10:12:29.006390+00:00 app[web.1]: ℹ ｢wds｣: webpack output is served from
2020-04-12T10:12:29.006491+00:00 app[web.1]: ℹ ｢wds｣: Content not from webpack is served from /app/public
2020-04-12T10:12:29.006574+00:00 app[web.1]: ℹ ｢wds｣: 404s will fallback to /
2020-04-12T10:12:29.006803+00:00 app[web.1]: Starting the development server...
2020-04-12T10:12:29.006804+00:00 app[web.1]:
2020-04-12T10:12:29.112722+00:00 heroku[web.1]: State changed from starting to crashed


问:
ASP - how to remove single quote from user input text
```<code>answer  = Request.Form("Text" & i)
</code>```

In a form a user inputs random text which is inserted into a database. Currently if the user puts in single quotes it creates an error. How do i remove just single quotes' from the users answer?

答:
' are escaped by doubling, i.e replacing ' with 2 x ' for example "Ralph''s".

However you are far better off using parametrized statements with command objects which will take care of that for you.

Body:
answer  = Request.Form("Text" & i)

In a form a user inputs random text which is inserted into a database. Currently if the user puts in single quotes it creates an error. How do i remove just single quotes' from the users answer?


问:
How to get params in react hooks component?
For class component there is "this.props.route.params" option. How to get params from one screen to other screen in react hook functional component.</p>

```<code>"react": "16.11.0",
"react-native": "0.62.2",
"react-navigation": "@react-navigation/native": "^5.1.2",
</code>```

答:
You can use:

If the component is in a navigation stack use:

const myParam = props.route.params?.param_name

```
<p>Otherwise:</p>
<pre class="lang-js prettyprint-override"><code>
import { useRoute } from "@react-navigation/native";
//
//
const route = useRoute()

const myParam = route.params?.param_name

</code>```

The ? is for security. If params is undefined it won't crash.

Body:
For class component there is "this.props.route.params" option. How to get params from one screen to other screen in react hook functional component.

"react": "16.11.0",
"react-native": "0.62.2",
"react-navigation": "@react-navigation/native": "^5.1.2",

Body:
You can use:

If the component is in a navigation stack use:

const myParam = props.route.params?.param_name

Otherwise:

import { useRoute } from "@react-navigation/native";
//
//
const route = useRoute()

const myParam = route.params?.param_name

The ? is for security. If params is undefined it won't crash.


问:
Paragraph mark of UWP RichEditBox is not resized
With this code (Editor.Document.Selection.CharacterFormat.Size = 20;) I change the font size of a UWP RichEditBox in the Page_Loaded-handle. When I start typing some characters, everything works fine. But when I select the paragraph mark and then type something, this text appears in the wrong font size (10.5).

What I've tried is to expand the selection before setting the font size, but it seems that there is no paragraph mark when there's no text. But when the rich edit box is empty and I press Shift+Right Arrow ⟶ (as I would normally select the paragraph mark), the font size is set back to 10.5.

Is there any workaround to prevent that the font size is set back to 10.5 in any case?

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock x:Name="FontSizeBlock" Grid.Row="0"></TextBlock>
    <RichEditBox x:Name="Editor" Grid.Row="1" SelectionChanged="HandleRichEditBox_SelectionChanged"></RichEditBox>
</Grid>

public sealed partial class MainPage : Page {
    public MainPage() {
        this.InitializeComponent();
        this.Loaded += Page_Loaded;
    }

    private void Page_Loaded(object sender, RoutedEventArgs e) {
        Editor.Document.Selection.SetRange(0, 1);
        Editor.Document.Selection.CharacterFormat.Size = 20;
    }

    private void HandleRichEditBox_SelectionChanged(object sender, RoutedEventArgs e) {
        FontSizeBlock.Text = "FontSize: " + Editor.Document.Selection.CharacterFormat.Size;
    }
}
</code>```

答:
Is there any workaround to prevent that the font size is set back to 10.5 in any case?

For your requirement, you could force font size to 20 when you  press Shift+Right. Please refer the following code.

```<code>private void HandleRichEditBox_SelectionChanged(object sender, RoutedEventArgs e)
{
    FontSizeBlock.Text = "FontSize: " + Editor.Document.Selection.CharacterFormat.Size;
    if (Editor.Document.Selection.CharacterFormat.Size == 10.5)
    {
        Editor.Document.Selection.SetRange(0, 1);
        Editor.Document.Selection.CharacterFormat.Size = 20;
    }
}
</code>```

Body:
With this code (Editor.Document.Selection.CharacterFormat.Size = 20;) I change the font size of a UWP RichEditBox in the Page_Loaded-handle. When I start typing some characters, everything works fine. But when I select the paragraph mark and then type something, this text appears in the wrong font size (10.5).

What I've tried is to expand the selection before setting the font size, but it seems that there is no paragraph mark when there's no text. But when the rich edit box is empty and I press Shift+Right Arrow ⟶ (as I would normally select the paragraph mark), the font size is set back to 10.5.

Is there any workaround to prevent that the font size is set back to 10.5 in any case?

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock x:Name="FontSizeBlock" Grid.Row="0"></TextBlock>
    <RichEditBox x:Name="Editor" Grid.Row="1" SelectionChanged="HandleRichEditBox_SelectionChanged"></RichEditBox>
</Grid>

public sealed partial class MainPage : Page {
    public MainPage() {
        this.InitializeComponent();
        this.Loaded += Page_Loaded;
    }

    private void Page_Loaded(object sender, RoutedEventArgs e) {
        Editor.Document.Selection.SetRange(0, 1);
        Editor.Document.Selection.CharacterFormat.Size = 20;
    }

    private void HandleRichEditBox_SelectionChanged(object sender, RoutedEventArgs e) {
        FontSizeBlock.Text = "FontSize: " + Editor.Document.Selection.CharacterFormat.Size;
    }
}

Body:
Is there any workaround to prevent that the font size is set back to 10.5 in any case?

For your requirement, you could force font size to 20 when you  press Shift+Right. Please refer the following code.

private void HandleRichEditBox_SelectionChanged(object sender, RoutedEventArgs e)
{
    FontSizeBlock.Text = "FontSize: " + Editor.Document.Selection.CharacterFormat.Size;
    if (Editor.Document.Selection.CharacterFormat.Size == 10.5)
    {
        Editor.Document.Selection.SetRange(0, 1);
        Editor.Document.Selection.CharacterFormat.Size = 20;
    }
}


问:
Compare the first word of a page title to an array in Javascript
the following code gets the page title, compares it with data in array and outputs me a final value

```<code>var title = (document.title);

//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    var varindex = array.indexOf(variable)
    return array[varindex+2]
}
//calling the function
testfunction(testarray, title)

var finalvalue = testfunction(testarray, title);
</code>```

So if my page title is Blue, it gives me the value 110 that is what I need.
It works fine but in this way the only valid title for my page has to be Blue, otherwise it won't work.

I would like to be able to have a longer page title like Blue Shoes .  I tried by adding the following variable at the beginning to get only the title first word

```<code>var fulltitle = (document.title);
var title = fulltitle.split(' ').slice(0,1);
</code>```

but it doesn't work. What is wrong with my code ?
thanks

答:
I'm not sure that I understand you right, but there can be one problem. Title and value in the array can start from Uppercase or Lower case. try to do something like this.</p>

```<code>var title = (document.title);

//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    // CHANGES HERE
    var varindex = array.indexOf(variable.toLocaleLowerCase())
    return array[varindex+2]
}
//calling the function
testfunction(testarray, title)

var finalvalue = testfunction(testarray, title);
</code>```

Body:
the following code gets the page title, compares it with data in array and outputs me a final value

var title = (document.title);

//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    var varindex = array.indexOf(variable)
    return array[varindex+2]
}
//calling the function
testfunction(testarray, title)

var finalvalue = testfunction(testarray, title);

So if my page title is Blue, it gives me the value 110 that is what I need.
It works fine but in this way the only valid title for my page has to be Blue, otherwise it won't work.

I would like to be able to have a longer page title like Blue Shoes .  I tried by adding the following variable at the beginning to get only the title first word

var fulltitle = (document.title);
var title = fulltitle.split(' ').slice(0,1);

but it doesn't work. What is wrong with my code ?
thanks

Body:
I'm not sure that I understand you right, but there can be one problem. Title and value in the array can start from Uppercase or Lower case. try to do something like this.

var title = (document.title);

//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    // CHANGES HERE
    var varindex = array.indexOf(variable.toLocaleLowerCase())
    return array[varindex+2]
}
//calling the function
testfunction(testarray, title)

var finalvalue = testfunction(testarray, title);


问:
Is there anyway to connect IBM RTC and Spring tool suite 4 IDE?
I have IBM eclipse to load code from RTC, but i'm comfortable with working in STS. If there is any plugin to connect IBM RTC from STS would be great to commit code. I tried all the way, it all suggests for Eclipse IDE. Anyone has any idea about this ?</p>

答:
You best bet would be to take a generic Eclipse and add:

the RTC Eclipse Client Add-Ons

the Spring Tools 4 plugin (as described here)

And see if both can cohabit.


问:
How to split csv data by value
im in a situation where i have to plot this csv data like below.

```<code>"x1","x2","y"
-0.626453810742332,0.409401839650934,-1
0.183643324222082,1.68887328620405,1
-0.835628612410047,1.58658843344197,-1
</code>```

And the information of the label y should be expressed in the form of color.

I tried coding like this.

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

df = pd.read_csv("data.csv")

df['x'] = df['x1'] + df['x2']

for value in df['y']:
    if value == 1:
        df['y1'] = df['y']
    else:
        df['y-1'] = df['y']
print(df['y1'])

plt.figure()
plt.scatter(df['x'], df['y1'], c='red')
plt.figure()
plt.scatter(df['x'], df['y-1'], c='blue')
plt.show()
</code>```

but this didn't give me what i wanted.
and i ran print(df['y1']) to see what went wrong and the result is

```<code>0     -1
1      1
2     -1
3      1
4     -1
.
.
.
</code>```

i splitted by value 1 or -1 but still mixed. how can i split this by value 1 or -1?

答:
You can use seaborn:

```<code>import seaborn as sns

sns.scatterplot(data=df, x='x1', y='x2', hue='y')
</code>```

Or you can use groupby:

```<code>fig, ax = plt.subplots()
for k,d in df.groupby('y'):

    d.plot.scatter(x='x1',y='x2', label=k)
</code>```

Title: How to split csv data by value

Body:
im in a situation where i have to plot this csv data like below.

"x1","x2","y"
-0.626453810742332,0.409401839650934,-1
0.183643324222082,1.68887328620405,1
-0.835628612410047,1.58658843344197,-1

And the information of the label y should be expressed in the form of color.

I tried coding like this.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("data.csv")

df['x'] = df['x1'] + df['x2']

for value in df['y']:
    if value == 1:
        df['y1'] = df['y']
    else:
        df['y-1'] = df['y']
print(df['y1'])

plt.figure()
plt.scatter(df['x'], df['y1'], c='red')
plt.figure()
plt.scatter(df['x'], df['y-1'], c='blue')
plt.show()

but this didn't give me what i wanted.
and i ran print(df['y1']) to see what went wrong and the result is

0     -1
1      1
2     -1
3      1
4     -1
.
.
.

i splitted by value 1 or -1 but still mixed. how can i split this by value 1 or -1?

Body:
You can use seaborn:

import seaborn as sns

sns.scatterplot(data=df, x='x1', y='x2', hue='y')

Or you can use groupby:

fig, ax = plt.subplots()
for k,d in df.groupby('y'):

    d.plot.scatter(x='x1',y='x2', label=k)


问:
Accessing object values within array within object
I'm trying to process data from the OpenWeather API for multiple cities. This is what the data looks like:

```<code>{
"cnt":20,
"list":[
    {
    "coord":{"lon":-99.13,"lat":19.43},
    "sys":{"country":"MX","timezone":-18000,"sunrise":1591012665,"sunset":1591060290},
    "weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],
    "main":{"temp":12.88,"feels_like":11.84,"temp_min":12.78,"temp_max":13,"pressure":1027,"humidity":82},
    "visibility":8047,
    "wind":{"speed":1.5,"deg":60},
    "clouds":{"all":20},
    "dt":1591013691,
    "id":3530597,
    "name":"Mexico City"},
    {...next cities...}
    ]
}
</code>```

I'm fine with everything, except the weather part(3rd line). I want to assign each value to a separate variable like so:

```<code>weatherid = 801
main = "Clouds"
description = "few clouds"
</code>```

I've tried stuff around the lines of

```<code>main = citydata.list[i].weather.main;       (doesn't work)
main = citydata.list[i].weather.main();     (doesn't work)
main = Object.values(citydata.list[i].weather);
</code>```

and quite a few things in between.

(Well, the last one kinda does something but I don't end up with something different, and when I try and get the values it's always "undefined")

So, what's the simplest way of accessing that data and storing each part of it in its own variable.
Or even just converting the contents of "main" into an array (I'm assuming those questions overlap)

Thanks!

答:
try that:</p>

```<code> const data =  JSON.parse(req.data);
 const main = data.list[0].weather.main
</code>```

Body:
I'm trying to process data from the OpenWeather API for multiple cities. This is what the data looks like:

{
"cnt":20,
"list":[
    {
    "coord":{"lon":-99.13,"lat":19.43},
    "sys":{"country":"MX","timezone":-18000,"sunrise":1591012665,"sunset":1591060290},
    "weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],
    "main":{"temp":12.88,"feels_like":11.84,"temp_min":12.78,"temp_max":13,"pressure":1027,"humidity":82},
    "visibility":8047,
    "wind":{"speed":1.5,"deg":60},
    "clouds":{"all":20},
    "dt":1591013691,
    "id":3530597,
    "name":"Mexico City"},
    {...next cities...}
    ]
}

I'm fine with everything, except the weather part(3rd line). I want to assign each value to a separate variable like so:

weatherid = 801
main = "Clouds"
description = "few clouds"

I've tried stuff around the lines of

main = citydata.list[i].weather.main;       (doesn't work)
main = citydata.list[i].weather.main();     (doesn't work)
main = Object.values(citydata.list[i].weather);

and quite a few things in between.

(Well, the last one kinda does something but I don't end up with something different, and when I try and get the values it's always "undefined")

So, what's the simplest way of accessing that data and storing each part of it in its own variable.
Or even just converting the contents of "main" into an array (I'm assuming those questions overlap)

Thanks!

Body:
try that:

 const data =  JSON.parse(req.data);
 const main = data.list[0].weather.main


答:
This is because the C# Language specification v. 4.0 section 1.6.6.2 "Method body and local variables" states the following:

A method body can declare variables that are specific to the invocation of the method. Such variables are called local variables.

[skipped]

C# requires a local variable to be definitely assigned before its value can be obtained.

This is to avoid letting you to shoot yourself in the foot, as Binary Worrier neatly pointed out.

Title: Fixing the 'Use of unassigned local variable' with a null assignment. Why?

Body:
With a piece of code like this, the compiler complains on c.MyProperty:

MyClass c;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // "Use of unassigned local variable 'c'".

Yet it doesn't complain if you assign a null to c in initialization:

MyClass c = null;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // no complains this time.

So, why does this work?  If c wasn't assigned a null and the compiler hypothetically allowed it, wouldn't the same exception be thrown at c.MyProperty, Object reference not set to an instance of an object?


问:
Error 404 viewing a BIRT Report in a JSP page in Eclipse
I am trying to run a BIRT report in a JSP, following The BIRT documentation
Almost everything works fine: the report is correctly viewed in preview, but when I try to run the project and to show the report in the JSP I get a 404 error not found.
The web.xml:

```<code>
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="4.0"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
        <display-name>MktPortal</display-name>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
        </welcome-file-list>
        <jsp-config>
            <taglib>
                <taglib-uri>/birt.tld</taglib-uri>
                <taglib-location>/WEB-INF/tlds/birt.tld</taglib-location>
            </taglib>
        </jsp-config>
    </web-app>

</code>```

The viewReport.jsp:

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/birt.tld" prefix="birt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                       "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <birt:viewer id="birtViewer" reportDesign="v_venditedispre.rptdesign"
        pattern="frameset" height="450" width="700" format="html">
    </birt:viewer>
</body>
</html>

</code>```

and this is the error:

答:
The BIRT will require BIRT runtime to render the rptdesign file.
The Taglib which you are using does not contain the runtime itself.

To test it properly just download the BIRT runtime war file and deploy into Web Server and place the rptdesign file into the proper path and then try to render it.

Link for BIRT runtime: http://www.eclipse.org/downloads/download.php?file=/birt/downloads/drops/R-R1-4.8.0-201806261756/birt-runtime-4.8.0-20180626.zip

Once you deploy runtime into the same web server it will start working. Also, it is suggested to keep the reporting separate from the core application code.
This clearly means that create a single directory to store all reports and point the directory to pick the report file.

Body:
I am trying to run a BIRT report in a JSP, following The BIRT documentation
Almost everything works fine: the report is correctly viewed in preview, but when I try to run the project and to show the report in the JSP I get a 404 error not found.
The web.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="4.0"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
        <display-name>MktPortal</display-name>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
        </welcome-file-list>
        <jsp-config>
            <taglib>
                <taglib-uri>/birt.tld</taglib-uri>
                <taglib-location>/WEB-INF/tlds/birt.tld</taglib-location>
            </taglib>
        </jsp-config>
    </web-app>

The viewReport.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/birt.tld" prefix="birt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                       "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

    <birt:viewer id="birtViewer" reportDesign="v_venditedispre.rptdesign"
        pattern="frameset" height="450" width="700" format="html">
    </birt:viewer>

and this is the error:


问:
Stop a thread as soon as possible without having to add "if not running: break" before each line of code?
Context: I've aleady read Is there any way to kill a Thread? and its answers, but here I'm focusing on a possible solution with a function (inside a wrapper?) that would automatically check a flag running before actually running each line of code of the thread target function. Also I have already read Python, Stop a Thread but it does not solve the problem since the flag checking "granularity" is only once every while loop, whereas I'd like it to be at each line of code.

With the following code (simplified for this question):

```<code>import threading, time

def character_loop():
    while running:
        print('character moving left')
        time.sleep(1)
        print('character moving middle')
        time.sleep(1)
        print('character moving right')
        time.sleep(1)

running = True
threading.Thread(target=character_loop).start()
time.sleep(4.5)
running = False     # how to stop *any* movement here?
time.sleep(10)
</code>```

it is in fact doing two full loops, i.e. left/mid/right/left/mid/right, whereas I would like to stop any movement after 4.5 seconds.

How to have left/mid/right/left/<stop here!> instead?

In other words, how to be able to stop a thread as soon as possible? (possibly after each line of code running in the thread target function)

This works:

```<code>def character_loop():
    while running:
        print('character moving left')
        if not running:
            break
        time.sleep(1)
        if not running:
            break
        print('character moving middle')
        if not running:
            break
        time.sleep(1)
        if not running:
            break
        print('character moving right')
        if not running:
            break
        time.sleep(1)
</code>```

but having to add

```<code>if not running:
    break
</code>```

after each line of code in the main loop is really annoying.

I'm sure there's a general threading / scheduling solution for this: how to be able to stop a thread function as soon as possible, ideally after each line of code, and not only when the function comes back to while running:?

PS: in my real code, it's not just print('character moving left') but another function that takes a few milliseconds to seconds to complete depending on the action.

答:
Switch from using threads to asyncio which supports immediate cancellation of tasks. However this could prove to be difficult depending on how the code is structured. You will need an asyncio loop in the main tread to be started. Currently this is done with the asyncio.run() and the main(), but will be different in your implementation.

```<code>import asyncio

async def runner():
    try:
        while True:
            print("left")
            await asyncio.sleep(1)
            print("mid")
            await asyncio.sleep(1)
            print("right")
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        print("Task was canceled")

async def main():
    # In Python 3.7+
    task = asyncio.create_task(runner())
    # This works in all Python versions but is less readable
    # task = asyncio.ensure_future(runner())
    await asyncio.sleep(4.5)
    task.cancel()
    await asyncio.sleep(5)

if __name__ == "__main__":
    asyncio.run(main())
</code>```

Body:
Context: I've aleady read Is there any way to kill a Thread? and its answers, but here I'm focusing on a possible solution with a function (inside a wrapper?) that would automatically check a flag running before actually running each line of code of the thread target function. Also I have already read Python, Stop a Thread but it does not solve the problem since the flag checking "granularity" is only once every while loop, whereas I'd like it to be at each line of code.

With the following code (simplified for this question):

import threading, time

def character_loop():
    while running:
        print('character moving left')
        time.sleep(1)
        print('character moving middle')
        time.sleep(1)
        print('character moving right')
        time.sleep(1)

running = True
threading.Thread(target=character_loop).start()
time.sleep(4.5)
running = False     # how to stop *any* movement here?
time.sleep(10)

it is in fact doing two full loops, i.e. left/mid/right/left/mid/right, whereas I would like to stop any movement after 4.5 seconds.

How to have left/mid/right/left/<stop here!> instead?

In other words, how to be able to stop a thread as soon as possible? (possibly after each line of code running in the thread target function)

This works:

def character_loop():
    while running:
        print('character moving left')
        if not running:
            break
        time.sleep(1)
        if not running:
            break
        print('character moving middle')
        if not running:
            break
        time.sleep(1)
        if not running:
            break
        print('character moving right')
        if not running:
            break
        time.sleep(1)

but having to add

if not running:
    break

after each line of code in the main loop is really annoying.

I'm sure there's a general threading / scheduling solution for this: how to be able to stop a thread function as soon as possible, ideally after each line of code, and not only when the function comes back to while running:?

PS: in my real code, it's not just print('character moving left') but another function that takes a few milliseconds to seconds to complete depending on the action.

Body:
Switch from using threads to asyncio which supports immediate cancellation of tasks. However this could prove to be difficult depending on how the code is structured. You will need an asyncio loop in the main tread to be started. Currently this is done with the asyncio.run() and the main(), but will be different in your implementation.

import asyncio

async def runner():
    try:
        while True:
            print("left")
            await asyncio.sleep(1)
            print("mid")
            await asyncio.sleep(1)
            print("right")
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        print("Task was canceled")

async def main():
    # In Python 3.7+
    task = asyncio.create_task(runner())
    # This works in all Python versions but is less readable
    # task = asyncio.ensure_future(runner())
    await asyncio.sleep(4.5)
    task.cancel()
    await asyncio.sleep(5)

if __name__ == "__main__":
    asyncio.run(main())