问:
Keras ValueError trying to load model
I am using Anaconda Navigator, Jupyter to be precised.

```<code>import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
>>> 1.14.0
</code>```

This is my model

```<code>def create_model():
  model = tf.keras.Sequential([
    keras.layers.Dense(86, activation='relu', kernel_regularizer=keras.regularizers.l2(0.0001),input_shape=(129,)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(142, activation='relu', kernel_regularizer=keras.regularizers.l2(0.0001)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(4, activation='softmax')
    ])
  return model

model = create_model()

# Display the model's architecture
model.summary()
</code>```

After training,predicting and evaluating my model, I decided to save it using

```<code>model.save('/Users/Jennifer/myproject/my_model.h5')
</code>```

I checked the directory and folder with the h5py file. And I decided to load it using

```<code>new_model1 = tf.keras.models.load_model('/Users/Jennifer/myproject/my_model.h5')
</code>```

I got an Error

```<code>ValueError: Unknown entries in loss dictionary: ['class_name', 'config']. Only expected following keys: ['dense_17']
</code>```

Please help me. What should I do? I have almost spent the whole day trying to solve this issue. Thanks

答:
Here is a bit of a work around that just loads the weights:

```<code>#!/usr/bin/env python3

from tensorflow import keras
import os

def create_model():
  model = keras.Sequential([
    keras.layers.Dense(86, activation='relu', kernel_regularizer=keras.regularizers.l2(0.0001),input_shape=(129,)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(142, activation='relu', kernel_regularizer=keras.regularizers.l2(0.0001)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(4, activation='softmax')
    ])
  return model

if os.path.exists("junk.h5"):
    model = create_model()
    model.load_weights("junk.h5")

else:
    model = create_model()
    model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
    model.save("junk.h5")
</code>```

Another workaround would be to save the model without the optimizer

```<code>model.save("junk.h5", include_optimizer=False)
</code>```

It looks like the loss function you're using creates a dictionary that has invalid keys. This sounds like a bug in keras/tensorflow. That is why the colab one probably worked because it was using a newer version.

Title: Keras ValueError trying to load model

Body:
I am using Anaconda Navigator, Jupyter to be precised.

import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
>>> 1.14.0

This is my model

def create_model():
  model = tf.keras.Sequential([
    keras.layers.Dense(86, activation='relu', kernel_regularizer=keras.regularizers.l2(0.0001),input_shape=(129,)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(142, activation='relu', kernel_regularizer=keras.regularizers.l2(0.0001)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(4, activation='softmax')
    ])
  return model

model = create_model()

# Display the model's architecture
model.summary()

After training,predicting and evaluating my model, I decided to save it using

model.save('/Users/Jennifer/myproject/my_model.h5')

I checked the directory and folder with the h5py file. And I decided to load it using

new_model1 = tf.keras.models.load_model('/Users/Jennifer/myproject/my_model.h5')

I got an Error

ValueError: Unknown entries in loss dictionary: ['class_name', 'config']. Only expected following keys: ['dense_17']

Please help me. What should I do? I have almost spent the whole day trying to solve this issue. Thanks

Body:
Here is a bit of a work around that just loads the weights:

#!/usr/bin/env python3

from tensorflow import keras
import os

def create_model():
  model = keras.Sequential([
    keras.layers.Dense(86, activation='relu', kernel_regularizer=keras.regularizers.l2(0.0001),input_shape=(129,)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(142, activation='relu', kernel_regularizer=keras.regularizers.l2(0.0001)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(4, activation='softmax')
    ])
  return model

if os.path.exists("junk.h5"):
    model = create_model()
    model.load_weights("junk.h5")

else:
    model = create_model()
    model.compile(optimizer=keras.optimizers.Adam(0.0001), loss=keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
    model.save("junk.h5")

Another workaround would be to save the model without the optimizer

model.save("junk.h5", include_optimizer=False)

It looks like the loss function you're using creates a dictionary that has invalid keys. This sounds like a bug in keras/tensorflow. That is why the colab one probably worked because it was using a newer version.


来源: stackexchange

问:
Deriving time complexity from runtime analysis
As a non computer scientist I find it a bit hard to understand time complexity and the way it is calculated, So my question is if it is possible for the time complexity of a certain algorithm / program be derived from running it on increasingly large input data, and then look at how runtime changes relative to the  increase in the input size n.

I'm asking this because I wrote an algorithm in C++ which basically does pixel shading on 2D images using  a single cpu core and a single thread (3GHZ processor). I measured the runtime on input sizes from 2^4 up to 2^30 which is a matrix of size  32,768 ** 2. Now I have this plot of how my runtime behaves as a function of my input size n:

So for the input size of n = 2^4 to 2^30 the exact runtimes were(by row):

```<code> [1]  0.000  0.000  0.000  0.000  0.000  0.000  0.000
 [8]  0.000  0.000  0.000  0.000  0.001  0.000  0.000
[15]  0.002  0.004  0.013  0.018  0.053  0.079  0.231
[22]  0.358  0.963  1.772  4.626  9.713 25.582
</code>```

Now this is a bit strange, because when The power of 2 changes from an Odd to an even, the runtime is increased by just 1.5, but when it changes from even to an Odd, the runtime triples.  So, when I double my input, my runtime increases by an average multiple of (3 + 1.5) / 2 = 2.25. In fact, it seems as though when n becomes arbitrarily large, both changes in the power argument from Odd to even and even to Odd cause runtime to be multiplied by a constant of 2.25, in other words: as n becomes larger, the runtime multiplier converges to 2.25.

If my algorithm is quite complex, is there a way to say something about its time complexity from this analysis?

答:
I think it's perfectly reasonable for a lot of algorithms to figure out a curve that fits the data well, and then use the expression for that curve as a working complexity. For this to work well you might want to throw out "small" input sizes for your algorithm and focus on larger ones to minimize the effect of non-asymptotic overhead.

For instance, we can tell it most likely grows faster than quadratic since solving the constants for f(30) and then calculating what we'd expect for f(20) gives a number that is much too large, implying our function asymptotically is growing much faster than quadratically. If we assume an exponential function and solve for the constants at f(30) we get an expected value for f(20) that is much closer to the actual number (though a little lower, so our function might be growing a little more slowly than A*2^n … but we could probably introduce a new factor B to find A*2^(Bn) and get a little closer).

It's not a valid or accepted way to calculate the theoretical asymptotic time complexity of the function whose graph you're looking at, but I think it's fine to say based on this graph your asymptotic complexity is likely exponential with a base around 2.

Actually it looks like your function is doubling values and tripling them alternately. If this is really the case, then you'd expect every two increments in n to yield a six-fold increase; the square root of 6 is about 2.45 so your function really might be an exponential like A*2.45^n, or at least that might give a better fit than using base 2.

ContentLicense: CC BY-SA 4.0

Body:
As a non computer scientist I find it a bit hard to understand time complexity and the way it is calculated, So my question is if it is possible for the time complexity of a certain algorithm / program be derived from running it on increasingly large input data, and then look at how runtime changes relative to the  increase in the input size n.

I'm asking this because I wrote an algorithm in C++ which basically does pixel shading on 2D images using  a single cpu core and a single thread (3GHZ processor). I measured the runtime on input sizes from 2^4 up to 2^30 which is a matrix of size  32,768 ** 2. Now I have this plot of how my runtime behaves as a function of my input size n:

So for the input size of n = 2^4 to 2^30 the exact runtimes were(by row):

 [1]  0.000  0.000  0.000  0.000  0.000  0.000  0.000
 [8]  0.000  0.000  0.000  0.000  0.001  0.000  0.000
[15]  0.002  0.004  0.013  0.018  0.053  0.079  0.231
[22]  0.358  0.963  1.772  4.626  9.713 25.582

Now this is a bit strange, because when The power of 2 changes from an Odd to an even, the runtime is increased by just 1.5, but when it changes from even to an Odd, the runtime triples.  So, when I double my input, my runtime increases by an average multiple of (3 + 1.5) / 2 = 2.25. In fact, it seems as though when n becomes arbitrarily large, both changes in the power argument from Odd to even and even to Odd cause runtime to be multiplied by a constant of 2.25, in other words: as n becomes larger, the runtime multiplier converges to 2.25.

If my algorithm is quite complex, is there a way to say something about its time complexity from this analysis?


问:
How can I add fields to a json file from the fields in the front end in a react application?
I have a config.json file where I have the values for the dropdown on the home page of my application. The values are been populated dynamically, now what i am trying to do is enable the user to add values to the config file from the text fields present in the front end. I am posting a request and have been able to push the values to the config file as well but I am unable to handle the condition where the dropdown values are already present. I have three fields Controller, test and Protocol and I want to apply the logic which is commented in the server side code which I have shown below. Can anyone please help to achieve this logic. Any help is much appreciated.

Regards

Part where help is needed to build the logic.

// We found controller so need to check for test
// if test found nothing to do
// if not found add test
// if test found need to check for protcol
```

答:
In your config.json, Test is an array of elements. Hence d.Test === req.body.test will not yield the intended result. I assume you're trying to check whether req.body.test is present in the Test array, and not if they match.

const { controller, test, protocol } = req.body;
const index = config.controllers.findIndex((c) => c.Name === controller);
if (index === -1) {
    config.controllers.push({
        Name: controller,
        Test: [test],
        Protocol: [protocol],
    });
} else {
    // Check if test exists in Test array...
    if (!config.controllers[index].Test.includes(test)) {
        config.controllers[index].Test.push(test);
    } else {
        // Check if protocol exists in Protocol array...
        if (!config.controllers[index].Protocol.includes(protocol)) {
            config.controllers[index].Protocol.push(protocol);
        }
    }
}

// Rest of your code.
```

BTW, it is a good idea to destructure res.body and the values in variables, will help you write cleaner looking code. Hope this helps!

Body:
In your config.json, Test is an array of elements. Hence d.Test === req.body.test will not yield the intended result. I assume you're trying to check whether req.body.test is present in the Test array, and not if they match.

const { controller, test, protocol } = req.body;
const index = config.controllers.findIndex((c) => c.Name === controller);
if (index === -1) {
    config.controllers.push({
        Name: controller,
        Test: [test],
        Protocol: [protocol],
    });
} else {
    // Check if test exists in Test array...
    if (!config.controllers[index].Test.includes(test)) {
        config.controllers[index].Test.push(test);
    } else {
        // Check if protocol exists in Protocol array...
        if (!config.controllers[index].Protocol.includes(protocol)) {
            config.controllers[index].Protocol.push(protocol);
        }
    }
}

// Rest of your code.

BTW, it is a good idea to destructure res.body and the values in variables, will help you write cleaner looking code. Hope this helps!


问:
Merge a single list of dictionaries with the same key value
I can see many similar questions on here but not one that I can find that helps me get the desired output.

I have a single list of dictionaries that have the same ID but with different key value pairs, id like to join all those key values pairs into a single list entry, below is a sample of data and the desired output.

Thanks for your help

```<code>data = [
    {'id': '10', 'animal' : 'cat'},
    {'id': '11', 'animal' : 'dog'},
    {'id': '3', 'animal' : 'pigeon'},
    {'id': '10', 'color' : 'yellow'},
    {'id': '11', 'color' : 'brown'},
    {'id': '3', 'color' : 'grey'},
    {'id': '10', 'type' : 'furry'},
    {'id': '11', 'type' : 'fluffy'},
    {'id': '3', 'type' : 'dirty'},
]
</code>```

desired output

```<code>data = [
    {'id': '10', 'animal' : 'cat', 'color' : 'yellow', 'type' : 'furry'},
    {'id': '11', 'animal' : 'dog', 'color' : 'brown', 'type' : 'fluffy'},
    {'id': '3', 'animal' : 'pigeon', 'color' : 'grey', 'type' : 'dirty'},
]
</code>```

答:
In Python 3.9 (ETA Fall 2020), you'll be able to use the | operator to merge dicts with the same id key.

```<code>from itertools import groupby
from operator import or_, itemgetter
from functools import reduce

# I know *why* groupby doesn't have an option to
# sort your data first, but that doesn't mean I can't
# wish that it could...
def group(data, key):
    "Iterate over groups of dicts considered equal according to key"
    yield from map(itemgetter(1), groupby(sorted(data, key=key), key))

data = [
    {'id': '10', 'animal' : 'cat'},
    {'id': '11', 'animal' : 'dog'},
    {'id': '3', 'animal' : 'pigeon'},
    {'id': '10', 'color' : 'yellow'},
    {'id': '11', 'color' : 'brown'},
    {'id': '3', 'color' : 'grey'},
    {'id': '10', 'type' : 'furry'},
    {'id': '11', 'type' : 'fluffy'},
    {'id': '3', 'type' : 'dirty'},
    ]

# E.g., {'id': 10, 'animal': 'cat'} | {'id': 10, 'color': 'yellow'}
#  == {'id': 10, 'animal': 'cat', 'color': 'yellow'}
data = [reduce(or_, ds) for ds in group(data, itemgetter('id'))]
</code>```

Body:
I can see many similar questions on here but not one that I can find that helps me get the desired output.

I have a single list of dictionaries that have the same ID but with different key value pairs, id like to join all those key values pairs into a single list entry, below is a sample of data and the desired output.

Thanks for your help

data = [
    {'id': '10', 'animal' : 'cat'},
    {'id': '11', 'animal' : 'dog'},
    {'id': '3', 'animal' : 'pigeon'},
    {'id': '10', 'color' : 'yellow'},
    {'id': '11', 'color' : 'brown'},
    {'id': '3', 'color' : 'grey'},
    {'id': '10', 'type' : 'furry'},
    {'id': '11', 'type' : 'fluffy'},
    {'id': '3', 'type' : 'dirty'},
]

desired output

data = [
    {'id': '10', 'animal' : 'cat', 'color' : 'yellow', 'type' : 'furry'},
    {'id': '11', 'animal' : 'dog', 'color' : 'brown', 'type' : 'fluffy'},
    {'id': '3', 'animal' : 'pigeon', 'color' : 'grey', 'type' : 'dirty'},
]

Body:
In Python 3.9 (ETA Fall 2020), you'll be able to use the | operator to merge dicts with the same id key.

from itertools import groupby
from operator import or_, itemgetter
from functools import reduce

# I know *why* groupby doesn't have an option to
# sort your data first, but that doesn't mean I can't
# wish that it could...
def group(data, key):
    "Iterate over groups of dicts considered equal according to key"
    yield from map(itemgetter(1), groupby(sorted(data, key=key), key))

data = [
    {'id': '10', 'animal' : 'cat'},
    {'id': '11', 'animal' : 'dog'},
    {'id': '3', 'animal' : 'pigeon'},
    {'id': '10', 'color' : 'yellow'},
    {'id': '11', 'color' : 'brown'},
    {'id': '3', 'color' : 'grey'},
    {'id': '10', 'type' : 'furry'},
    {'id': '11', 'type' : 'fluffy'},
    {'id': '3', 'type' : 'dirty'},
    ]

# E.g., {'id': 10, 'animal': 'cat'} | {'id': 10, 'color': 'yellow'}
#  == {'id': 10, 'animal': 'cat', 'color': 'yellow'}
data = [reduce(or_, ds) for ds in group(data, itemgetter('id'))]


问:
How to insert data from html form into database without using HTML POST method?
Hi I would like to know if there is any other way using javascript or something to enter the user input directly to database without using POST method.</p>

答:
whats wrong with with using an Ajax call using jQuery, prototype, or dojo.

An other option is to use flash or silverlight and call a web service

OwnerDisplayName: johnnaples

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Bob The Janitor

ContentLicense: CC BY-SA 3.0


问:
Converting separate month, day and year values into a timestamp
I have a month value (1-12), day value (1-31), and a year value (2010,2011,2012). I also have a hour value and a minute value.

How can I give this to strtotime() in a way it can convert it to a timestamp?

答:
Y-m-d hh:mm will work

```<code>echo strtotime('2011-12-14 11:44 am');
</code>```

cit @Pekka :)

Body:
Y-m-d hh:mm will work

echo strtotime('2011-12-14 11:44 am');

cit @Pekka :)


问:
Laravel - Get records between two dates from second table
I have something like this:

Table 1: Training Name, created_at, user_id (Plan_Treninga)

Table 2: user_id, created_at, expire_at (InvoiceUser)

I want to pull all from Table 1 where created_at is between Table 2 created_at and expire_at.

This is something what i am trying to..

```<code>$plan = Plan_Treninga::whereBetween(function($q) use ($id){
          $inv = InvoiceUser::where([
            ["user_id",$id],
            ["status","paid"],
          ])->latest("id")->first();
        })
</code>```

I haven't finished it yet, but my brain stopped working so I have to ask here.

答:
Take a look at joins https://laravel.com/docs/7.x/queries#joins

I am not saying this is the exact solution but I have something similar that I have changed to point you in the right direction.

With joins you can do lots of things.

```<code>$results = DB::table('table1')
            ->join('table2', function ($join) {
                $join->on('table1.user_id', '=', 'table2.user_id')
                    ->where('table2.status', '=', 'paid')
                    ->where('table2.created_at', '>', 'table1.created_at');
            })
            ->get();
</code>```

Also look at relationships. There is some good answers for setting up many to many relationships.

https://laravel.com/docs/7.x/eloquent-relationships#many-to-many

Body:
I have something like this:

Table 1: Training Name, created_at, user_id (Plan_Treninga)

Table 2: user_id, created_at, expire_at (InvoiceUser)

I want to pull all from Table 1 where created_at is between Table 2 created_at and expire_at.

This is something what i am trying to..

$plan = Plan_Treninga::whereBetween(function($q) use ($id){
          $inv = InvoiceUser::where([
            ["user_id",$id],
            ["status","paid"],
          ])->latest("id")->first();
        })

I haven't finished it yet, but my brain stopped working so I have to ask here.

Body:
Take a look at joins https://laravel.com/docs/7.x/queries#joins

I am not saying this is the exact solution but I have something similar that I have changed to point you in the right direction.

With joins you can do lots of things.

$results = DB::table('table1')
            ->join('table2', function ($join) {
                $join->on('table1.user_id', '=', 'table2.user_id')
                    ->where('table2.status', '=', 'paid')
                    ->where('table2.created_at', '>', 'table1.created_at');
            })
            ->get();

Also look at relationships. There is some good answers for setting up many to many relationships.

https://laravel.com/docs/7.x/eloquent-relationships#many-to-many


问:
This project uses AndroidX dependencies, but the 'android.useAndroidX' property is not enabled
This is my Error;

```<code>This project uses AndroidX dependencies, but the 'android.useAndroidX' property is not enabled. Set this property to true in the gradle.properties file and retry.
The following AndroidX dependencies are detected:
androidx.fragment:fragment:1.0.0,
androidx.versionedparcelable:versionedparcelable:1.0.0,
androidx.slidingpanelayout:slidingpanelayout:1.0.0
...
</code>```

How can i solve this problem? i delete all androidx libraries from my gradle files and my imported libraries from classes. i dont want to use androidx.

答:
The Android Gradle plugin provides the following global flags that you can set in your gradle.properties file:

android.useAndroidX: When set to true, this flag indicates that you want to start using AndroidX from now on.

If the flag is absent, Android Studio behaves as if the flag were set to false.

Therefore use this plugin android.useAndroidX=true in gradle.properties and sync project.

This should solve your problem.

Body:
This is my Error;

This project uses AndroidX dependencies, but the 'android.useAndroidX' property is not enabled. Set this property to true in the gradle.properties file and retry.
The following AndroidX dependencies are detected:
androidx.fragment:fragment:1.0.0,
androidx.versionedparcelable:versionedparcelable:1.0.0,
androidx.slidingpanelayout:slidingpanelayout:1.0.0
...

How can i solve this problem? i delete all androidx libraries from my gradle files and my imported libraries from classes. i dont want to use androidx.


问:
How do I create JSON array in this specific structure
This is the array format [{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}] I got from my angular form that having a dynamic table with columns name and number respectively.

I want to convert above mentioned array into the below mentioned format to store in database.

```<code>"name": [
            {
                "first_name": "Rose",
                "formatted_name": "Rose",
            },
            {
                "first_name": "smith",
                "formatted_name": "Smith",
            },
        ] ,

"phones": [
            {
                "phone": "+919224512555",
                "type": "HOME"
            },
            {
                "phone": "+91975555224",
                "type": "HOME",
            }
        ],
</code>```

I'm using angular for front-end development and laravel for back-end

答:
I think maybe this would be better way of doing it

```<code>const data = [
  { name: "Rose", number: "+919224512555" },
  { name: "smith", number: "+91975555224" },
]

const mapped = {
    "name": data.map((item) => ({
        first_name: item.name,
        formatted_name: item.name, // do your own formatting here
    })),
    "phone": data.map((item) => ({
        phone: item.number,
        type: item.number, // do your own processing here
    }))
}

console.log(mapped)
</code>```

hope it benefits you

Body:
This is the array format [{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}] I got from my angular form that having a dynamic table with columns name and number respectively.

I want to convert above mentioned array into the below mentioned format to store in database.

"name": [
            {
                "first_name": "Rose",
                "formatted_name": "Rose",
            },
            {
                "first_name": "smith",
                "formatted_name": "Smith",
            },
        ] ,

"phones": [
            {
                "phone": "+919224512555",
                "type": "HOME"
            },
            {
                "phone": "+91975555224",
                "type": "HOME",
            }
        ],

I'm using angular for front-end development and laravel for back-end

Body:
I think maybe this would be better way of doing it

const data = [
  { name: "Rose", number: "+919224512555" },
  { name: "smith", number: "+91975555224" },
]

const mapped = {
    "name": data.map((item) => ({
        first_name: item.name,
        formatted_name: item.name, // do your own formatting here
    })),
    "phone": data.map((item) => ({
        phone: item.number,
        type: item.number, // do your own processing here
    }))
}

console.log(mapped)

hope it benefits you


问:
Camel Ip Address caching
I have a URL in camel route which is set via JVM custom property and it remains unchanged.

```<code>    **<camel:to id="to-server" uri="{{serverURL}}" />**
</code>```

serverURL property is set to a site loadbalancer address http://xyz:8080/Server/transactionServlet

In the network layer this URL can either be pointed to Server 1 or Server 2, the URL should work regardless of which server we're using.

After the switch over from Server 1 to Server 2, our WAR still tries to post to Server 1 and fails.
It appears that our WAR is caching the the URL address (what the site loadbalancer was pointing to at the time) when it was started and does not recognize that we have switched over.
The only workaround is to restart the application WAR, at which point it stores the Server 2 address (what the site loadbalancer is now pointing to) and begins posting transactions to Server 2.

is there any way to make camel not cache the IP Address and post to whatever server URL is pointing to ?
I am using Apache Camel 2.14

答:
Have a look at networkaddress.cache.ttl.

Specified in java.security to indicate the caching policy for successful name lookups from the name service.. The value is specified as integer to indicate the number of seconds to cache the successful lookup.
  A value of -1 indicates "cache forever". The default behavior is to cache forever when a security manager is installed, and to cache for an implementation specific period of time, when a security manager is not installed.

Title: Camel Ip Address caching

Body:
I have a URL in camel route which is set via JVM custom property and it remains unchanged.

    **<camel:to id="to-server" uri="{{serverURL}}" />**

serverURL property is set to a site loadbalancer address http://xyz:8080/Server/transactionServlet

In the network layer this URL can either be pointed to Server 1 or Server 2, the URL should work regardless of which server we're using.

After the switch over from Server 1 to Server 2, our WAR still tries to post to Server 1 and fails.
It appears that our WAR is caching the the URL address (what the site loadbalancer was pointing to at the time) when it was started and does not recognize that we have switched over.
The only workaround is to restart the application WAR, at which point it stores the Server 2 address (what the site loadbalancer is now pointing to) and begins posting transactions to Server 2.

is there any way to make camel not cache the IP Address and post to whatever server URL is pointing to ?
I am using Apache Camel 2.14


问:
ERROR Android emulator gets killed in Android Studio
After updating to Android Studio 2 when I try to run my application and choose an emulator, I wait for the emulator to start and it suddenly gets killed. I can see the emulator process for some minutes but never the GUI. In Android studio, I get the error

```<code>android studio Error while waiting for the device: The emulator process for AVD was killed
</code>```

This happens even if I run the emulator outside Android Studio. I have tried both an Android 6 and an Android 4.4-based emulator.
Running on a Windows 7 x64 PC. Similar post to another StackOverflow post which was closed. I have tried various ram, VM heap, and resolution settings.

答:
For Android Studio v4.1 and above:

Menu -> Android Studio -> Preferences -> Tools -> Emulator

Uncheck Launch in a tool window option.

Body:
After updating to Android Studio 2 when I try to run my application and choose an emulator, I wait for the emulator to start and it suddenly gets killed. I can see the emulator process for some minutes but never the GUI. In Android studio, I get the error

android studio Error while waiting for the device: The emulator process for AVD was killed

This happens even if I run the emulator outside Android Studio. I have tried both an Android 6 and an Android 4.4-based emulator.
Running on a Windows 7 x64 PC. Similar post to another StackOverflow post which was closed. I have tried various ram, VM heap, and resolution settings.


问:
Return value from .then method
Goal of the code below is to replace some links with data fetched from API.

const articleData = '
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in data-embed=\"Instagram\" href=\"https://www.instagram.com/p/CAttGmVIIAS/\">reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
'

const article = document.createElement('div')

article.innerHTML = articleData;

[...article.querySelectorAll('[data-embed=Instagram]')].forEach(link => {
    fetch(`https://api.instagram.com/oembed/?maxwidth=400&url=${link.href}`)
    .then(response => {
        if (response.ok) {
            return response.json()
        }
        throw response.error
    })
    .then(json => {
        const instagramHtml = document.createElement('div')
        instagramHtml.innerHTML = json.html
        console.log(link.parentNode)
        link.parentNode.replaceChild(instagramHtml, link)
    })
})```

Everything works fine until it comes to replacing. It basically happens, but only within .then
method. How could I return from it?

Thank you!

答:
You cannot return a value from a Promise, however, assuming you're able to use async/await, you could do something like the following:

async function main() {
  try {
    const articleData =
      '
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
';
    const article = document.createElement("div");

    article.innerHTML = articleData;

    const links = [].slice.call(
      article.querySelectorAll("[data-embed=Instagram]")
    );
    // fetch all links and wait for a response
    const data = await Promise.all(links.map(link => get(link.href)));

    data.forEach(html => {
      const instagramHtml = document.createElement("div");
      instagramHtml.innerHTML = html;

      // do whatever you need to do here...
    });
  } catch (error) {
    // handle errors appropriately
    console.error(error);
  }
}
main();

function get(url) {
  return fetch(url).then(response => {
    if (response.ok) {
      return response.text();
    }
    throw response.error;
  });
}
```

Here's a working example:

CodeSandbox

See browser support for async/await:

href="https://caniuse.com/#feat=async-functions" rel="nofollow noreferrer">Can I use...

Title: Return value from .then method

Body:
Goal of the code below is to replace some links with data fetched from API.

const articleData = '
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
'

const article = document.createElement('div')

article.innerHTML = articleData;

[...article.querySelectorAll('[data-embed=Instagram]')].forEach(link => {
    fetch(`https://api.instagram.com/oembed/?maxwidth=400&url=${link.href}`)
    .then(response => {
        if (response.ok) {
            return response.json()
        }
        throw response.error
    })
    .then(json => {
        const instagramHtml = document.createElement('div')
        instagramHtml.innerHTML = json.html
        console.log(link.parentNode)
        link.parentNode.replaceChild(instagramHtml, link)
    })
})

Everything works fine until it comes to replacing. It basically happens, but only within .then
method. How could I return from it?

Thank you!

Body:
You cannot return a value from a Promise, however, assuming you're able to use async/await, you could do something like the following:

async function main() {
  try {
    const articleData =
      '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor <a data-embed="Instagram" href="https://www.instagram.com/p/CAttGmVIIAS/">incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in <a data-embed="Instagram" href="https://www.instagram.com/p/CAttGmVIIAS/">reprehenderit</a> in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>';
    const article = document.createElement("div");

    article.innerHTML = articleData;

    const links = [].slice.call(
      article.querySelectorAll("[data-embed=Instagram]")
    );
    // fetch all links and wait for a response
    const data = await Promise.all(links.map(link => get(link.href)));

    data.forEach(html => {
      const instagramHtml = document.createElement("div");
      instagramHtml.innerHTML = html;

      // do whatever you need to do here...
    });
  } catch (error) {
    // handle errors appropriately
    console.error(error);
  }
}
main();

function get(url) {
  return fetch(url).then(response => {
    if (response.ok) {
      return response.text();
    }
    throw response.error;
  });
}

Here's a working example:

CodeSandbox

See browser support for async/await:

Can I use...


问:
Python: words replacing in huge text
I have a huge text and a list of words ~10K.
What is the fastest way in Python to replace all this words in text with some other word?

EDIT:
Text size >1Gb, text is human written, and "extremely tokenized" (any runs of alphanumeric characters and any other single symbols was splitted into new tokens)

a number of words >10K, each word frequency in text is 1
the replacement word is same in all replacements.
Python 2.5-2.7

答:
I'd suggest a simple approach, replacing one line a time:</p>

```<code>pattern1 = 'foo'
pattern2 = 'bar'

with open('input.txt') as input, open('output.txt', 'w') as output:
    for line in input:
        output.write(line.replace(pattern1, pattern2))
</code>```

Title: Python: words replacing in huge text

Body:
I'd suggest a simple approach, replacing one line a time:

pattern1 = 'foo'
pattern2 = 'bar'

with open('input.txt') as input, open('output.txt', 'w') as output:
    for line in input:
        output.write(line.replace(pattern1, pattern2))


问:
Behaviour of increment and decrement operators in Python
How do I use pre-increment/decrement operators (++, --), just like in C++?

Why does ++count run, but not change the value of the variable?

答:
In python 3.8+ you can do :

```<code>(a:=a+1) #same as ++a (increment, then return new value)
(a:=a+1)-1 #same as a++ (return the incremented value -1) (useless)
</code>```

You can do a lot of thinks with this.

```<code>>>> a = 0
>>> while (a:=a+1) < 5:
    print(a)

1
2
3
4
</code>```

Or if you want write somthing with more sophisticated syntaxe (the goal is not optimization):

```<code>>>> del a
>>> while (a := (a if 'a' in locals() else 0) + 1) < 5:
    print(a)

1
2
3
4
</code>```

It will return 0 even if 'a' doesn't exist without errors, and then will set it to 1

Body:
In python 3.8+ you can do :

(a:=a+1) #same as ++a (increment, then return new value)
(a:=a+1)-1 #same as a++ (return the incremented value -1) (useless)

You can do a lot of thinks with this.

>>> a = 0
>>> while (a:=a+1) < 5:
    print(a)

1
2
3
4

Or if you want write somthing with more sophisticated syntaxe (the goal is not optimization):

>>> del a
>>> while (a := (a if 'a' in locals() else 0) + 1) < 5:
    print(a)

1
2
3
4

It will return 0 even if 'a' doesn't exist without errors, and then will set it to 1


问:
How can we encrypt a specific file/folder in android?
I am creating a file inside android root data,

```<code>    File myDir;
    myDir = new File(cw.getDir("", Context.MODE_PRIVATE).getPath() + File.separator + "New_Folder");

    if (!myDir.exists())
    {
        myDir.mkdirs();
    }
    else
    {
        Log.e("ASA9", "File Already Created.");
    }
</code>```

Can i encrypt that file?

Or can i Put a password to it?

答:
Check out the android's official documentation to do this.

https://developer.android.com/reference/androidx/security/crypto/EncryptedFile

```<code>  String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);

  File file = new File(context.getFilesDir(), "secret_data");
  EncryptedFile encryptedFile = EncryptedFile.Builder(
      file,
      context,
      masterKeyAlias,
      EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
  ).build();

  // write to the encrypted file
  FileOutputStream encryptedOutputStream = encryptedFile.openFileOutput();

  // read the encrypted file
  FileInputStream encryptedInputStream = encryptedFile.openFileInput();
</code>```

You also have to add this dependency in the android build.gradle file

```<code>dependencies {
    implementation "androidx.security:security-crypto:1.0.0-rc02"
}
</code>```

Body:
I am creating a file inside android root data,

    File myDir;
    myDir = new File(cw.getDir("", Context.MODE_PRIVATE).getPath() + File.separator + "New_Folder");

    if (!myDir.exists())
    {
        myDir.mkdirs();
    }
    else
    {
        Log.e("ASA9", "File Already Created.");
    }

Can i encrypt that file?

Or can i Put a password to it?

Body:
Check out the android's official documentation to do this.

https://developer.android.com/reference/androidx/security/crypto/EncryptedFile

  String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);

  File file = new File(context.getFilesDir(), "secret_data");
  EncryptedFile encryptedFile = EncryptedFile.Builder(
      file,
      context,
      masterKeyAlias,
      EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
  ).build();

  // write to the encrypted file
  FileOutputStream encryptedOutputStream = encryptedFile.openFileOutput();

  // read the encrypted file
  FileInputStream encryptedInputStream = encryptedFile.openFileInput();

You also have to add this dependency in the android build.gradle file

dependencies {
    implementation "androidx.security:security-crypto:1.0.0-rc02"
}


问:
What should be change in the "gender" part of the coding I have done below?
In the code below keeps on looping where entering 1 will lead in the void main() function and inside it, there is "gender" information. However, the gender output always got skipped over right after I type the date.

The "Enter your gender(Male/Female): " part got skipped

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

void entry() {
    FILE *fpointer;
    char name[20], gender[20], op, option;
    int visit_ID, phone_number, service_needed, change_service, date;
    float service_fee, payment_made, changes, change_service_fee;

    printf("\n\nEnter information:\n");
    printf("\nEnter name: ");
    scanf("%s", name);
    printf("\n\nEnter your ID number(Number only): ");
    scanf("%d", &visit_ID);
    printf("\n\nEnter today date in dd-mm-yy: ");
    scanf("%d", &date);
    printf("\n\nEnter your gender(Male/Female): ");
    scanf("%s", &gender);
    printf("\n\nEnter your phone number: ");
    scanf("%d", &phone_number);
    printf("\n\nDone registered\n\n");

    if ((fpointer = fopen("visitdetails.txt", "a")) == NULL) {
        perror("Write");
        exit(1);
    }
    fprintf(fpointer, "Visit ID = %d", visit_ID);
    fprintf(fpointer, "\nCustomer name = %s", name);
    fprintf(fpointer, "\nLast visit date : %d", date);
    fprintf(fpointer, "\nLast Service type repaired: %d", service_needed);
    fscanf(fpointer, "%d", service_needed);
    fprintf(fpointer, "\nLast Service fee: %.2f", service_fee);
    fprintf(fpointer, "\nLast payment: %.2f", payment_made);
    printf("\n\nRecord Written Successfully\n\n!!!");
    fclose(fpointer);
}

void Repair() {
    char name[20], gender[20], op, option;
    int visit_ID, phone_number, service_needed, date;
    float service_fee, payment_made, changes, change_service_fee;
    FILE *Welcome;

    Welcome = fopen("visitdetails.txt", "r");
    printf("\nWhich service type do you need(1-8)? ");
    scanf("%d", &service_needed);

    switch (service_needed) {
      case 1:
        printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ");
        scanf("%f", &service_fee);
        break;

      case 2:
        printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ");
        scanf("%f", &service_fee);
        break;

      case 3:
        printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ");
        scanf("%f", &service_fee);
        break;

      case 4:
        printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ");
        scanf("%f", &service_fee);
        break;

      case 5:
        printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ");
        scanf("%f", &service_fee);
        break;

      case 6:
        printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ", service_fee);
        scanf("%f", &service_fee);
        break;

      case 7:
        printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ", service_fee);
        scanf("%f", &service_fee);
        break;

      case 8:
        printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ", service_fee);
        scanf("%f", &service_fee);
        break;

      default:
        printf("Invalid option");
    }

    printf("\n\nPayment: ", payment_made);
    scanf("%f", &payment_made);

    if (payment_made > service_fee) {
        changes = payment_made - service_fee;
        printf("\nHere is your changes :%.2f\n", changes);
    }
    fclose(Welcome);
}

void Viewing_Store() {
    FILE *view;
    view = fopen("visitdetails.txt", "r");

    printf("No |    Service Type                                    | Needed Days | Service Fee | \n");
    printf("                                                                      |Normal|Urgent|\n");
    printf("1. | Remove virus,Malware, or Spyware                   |      2      | 30RM | 50RM |\n");
    printf("2. | Troubleshot and fix computer running slow          |      2      | 40RM | 70RM |\n");
    printf("3. | Laptop Screen Replacement                          |      3      | 330RM| 430RM|\n");
    printf("4. | Laptop Keyboard Replacement                        |      2      | 160RM| 200RM|\n");
    printf("5. | Laptop Battery Replacement                         |      1      | 180RM| 210RM|\n");
    printf("6. | Operating System Format and Installation           |      2      | 50RM | 80RM |\n");
    printf("7. | Data Backup and Recovery                           |      2      | 100RM| 150RM|\n");
    printf("8. | Internet Connectivity issues                       |      1      | 50RM | 75RM |\n");

    fclose(view);
}

void change_type() {
    FILE *change;
    char name[20], gender[20], op, option;
    int visit_ID, phone_number, service_needed, change_service, date;
    float service_fee, payment_made, changes, change_service_fee;

    change = fopen("visitdetails.txt", "r");
    printf("\nAre you sure you want to change the service type into(Y/N) : ", op);
    scanf("%s", &op);
    if (op == 'Y') {
        printf("\nWhat service type do you want to change into(1-8)? ", change_service);
        scanf("%d", &change_service);
        switch (change_service) {
          case 1:
            printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 2:
            printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 3:
            printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 4:
            printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 5:
            printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 6:
            printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 7:
            printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 8:
            printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          default:
            printf("Invalid option");
        }
    } else
    if (op == 'N') {
        printf("\nThe final price will be : %.2f", service_fee);
    }

    printf("\n\nPayment: ", payment_made);
    scanf("%f", &payment_made);

    if (payment_made > service_fee) {
        changes = payment_made - service_fee;
        printf("\nHere is your changes :%.2f\n", changes);
    } else
    if (payment_made > change_service_fee) {
        changes = payment_made - change_service_fee;
        printf("\nHere is your changes: %.2f\n", changes);
    } else
    if (payment_made == service_fee) {
        changes = payment_made - service_fee;
        printf("\nHere is your changes %f\n", changes);
    } else
    if (payment_made == change_service_fee) {
        changes = payment_made - change_service_fee;
        printf("\nHere is your changes: %f\n", changes);
    } else {
        printf("Error");
    }

    fprintf(change, "\n\nChanging service type into: %d", change_service);
    fprintf(change, "\nThe price of this service type is: %f", change_service_fee);
    fprintf(change,"\nPayment: %.2f", payment_made);
    fclose(change);
}

void any_visit(char anv[]) {
    FILE *anyvisit;
    char name[200], gender[20];
    int visit_ID, phone_number, service_needed, change_service, date, set;
    float service_fee, payment_made, changes, change_service_fee;

    anyvisit = fopen("visitdetails.txt","r");
    while (fscanf(any_visit, "%s %d %d %s %d %d\n", name, visit_ID, date, gender, phone_number, payment_made) != EOF) {
        set = strcmp(date, anv);
        if (set == 0) {
            printf("Visit_ID is %d", visit_ID);
            printf("\nName : %s", name);
            printf("\nGender is %s", gender);
            printf("\nPhone number is %d", phone_number);
            printf("\nPayment : %.2f", payment_made);
        }
    }
    fclose(anyvisit);
}

void search(char cnm[]) {
    FILE *search;
    char name[200], gender[20];
    int visit_ID, phone_number, service_needed, change_service, date, tes;
    float service_fee, payment_made, changes, change_service_fee;

    search = fopen("visitdetails.txt","r");
    while (fscanf(search, "%s %d %d %s %d %d\n", name, visit_ID, date, gender, phone_number, payment_made) != EOF) {
        tes = strcmp(name, cnm);
        if (tes == 0) {
            printf("Visit_ID is %d", visit_ID);
            printf("Date of visit is %d", date);
            printf("\nGender is %s", gender);
            printf("\nPhone number is %d", phone_number);
            printf("\nPayment: %d", date);
        }
    }
    fclose(search);
}

void main() {
    char name[200], gender[20], op, option, ch, cnm[30], anv[30];
    int visit_ID, phone_number, service_needed, change_service, date;
    float service_fee, payment_made, changes, change_service_fee;

    printf("*****Welcome to the Computer center*****\n");
    printf("\nBefore entering the store and have your equipment repair, it is best to view the store\n");
    do {
        printf("\nPress '1' to enter and have your data store");
        printf("\nPress '2' to View the store");
        printf("\nPress '3' to have your equipment being repaired");
        printf("\nPress '4' if you want to change your repair type");
        printf("\nPress '5' if you want to Search");
        printf("\nPress '6' if you want to search payment and unpaid balance by any visit");
        printf("\nPress '0' to exit");
        printf("\nEnter your choice : ");
        scanf("%d", &ch);
        switch(ch) {
          case 1:
            entry();
            break;
          case 2:
            Viewing_Store();
            break;
          case 3:
            Repair();
            break;
          case 4:
            change_type();
            break;
          case 5:
            printf("Enter your name: ");
            scanf("%s", &cnm);
            search(cnm);
            break;
          case 6:
            printf("Enter the date you visit: ");
            scanf("%d", &anv);
            any_visit(anv);
            break;
          case 0:
            exit(0);
          default:
            printf("\nInvalid Entry!!! ");
        }
    } while (ch != 0);
}
```

答:
```<code>This is what updated from before, however the search function when pressing '5' and '6' says that segmentation fault but i can't find any wrong code in my coding. Do you mind if you check once more what is the fault @Rohith S

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

void entry()
{
      FILE * fpointer;
      char name[20], gender[20], op, option, date[50];
      int visit_ID, phone_number, service_needed, change_service;
      float service_fee, payment_made, changes, change_service_fee;

      printf("\n\nEnter information:\n");
      printf("\nEnter name: ");
      scanf("%s", name);
      printf("\n\nEnter your ID number(Number only): ");
      scanf("%d", &visit_ID);
      printf("\n\nEnter today date in dd-mm-yy: ");
      scanf("%s" ,&date);
      printf("\n\nEnter your gender(Male/Female): ");
      scanf("%s",gender);
      printf("\n\nEnter your phone number: ");
      scanf("%d", &phone_number);
      printf("\n\nDone registered\n\n");

      if((fpointer = fopen("visitdetails.txt", "a")) == NULL)
        {
          perror("Write");
              exit(1);
        }
      fprintf(fpointer, "Visit ID = %d", visit_ID);
      fprintf(fpointer, "\nCustomer name = %s", name);
      fprintf(fpointer, "\nLast visit date : %s", date);
      fprintf(fpointer,"\nLast Service type repaired: %d", service_needed);
      fscanf(fpointer,"%d",service_needed);
      fprintf(fpointer, "\nLast Service fee: %.2f",service_fee);
      fprintf(fpointer,"\nLast payment: %.2f",payment_made);
      printf("\n\nRecord Written Successfully!!!\n\n");
      fclose(fpointer);
}
void Repair()
{
      char name[20], gender[20], op, option, date[50];
      int visit_ID, phone_number,service_needed;
      float service_fee, payment_made, changes, change_service_fee;

      FILE *Welcome;
      Welcome = fopen("visitdetails.txt","r");
          printf("\nWhich service type do you need(1-8)? ");
          scanf("%d", &service_needed);

          switch(service_needed)
          {
            case 1:
                printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 2:
                printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 3:
                printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 4:
                printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 5:
                printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ");
                scanf("%f",&service_fee);
                break;

            case 6:
                printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ",service_fee);
                scanf("%f",&service_fee);
            break;

            case 7:
                printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ",service_fee);
                scanf("%f",&service_fee);
            break;

            case 8:
                printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ",service_fee);
                scanf("%f",&service_fee);
            break;

            default:
            printf("Invalid option");
          }

          printf("\n\nPayment: ", payment_made);
          scanf("%f",&payment_made);

          if(payment_made > service_fee)
          {
            changes = payment_made - service_fee;
            printf("\nHere is your changes :%.2f\n", changes);
          }
            fclose(Welcome);
}
void Viewing_Store()
{
  FILE *view;
  view = fopen("visitdetails.txt","r");

  printf("No |    Service Type                                    | Needed Days | Service Fee | \n");
  printf("                                                                      |Normal|Urgent|\n");
  printf("1. | Remove virus,Malware, or Spyware                   |      2      | 30RM | 50RM |\n");
  printf("2. | Troubleshot and fix computer running slow          |      2      | 40RM | 70RM |\n");
  printf("3. | Laptop Screen Replacement                          |      3      | 330RM| 430RM|\n");
  printf("4. | Laptop Keyboard Replacement                        |      2      | 160RM| 200RM|\n");
  printf("5. | Laptop Battery Replacement                         |      1      | 180RM| 210RM|\n");
  printf("6. | Operating System Format and Installation           |      2      | 50RM | 80RM |\n");
  printf("7. | Data Backup and Recovery                           |      2      | 100RM| 150RM|\n");
  printf("8. | Internet Connectivity issues                       |      1      | 50RM | 75RM |\n");

  fclose(view);
}
void change_type()
{
  FILE *change;
  char name[20], gender[20], op, option, date[50];
  int visit_ID, phone_number, service_needed, change_service;
  float service_fee, payment_made, changes, change_service_fee;

      change = fopen("visitdetails.txt","r");
      printf("\nAre you sure you want to change the service type into(Y/N) : ", op);
      scanf("%s", &op);
      if(op == 'Y')
      {
        printf("\nWhat service type do you want to change into(1-8)? ", change_service);
        scanf("%d", &change_service);
        switch(change_service)
        {
          case 1:
          printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ",change_service_fee);
          scanf("%f",&change_service_fee);
          break;

          case 2:
          printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ",change_service_fee);
          scanf("%f",&change_service_fee);
          break;

          case 3:
          printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ",change_service_fee);
          scanf("%f",&change_service_fee);
          break;

          case 4:
          printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ",change_service_fee);
          scanf("%f",&change_service_fee);
          break;

          case 5:
          printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ",change_service_fee);
          scanf("%f",&change_service_fee);
          break;

          case 6:
          printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ",change_service_fee);
          scanf("%f",&change_service_fee);
          break;

          case 7:
          printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ",change_service_fee);
          scanf("%f",&change_service_fee);
          break;

          case 8:
          printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ",change_service_fee);
          scanf("%f",&change_service_fee);
          break;

          default:
          printf("Invalid option");
        }
      }
      else if (op == 'N')
      {
        printf("\nThe final price will be : %.2f", service_fee);
      }

      printf("\n\nPayment: ", payment_made);
      scanf("%f",&payment_made);

      if(payment_made > service_fee)
      {
        changes = payment_made - service_fee;
        printf("\nHere is your changes :%.2f\n", changes);
      }
      else if(payment_made > change_service_fee)
      {
        changes = payment_made - change_service_fee;
        printf("\nHere is your changes: %.2f\n", changes);
      }
      else if(payment_made == service_fee)
      {
        changes = payment_made - service_fee;
        printf("\nHere is your changes %f\n", changes);
      }
      else if(payment_made == change_service_fee)
      {
        changes = payment_made - change_service_fee;
        printf("\nHere is your changes: %f\n", changes);
      }
      else
      {
        printf("Error");
      }

      fprintf(change, "\n\nChanging service type into: %d", change_service);
      fprintf(change, "\nThe price of this service type is: %f", change_service_fee);
      fprintf(change,"\nPayment: %.2f",payment_made);
      fclose(change);
}
void any_visit(char anv[])
{
  FILE *anyvisit;

  char name[200], gender[20],date[50];
  int visit_ID, phone_number, service_needed, change_service, set;
  float service_fee, payment_made, changes, change_service_fee;

  anyvisit = fopen("visitdetails.txt","r");
  while(fscanf(any_visit, "%s %d %s %s %d %d\n", name, visit_ID, date, gender, phone_number, payment_made) !=EOF)
  {
    set = strcmp(date, anv);
    if(set == 0)
    {
      printf("Visit_ID is %d", visit_ID);
      printf("\nName : %s", name);
      printf("\nGender is %s", gender);
      printf("\nPhone number is %d", phone_number);
      printf("\nPayment : %.2f", payment_made);
    }
  }
  fclose(anyvisit);
}
void search(char cnm[])
{
  FILE *search;

  char name[200], gender[20],date[50];
  int visit_ID, phone_number, service_needed, change_service,tes;
  float service_fee, payment_made, changes, change_service_fee;

  search = fopen("visitdetails.txt","r");
  while(fscanf(search, "%s %d %s %s %d %d\n", name, visit_ID, date, gender, phone_number, payment_made) !=EOF)
  {
    tes = strcmp(name, cnm);
    if (tes == 0)
    {
      printf("Visit_ID is %d", visit_ID);
      printf("Date of visit is %s", date);
      printf("\nGender is %s", gender);
      printf("\nPhone number is %d", phone_number);
      printf("\nPayment: %d", payment_made);
    }
  }
  fclose(search);
}

void main()
{
  char name[200], gender[20], op, option, ch, cnm[30], anv[30],date[50];
  int visit_ID, phone_number, service_needed, change_service;
  float service_fee, payment_made, changes, change_service_fee;

  printf("*****Welcome to the Computer center*****\n");
  printf("\nBefore entering the store and have your equipment repair, it is best to view the store\n");
  do
  {
  printf("\nPress '1' to enter and have your data store");
  printf("\nPress '2' to View the store");
  printf("\nPress '3' to have your equipment being repaired");
  printf("\nPress '4' if you want to change your repair type");
  printf("\nPress '5' if you want to Search");
  printf("\nPress '6' if you want to search payment and unpaid balance by any visit");
  printf("\nPress '0' to exit");
  printf("\nEnter your choice : ");
  scanf("%d",&ch);
    switch(ch)
    {
    case 1: entry();
        break;
    case 2: Viewing_Store();
        break;
    case 3: Repair();
        break;
    case 4:change_type();
        break;
    case 5: printf("Enter your name: ");
            scanf("%s", &cnm);
            search(cnm);
        break;
    case 6: printf("Enter the date you visit: ");
            scanf("%d", &anv);
            any_visit(anv);
        break;
    case 0: exit(0);
    default: printf("\nInvalid Entry!!! ");
    }
  } while(ch != 0);
}
</code>```


问:
In a Svelte readable store array, How can I update only one item without touching the others?
I guess this question is more on JS sysntax, but I have a store array like this:

```<code>export const store = readable( {id: 0, value: 0} , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        set({id: 0, value: data});
    }
})
</code>```

The store defines its set method to update the value from a websockets connection.
How can I do the same but with a store array? Something like:

```<code>arr = [];
for(i=0; i<numberOfItems; i++) {
    arr = [...arr,{id: i, value: 0}];
}

export const store = readable( [{arr}] , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        var channel = data.channel;
        set({id: data.channel, value: data.value});
    }
})
</code>```

Here is where I dont manage to "set" o the array, and without having to declare the whole array every update.

答:
I think a readable store won't solve your problem, because you don't have an update method here. Why don't you try a writable store instead? It gives you an update function with the current value as an argument, so you can do something like this:

```<code>    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function(event) {
      var data = JSON.parse(event.data);
      var channel = data.channel;
      store.update(n => [...n, { id: data.channel, value: data.value }]);
    };
</code>```

Here is a REPL with an example of how it works. It uses intervals to simulate the webhooks functionality. If you open the console, you can see the updated store value.

Body:
I guess this question is more on JS sysntax, but I have a store array like this:

export const store = readable( {id: 0, value: 0} , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        set({id: 0, value: data});
    }
})

The store defines its set method to update the value from a websockets connection.
How can I do the same but with a store array? Something like:

arr = [];
for(i=0; i<numberOfItems; i++) {
    arr = [...arr,{id: i, value: 0}];
}

export const store = readable( [{arr}] , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        var channel = data.channel;
        set({id: data.channel, value: data.value});
    }
})

Here is where I dont manage to "set" o the array, and without having to declare the whole array every update.

Body:
I think a readable store won't solve your problem, because you don't have an update method here. Why don't you try a writable store instead? It gives you an update function with the current value as an argument, so you can do something like this:

    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function(event) {
      var data = JSON.parse(event.data);
      var channel = data.channel;
      store.update(n => [...n, { id: data.channel, value: data.value }]);
    };

Here is a REPL with an example of how it works. It uses intervals to simulate the webhooks functionality. If you open the console, you can see the updated store value.


问:
How to set GOOGLE_APPLICATION_CREDENTIALS in spring boot app
I am attempting to use the google vision library in java. The steps specify that I need to setup my auth credentials in order to start using the this library . I was able to generate my json property file from API Console Credentials page and I placed it in my spring boot app in the resources folder.

I think updated my application.properties file to include the value like so:

```<code>GOOGLE_APPLICATION_CREDENTIALS=datg-avatar-generator-9dc9155cd5bd.json
</code>```

I'm also setting my property source in my controller like so:

```<code>@PropertySource("${GOOGLE_APPLICATION_CREDENTIALS}")
</code>```

However, after doing that I'm still getting an error saying:

```<code>java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
</code>```

答:
I was able to configure this property using Spring Cloud GCP spring-cloud-gcp-starter-data-datastore, creating a service account project owner, copy the JSON private key to the main resources directory, and setting the following properties in the application.properties

```<code>spring.cloud.gcp.project-id=<project-id>
spring.cloud.gcp.credentials.location=classpath:<credentials-private-key>.json
</code>```

from the documentation

You can find the project id by visiting this page https://support.google.com/googleapi/answer/7014113?hl=en
Go to the API Console.

From the projects list, select Manage all projects. The names and IDs for all the projects you're a member of are displayed.
You can also select the project go the settings and see the project ID

Body:
I am attempting to use the google vision library in java. The steps specify that I need to setup my auth credentials in order to start using the this library . I was able to generate my json property file from API Console Credentials page and I placed it in my spring boot app in the resources folder.

I think updated my application.properties file to include the value like so:

GOOGLE_APPLICATION_CREDENTIALS=datg-avatar-generator-9dc9155cd5bd.json

I'm also setting my property source in my controller like so:

@PropertySource("${GOOGLE_APPLICATION_CREDENTIALS}")

However, after doing that I'm still getting an error saying:

java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.

Body:
I was able to configure this property using Spring Cloud GCP spring-cloud-gcp-starter-data-datastore, creating a service account project owner, copy the JSON private key to the main resources directory, and setting the following properties in the application.properties

spring.cloud.gcp.project-id=<project-id>
spring.cloud.gcp.credentials.location=classpath:<credentials-private-key>.json

from the documentation

You can find the project id by visiting this page https://support.google.com/googleapi/answer/7014113?hl=en
Go to the API Console.

From the projects list, select Manage all projects. The names and IDs for all the projects you're a member of are displayed.
You can also select the project go the settings and see the project ID


问:
Why is this Angular Material table not rendering?
I am working on a Contacts app with Angular 9 and Angular Material. The list component should display, for each contact, some info and an image, in a table row.

In my app.module.ts I have imported, among others, MatTableModule.

In app\services\contacts-list.service.ts I have:

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

import { Contact } from '../models/Contact';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
}

@Injectable({
  providedIn: 'root'
})

export class ContactsListService {

  contactsUrl = 'https://randomuser.me/api/?&results=20&inc=name,location,email,cell,picture';

  constructor(private http:HttpClient) { }

  getContcts():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

  getOneContact():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

}
</code>```

In the app\components\list\list.component.ts I have:

```<code>import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
})

export class ListComponent implements OnInit {

  pageTitle = 'My Contacts';

  contactsList:Contact[];

  constructor(private ContactsListService:ContactsListService) { }

  contactsTableData: MatTableDataSource<any>;
  displayedColumns: string[] = ['fullName', 'photo', 'email', 'city', 'country'];

  ngOnInit(): void  {
    // Contact list
    this.ContactsListService.getContcts().subscribe(
      contactsList => {
        this.contactsList = contactsList; console.log(contactsList);
        this.contactsTableData = new MatTableDataSource(contactsList);
      },
      error => { }
    );
  }
}
</code>```

I the above component's template:

```<code><div class="container">
    <h2 class="mat-display-1 page-title">{{pageTitle}}</h2>
    <div class="mat-elevation-z8">
        <mat-table [data-source]="contactsTableData">

            <ng-container matColumnDef="fullName">
                <mat-header-cell *matHeaderCellDef> Full Name </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.name.first}} {{element.name.last}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="photo">
                <mat-header-cell *matHeaderCellDef> Photo </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.picture.large}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="email">
                <mat-header-cell *matHeaderCellDef> Email address </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.email}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="city">
                <mat-header-cell *matHeaderCellDef> City </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.city}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="phone">
                <mat-header-cell *matHeaderCellDef> Phone </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.cell}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="country">
                <mat-header-cell *matHeaderCellDef> Country </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.country}} </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>
    </div>
</div>
</code>```

The problem

The problem I am faced with is that only the table header is displayed (the column names) with no data, evan thought the line console.log(contactsList) from the component correctly shows the arrary of contacts:

```<code>[
  {
     "name":{
        "title":"Mr",
        "first":"Mair",
        "last":"da Cunha"
     },
     "location":{
        "street":{
           "number":1198,
           "name":"Rua Belo Horizonte "
        },
        "city":"Cachoeiro de Itapemirim",
        "state":"Tocantins",
        "country":"Brazil",
        "postcode":36034,
        "coordinates":{
           "latitude":"-78.1101",
           "longitude":"-171.0313"
        },
        "timezone":{
           "offset":"+5:00",
           "description":"Ekaterinburg, Islamabad, Karachi, Tashkent"
        }
     },
     "email":"mair.dacunha@example.com",
     "cell":"(66) 5998-0008",
     "picture":{
        "large":"https://randomuser.me/api/portraits/men/88.jpg",
        "medium":"https://randomuser.me/api/portraits/med/men/88.jpg",
        "thumbnail":"https://randomuser.me/api/portraits/thumb/men/88.jpg"
     }
  }
]
</code>```

What is missing?

答:
On the tamplate, the mat-table should use [dataSource] instead of [data-source]. That should fix your issue.

Also quick tip, your response does not return an array of ContactAM, but an object that has a property called results, which in turn has a value of an array of ContactAM. So on your service, where you do the HTTP GET call and type it as ContactAM[], you should actually type it as { results: ContactAM[] }

Body:
I am working on a Contacts app with Angular 9 and Angular Material. The list component should display, for each contact, some info and an image, in a table row.

In my app.module.ts I have imported, among others, MatTableModule.

In app\services\contacts-list.service.ts I have:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

import { Contact } from '../models/Contact';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
}

@Injectable({
  providedIn: 'root'
})

export class ContactsListService {

  contactsUrl = 'https://randomuser.me/api/?&results=20&inc=name,location,email,cell,picture';

  constructor(private http:HttpClient) { }

  getContcts():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

  getOneContact():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

}

In the app\components\list\list.component.ts I have:

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
})

export class ListComponent implements OnInit {

  pageTitle = 'My Contacts';

  contactsList:Contact[];

  constructor(private ContactsListService:ContactsListService) { }

  contactsTableData: MatTableDataSource<any>;
  displayedColumns: string[] = ['fullName', 'photo', 'email', 'city', 'country'];

  ngOnInit(): void  {
    // Contact list
    this.ContactsListService.getContcts().subscribe(
      contactsList => {
        this.contactsList = contactsList; console.log(contactsList);
        this.contactsTableData = new MatTableDataSource(contactsList);
      },
      error => { }
    );
  }
}

I the above component's template:

{{pageTitle}}

        <mat-table [data-source]="contactsTableData">

            <ng-container matColumnDef="fullName">
                <mat-header-cell *matHeaderCellDef> Full Name </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.name.first}} {{element.name.last}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="photo">
                <mat-header-cell *matHeaderCellDef> Photo </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.picture.large}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="email">
                <mat-header-cell *matHeaderCellDef> Email address </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.email}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="city">
                <mat-header-cell *matHeaderCellDef> City </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.city}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="phone">
                <mat-header-cell *matHeaderCellDef> Phone </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.cell}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="country">
                <mat-header-cell *matHeaderCellDef> Country </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.country}} </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>

The problem

The problem I am faced with is that only the table header is displayed (the column names) with no data, evan thought the line console.log(contactsList) from the component correctly shows the arrary of contacts:

[
  {
     "name":{
        "title":"Mr",
        "first":"Mair",
        "last":"da Cunha"
     },
     "location":{
        "street":{
           "number":1198,
           "name":"Rua Belo Horizonte "
        },
        "city":"Cachoeiro de Itapemirim",
        "state":"Tocantins",
        "country":"Brazil",
        "postcode":36034,
        "coordinates":{
           "latitude":"-78.1101",
           "longitude":"-171.0313"
        },
        "timezone":{
           "offset":"+5:00",
           "description":"Ekaterinburg, Islamabad, Karachi, Tashkent"
        }
     },
     "email":"mair.dacunha@example.com",
     "cell":"(66) 5998-0008",
     "picture":{
        "large":"https://randomuser.me/api/portraits/men/88.jpg",
        "medium":"https://randomuser.me/api/portraits/med/men/88.jpg",
        "thumbnail":"https://randomuser.me/api/portraits/thumb/men/88.jpg"
     }
  }
]

What is missing?


答:
You could do with Array#reducer

const arr = [{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}];

const res = arr.reduce((a,{name,number})=>{
       a.name = a.name||[];
       a.name.push({first_name:name,formatted_name:name});
       a.phones = a.phones||[];
       a.phones.push({phone:number,type:'HOME'});
       return a;
},{})

console.log(res)```

Title: How do I create JSON array in this specific structure


问:
Pull out values from a multidimensional array into dataframe
I have a multidimensional dataarray with values at various lat, lon points. I would like to pull out these values and put them in a dataframe. I have tried using DataArray.to_dataframe() but I cannot get the dataframe to display exactly how I want it. Here is what the dataarray looks like.

```<code><xarray.DataArray (lat: 109, lon: 327)>
array([[0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       ...,
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.]])
Coordinates:
  * lat      (lat) float64 -52.0 -51.0 -50.0 -49.0 -48.0 ... 53.0 54.0 55.0 56.0
  * lon      (lon) float64 28.0 29.0 30.0 31.0 32.0 ... 351.0 352.0 353.0 354.0
</code>```

Ideal output would look like this:

```<code>Latitude   Longitude   Value
x          y           1
z          a           2
...        ...         ...
</code>```

Is there a better way of doing this besides a dataframe?

答: How about to_pandas()? This will give you a pandas dataframe, which should display in the way you are looking for.

Body:
I have a multidimensional dataarray with values at various lat, lon points. I would like to pull out these values and put them in a dataframe. I have tried using DataArray.to_dataframe() but I cannot get the dataframe to display exactly how I want it. Here is what the dataarray looks like.

<xarray.DataArray (lat: 109, lon: 327)>
array([[0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       ...,
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.]])
Coordinates:
  * lat      (lat) float64 -52.0 -51.0 -50.0 -49.0 -48.0 ... 53.0 54.0 55.0 56.0
  * lon      (lon) float64 28.0 29.0 30.0 31.0 32.0 ... 351.0 352.0 353.0 354.0

Ideal output would look like this:

Latitude   Longitude   Value
x          y           1
z          a           2
...        ...         ...

Is there a better way of doing this besides a dataframe?


问:
Unable to create AVD in Android Studio Mac
When trying to create a new virtual device on Android Studio, I receive an error,

An error occurred while creating the AVD. See idea.log for more info.

The error I found is

2018-01-31 10:01:34,090 [se-915-b08]   WARN - vdmanager.AvdManagerConnection - java.nio.file.NoSuchFileException: /Users/Name/.android/avd/Nexus_5X_API_27.ini

答:
This error occures because android studio cant see your .android file
Find file ~/.android

```<code>cd ~/.android
</code>```

you should be out of .android file (at least it worked like this on me otherwise it gives error chown: .android: No such file or directory)

```<code>cd ..
</code>```

then give permission to file

```<code>sudo chown <your_user_name> .android
</code>```

enter your password if asks

then try again creating avd in android studio

Body:
This error occures because android studio cant see your .android file
Find file ~/.android

cd ~/.android

you should be out of .android file (at least it worked like this on me otherwise it gives error chown: .android: No such file or directory)

cd ..

then give permission to file

sudo chown <your_user_name> .android

enter your password if asks

then try again creating avd in android studio


问:
ImportError: No module named requests on android kivy launcher
I am trying to run my python3 code through the kivy launcher on my android device but it crashes on launch, pointing towards the requests module in the error log. Is there any way to get the requests module to work on my android device?
As a side note, I am not using buildozer for this as I do not have a Linux machine, its strictly through the kivy launcher.</p>

答:
@Mark.97
Copy the modules required into the "kivy" folder on the mobile.
I was able to run the application successfully with kivy launcher after copying the following modules.
- requests
- idna
- certifi
- chardet
- urllib3</p>


问:
Getting duplicate elements in react component after fetchMore
I want to fetchMore data when onscroll reaches the bottom. The issue I have is that I get duplicate elements thus console yelling at me as well that I nee unique element keys. I'm getting the correct data in the graphql playground so it's an issue in my react component. Does this logic make sense? What's going wrong here?

```<code>class App extends Component {
  isBottom = (fetchMore, data) => {
    window.onscroll = () => {
      if (
        data &&
        data.infiniteScrollMovies &&
        data.infiniteScrollMovies.hasMore &&
        window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight
      ) {
        console.log('YES!')
        this.fetchMoreData(fetchMore, data)
      }
    }
  }

  fetchMoreData = (fetchMore, data) => {
    fetchMore({
      variables: {
        offset: data.infiniteScrollMovies.newOffset,
      },
      updateQuery: (prev, { fetchMoreResult }) => {
        if (!fetchMoreResult) return prev

        return {
          ...fetchMoreResult,
          infiniteScrollMovies: {
            ...fetchMoreResult.infiniteScrollMovies,
            movies: [...prev.infiniteScrollMovies.movies, ...fetchMoreResult.infiniteScrollMovies.movies],
          },
        }
      },
    })
  }

  render() {
    return (
      <div className="flex flex-column">
        <Query query={ALL_MOVIES} notifyOnNetworkStatusChange={true} fetchPolicy="network-only">
          {({ data, loading, error, fetchMore }) => {
            if (error) return <h1>{error.message}</h1>
            this.isBottom(fetchMore, data)
            return (
              <div>
                {data &&
                  data.infiniteScrollMovies &&
                  data.infiniteScrollMovies.movies.map(m => (
                    <article key={m.id}>
                    // ... rendering an element
                    </article>
                  ))}
           <div>{loading && <h1 className="red text-center">Loading...</h1>}</div>
</code>```

Here's my query:

```<code>export const ALL_MOVIES = gql`
  query infiniteScrollMovies($offset: Int) {
    infiniteScrollMovies(offset: $offset, limit: 16) {
      movies {
        image_url
        title
        id
      }
      hasMore
      newOffset
    }
  }
`
</code>```

答:
Use the variables parameter in updataeQuery to handle this scenario, basically you need to prevent the appending in cache if already its done.

Change your updateQuery to below

```<code>        updateQuery: (prev, { variables, fetchMoreResult }) => {
// Return the prev values, if it allready has the length specified by offset
// thereby preventing duplicate values in cache.
                        if (!fetchMoreResult ||
                           prev.infiniteScrollMovies.movies.length > variables.offset)
                         return prev
</code>```

Body:
I want to fetchMore data when onscroll reaches the bottom. The issue I have is that I get duplicate elements thus console yelling at me as well that I nee unique element keys. I'm getting the correct data in the graphql playground so it's an issue in my react component. Does this logic make sense? What's going wrong here?

class App extends Component {
  isBottom = (fetchMore, data) => {
    window.onscroll = () => {
      if (
        data &&
        data.infiniteScrollMovies &&
        data.infiniteScrollMovies.hasMore &&
        window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight
      ) {
        console.log('YES!')
        this.fetchMoreData(fetchMore, data)
      }
    }
  }

  fetchMoreData = (fetchMore, data) => {
    fetchMore({
      variables: {
        offset: data.infiniteScrollMovies.newOffset,
      },
      updateQuery: (prev, { fetchMoreResult }) => {
        if (!fetchMoreResult) return prev

        return {
          ...fetchMoreResult,
          infiniteScrollMovies: {
            ...fetchMoreResult.infiniteScrollMovies,
            movies: [...prev.infiniteScrollMovies.movies, ...fetchMoreResult.infiniteScrollMovies.movies],
          },
        }
      },
    })
  }

  render() {
    return (

        <Query query={ALL_MOVIES} notifyOnNetworkStatusChange={true} fetchPolicy="network-only">
          {({ data, loading, error, fetchMore }) => {
            if (error) return
{error.message}

            this.isBottom(fetchMore, data)
            return (

                {data &&
                  data.infiniteScrollMovies &&
                  data.infiniteScrollMovies.movies.map(m => (

                    // ... rendering an element

                  ))}

{loading &&
Loading...
}

Here's my query:

export const ALL_MOVIES = gql`
  query infiniteScrollMovies($offset: Int) {
    infiniteScrollMovies(offset: $offset, limit: 16) {
      movies {
        image_url
        title
        id
      }
      hasMore
      newOffset
    }
  }
`

Body:
Use the variables parameter in updataeQuery to handle this scenario, basically you need to prevent the appending in cache if already its done.

Change your updateQuery to below

        updateQuery: (prev, { variables, fetchMoreResult }) => {
// Return the prev values, if it allready has the length specified by offset
// thereby preventing duplicate values in cache.
                        if (!fetchMoreResult ||
                           prev.infiniteScrollMovies.movies.length > variables.offset)
                         return prev


问:
Spring Boot not loading @ConfigurationProperties
I am developing a Spring boot application where I am trying to configure custom properties for a bean which gives the suppourted extensions for my file .
When I run the application it runs sucessfully with 0 errors but the extensions are not loaded from the application.properties file.

Here is my code in application.properties :-----

```<code>suppourted.extensions[0]="jpg"
suppourted.extensions[1]="pdf"
suppourted.extensions[2]="png"

</code>```

Here is the code of the bean:--

```<code>package com.MyBoot.FirstBoot;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@ConfigurationProperties(prefix = "suppourted")
public class SuppourtedFiles {

    private List<String> extensions=new ArrayList<>();

    public List<String>getExtensions() {
        return extensions;
    }

    public void setExtensions(List<String>extensions) {
        this.extensions = extensions;
    }

    @Override
    public String toString() {
        return "SuppourtedFiles [extensions=" + extensions.size() + "]";
    }

}

</code>```

My main SpringBootApplication:----

```<code>package com.MyBoot.FirstBoot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class FirstBoot1Application {

    public static void main(String[] args) {
        SpringApplication.run(FirstBoot1Application.class, args);
    }

}

</code>```

I do not understand where the problem is occuring. Kindly help me.

Update:--

I want to send that object to my jsp page for displaying it using model not just create that bean in CommandLineRunner

答:
If I remember correctly you should either use

@Configuration

in your SuppourtedFiles class or

@EnableConfigurationProperties(SuppourtedFiles.class)

in your FirstBoot1Application.

Body:
I am developing a Spring boot application where I am trying to configure custom properties for a bean which gives the suppourted extensions for my file .
When I run the application it runs sucessfully with 0 errors but the extensions are not loaded from the application.properties file.

Here is my code in application.properties :-----

suppourted.extensions[0]="jpg"
suppourted.extensions[1]="pdf"
suppourted.extensions[2]="png"

Here is the code of the bean:--

package com.MyBoot.FirstBoot;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@ConfigurationProperties(prefix = "suppourted")
public class SuppourtedFiles {

    private List<String> extensions=new ArrayList<>();

    public List<String>getExtensions() {
        return extensions;
    }

    public void setExtensions(List<String>extensions) {
        this.extensions = extensions;
    }

    @Override
    public String toString() {
        return "SuppourtedFiles [extensions=" + extensions.size() + "]";
    }

}

My main SpringBootApplication:----

package com.MyBoot.FirstBoot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class FirstBoot1Application {

    public static void main(String[] args) {
        SpringApplication.run(FirstBoot1Application.class, args);
    }

}

I do not understand where the problem is occuring. Kindly help me.

Update:--

I want to send that object to my jsp page for displaying it using model not just create that bean in CommandLineRunner


问:
Flutter app with a web view deployed to the web
Seems like it should be something simple. I'm converting a mobile app to have web support. There are a few pages within the app that use WebView to display things such as terms and conditions and FAQ's.

As the WebView widget only supports ios and android from what I can tell, how should I do this? Of all the platforms you'd think the web was the easiest to do this!

答: ok, just after posting I came across IFrameElement which looking at this link https://medium.com/flutter-community/flutter-web-and-iframe-f26399aa1e2a should make it possible.


问:
Repository is not signed in docker build
I have the following Dockerfile that uses the latest Ubuntu image pulled from dockerhub:

```<code>FROM ubuntu:latest
RUN apt-get update  && apt-get install -y  g++ llvm lcov
</code>```

when I launch the docker build command, the following errors occur:

```<code>Err:2 http://archive.ubuntu.com/ubuntu bionic InRelease
At least one invalid signature was encountered.

Err:1 http://security.ubuntu.com/ubuntu bionic-security InRelease
  At least one invalid signature was encountered.

Err:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
  At least one invalid signature was encountered.

Err:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
  At least one invalid signature was encountered.

Reading package lists...

W: GPG error: http://archive.ubuntu.com/ubuntu bionic InRelease: At least one invalid signature was encountered.
E: The repository 'http://archive.ubuntu.com/ubuntu bionic InRelease' is not signed.

W: GPG error: http://security.ubuntu.com/ubuntu bionic-security InRelease: At least one invalid signature was encountered.
E: The repository 'http://security.ubuntu.com/ubuntu bionic-security InRelease' is not signed.

W: GPG error: http://archive.ubuntu.com/ubuntu bionic-updates InRelease: At least one invalid signature was encountered.
E: The repository 'http://archive.ubuntu.com/ubuntu bionic-updates InRelease' is not signed.

W: GPG error: http://archive.ubuntu.com/ubuntu bionic-backports InRelease: At least one invalid signature was encountered.
E: The repository 'http://archive.ubuntu.com/ubuntu bionic-backports InRelease' is not signed.
</code>```

I read here https://superuser.com/questions/1331936/how-can-i-get-past-a-repository-is-not-signed-message-when-attempting-to-upgr that you can pass this error using --allow-unauthenitcated or --allow-insecure-repositories but both seem to me workarounds that may compromize security of the container.

EDIT

Tried to pull ubuntu:18.04, ubuntu:19:04, ubuntu:19.10 same error with different distro name

答:
I had this problem on one of my two machines. Doing a ls -ld /tmp I got

```<code>drwxrwxrwt 3 root root 4096 May 15 20:46 /tmp
</code>```

for the working one and

```<code>drwxr-xr-t 1 root root 4096 May 26 05:44 /tmp
</code>```

for the failing one. After I did chmod 1777 /tmp, it worked!!

EDIT:

So, I dived a little deeper into this problem and realized there was something fundamentally wrong. I put my problems in another question and later found the answer that solved this myself: https://stackoverflow.com/a/62088961/7387935

The key point here is that on the machine that was working correctly I had aufs as storage driver and on the faulty one it was overlay2. After I changed that, all permissions were correct.

Body:
I have the following Dockerfile that uses the latest Ubuntu image pulled from dockerhub:

FROM ubuntu:latest
RUN apt-get update  && apt-get install -y  g++ llvm lcov

when I launch the docker build command, the following errors occur:

Err:2 http://archive.ubuntu.com/ubuntu bionic InRelease
At least one invalid signature was encountered.

Err:1 http://security.ubuntu.com/ubuntu bionic-security InRelease
  At least one invalid signature was encountered.

Err:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
  At least one invalid signature was encountered.

Err:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
  At least one invalid signature was encountered.

Reading package lists...

W: GPG error: http://archive.ubuntu.com/ubuntu bionic InRelease: At least one invalid signature was encountered.
E: The repository 'http://archive.ubuntu.com/ubuntu bionic InRelease' is not signed.

W: GPG error: http://security.ubuntu.com/ubuntu bionic-security InRelease: At least one invalid signature was encountered.
E: The repository 'http://security.ubuntu.com/ubuntu bionic-security InRelease' is not signed.

W: GPG error: http://archive.ubuntu.com/ubuntu bionic-updates InRelease: At least one invalid signature was encountered.
E: The repository 'http://archive.ubuntu.com/ubuntu bionic-updates InRelease' is not signed.

W: GPG error: http://archive.ubuntu.com/ubuntu bionic-backports InRelease: At least one invalid signature was encountered.
E: The repository 'http://archive.ubuntu.com/ubuntu bionic-backports InRelease' is not signed.

I read here https://superuser.com/questions/1331936/how-can-i-get-past-a-repository-is-not-signed-message-when-attempting-to-upgr that you can pass this error using --allow-unauthenitcated or --allow-insecure-repositories but both seem to me workarounds that may compromize security of the container.

EDIT

Tried to pull ubuntu:18.04, ubuntu:19:04, ubuntu:19.10 same error with different distro name

Body:
I had this problem on one of my two machines. Doing a ls -ld /tmp I got

drwxrwxrwt 3 root root 4096 May 15 20:46 /tmp

for the working one and

drwxr-xr-t 1 root root 4096 May 26 05:44 /tmp

for the failing one. After I did chmod 1777 /tmp, it worked!!

EDIT:

So, I dived a little deeper into this problem and realized there was something fundamentally wrong. I put my problems in another question and later found the answer that solved this myself: https://stackoverflow.com/a/62088961/7387935

The key point here is that on the machine that was working correctly I had aufs as storage driver and on the faulty one it was overlay2. After I changed that, all permissions were correct.