问:
Datadog data validation between on-prem and cloud database
Very new to Datadog and need some help. I have crafted 2 SQL queries (one for on-prem database and one for cloud database) and I would like to run those queries through Datadog and be able display the query results and validate that the daily results fall within an expected variance between the two systems.

I have already set up Datadog on the cloud environment and believe I should use DogStatsD to create a custom metric but I am pretty lost with how I can incorporate my necessary SQL queries in the code to create the metric for eventual display on a dashboard. Any help will be greatly appreciated!!!

答:
You probably want to be using the MySQL integration, and configure the 'custom queries' option: https://docs.datadoghq.com/integrations/faq/how-to-collect-metrics-from-custom-mysql-queries

You can follow those instructions after you configure the base integration https://docs.datadoghq.com/integrations/mysql/#pagetitle (This will give you a lot of use metrics in addition to the custom queries you want to run)

As you mentioned, DogStatsD is a library you can import to whatever script or application in order to submit metrics. But it really isn't a common practice in the slightest to modify the underlying code of your database. So instead it makes more sense to externally run a query on the database, take those results, and send them to datadog. You could totally write a python script or something to do this. However the Datadog agent already has this capability built in, so it's probably easier to just use that.

I am also just assuming SQL refers to MySQL, there are other integration for things like SQL Server, and PostgreSQL, and pretty much every implementation of sql. And the same pattern applies where you would configure the integration, and then add an extra line to the config file where you have the check run your queries.


来源: stackexchange

问:
How do you patch mock an import from a class that is being imported to a module you are testing?
The module I am attempting to test (with pytest and pytest-mock) is like so:

x.py

```<code>from a import ClassA

def a_func():
  class_a = ClassA()
  ...

</code>```

module a.py:

```<code>import b

class ClassA:
  ...

</code>```

test:

```<code>def test_my_code(mocker):
  import x
  mock_of_b = mocker.patch.object(x.a, 'b')
  ...

</code>```

or plain unittest:

```<code>import x

class MyTests(unittest.TestCase):

  @patch('x.a.b')
  def test_my_code(self, mock_of_b):
  ...
</code>```

I understand that x.a.b isn't going to work because a isn't actually imported - ClassA is but I'm not understanding how can I accomplish patching b in module a when importing ClassA directly.  x.ClassA.b won't work - is there some kind of param to access an imported classes module?  I could grab __module__ but that's just the string.

答:
Maybe you are making some mistakes. Take a look at a simple setup of a module + mock + function environment.

person.py

```<code>class Person:
    def __init__(self, name):
        self.name = name
    def get_name(self):
        return self.name
</code>```

function.py

```<code>from person import Person

def show_person(name):
    person = Person(name)
    return "The person name is {}".format(person.get_name())
</code>```

test.py

```<code>from unittest import TestCase, mock
from function import show_person

class TestPerson(TestCase):
    def test_person(self):
        with mock.patch('function.Person.get_name', return_value="bpreisler") as mock_person:
            self.assertEqual(show_person("John"), "The person name is bpreisler")

</code>```

ContentLicense: CC BY-SA 4.0

Body:
The module I am attempting to test (with pytest and pytest-mock) is like so:

x.py

from a import ClassA

def a_func():
  class_a = ClassA()
  ...

module a.py:

import b

class ClassA:
  ...

test:

def test_my_code(mocker):
  import x
  mock_of_b = mocker.patch.object(x.a, 'b')
  ...

or plain unittest:

import x

class MyTests(unittest.TestCase):

  @patch('x.a.b')
  def test_my_code(self, mock_of_b):
  ...

I understand that x.a.b isn't going to work because a isn't actually imported - ClassA is but I'm not understanding how can I accomplish patching b in module a when importing ClassA directly.  x.ClassA.b won't work - is there some kind of param to access an imported classes module?  I could grab __module__ but that's just the string.

Body:
Maybe you are making some mistakes. Take a look at a simple setup of a module + mock + function environment.

person.py

class Person:
    def __init__(self, name):
        self.name = name
    def get_name(self):
        return self.name

function.py

from person import Person

def show_person(name):
    person = Person(name)
    return "The person name is {}".format(person.get_name())

test.py

from unittest import TestCase, mock
from function import show_person

class TestPerson(TestCase):
    def test_person(self):
        with mock.patch('function.Person.get_name', return_value="bpreisler") as mock_person:
            self.assertEqual(show_person("John"), "The person name is bpreisler")


问:
My Android App shows as "this item is not compatible with your device"
I just published an update to my app in the market.  I then tried to bring it up on the market on my Nexus One running 2.2.2.  I could not find it in the market on the phone.  I went to the web market, found it, but install was disabled saying "this item is not compatible with your device".  Below is my manifest - I can't see anything that would prevent it from working on my Nexus One.  Makes me think it is not showing for others also.  Can anyone else install (or see if it is able to be seen) "Occupied for Kids" or "Occupied for Kids (Demo)".  You can try the Demo version easily enough because it is free.  Both exhibit the problem.  </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.ecg.occupiedDemo"
      android:versionCode="15"
      android:versionName="2.01"
      android:installLocation="auto" >

    <supports-screens
        android:smallScreens="false"
        android:normalScreens="true"
        android:largeScreens="true"
        android:anyDensity="true"
    />

    <uses-configuration android:reqTouchScreen="finger"></uses-configuration>
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/button_launchdemo" android:label="@string/app_name">
        *<Activity List Here>*
    </application>
    <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="7" />

</manifest>
</code>```

答:
Another possible reason:

I had this problem when I published an app, so I monkied around with it until I figured it out. When I disabled copy protection on my app, suddenly it was compatible with my device (Sony Xperia Play) and I was able to install through the android market.

Copy protection is now deprecated and is being replaced with a new licensing feature, so assuming licensing doens't have the same bug this problem will in theory be phased out. For those affected now, I have found a potential solution but it requires an unlocked bootloader to clear your cache partition:

http://forum.xda-developers.com/showpost.php?p=11626645&postcount=425

So if you are a developer and some people can't see your app, disable copy protection and use licensing instead. I also suggest using the Android SDK built in ProGuard feature to obfuscate (scramble) your code to make it harder to reverse engineer.

ContentLicense: CC BY-SA 2.5

Body:
I just published an update to my app in the market.  I then tried to bring it up on the market on my Nexus One running 2.2.2.  I could not find it in the market on the phone.  I went to the web market, found it, but install was disabled saying "this item is not compatible with your device".  Below is my manifest - I can't see anything that would prevent it from working on my Nexus One.  Makes me think it is not showing for others also.  Can anyone else install (or see if it is able to be seen) "Occupied for Kids" or "Occupied for Kids (Demo)".  You can try the Demo version easily enough because it is free.  Both exhibit the problem.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.ecg.occupiedDemo"
      android:versionCode="15"
      android:versionName="2.01"
      android:installLocation="auto" >

    <supports-screens
        android:smallScreens="false"
        android:normalScreens="true"
        android:largeScreens="true"
        android:anyDensity="true"
    />

    <uses-configuration android:reqTouchScreen="finger"></uses-configuration>
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/button_launchdemo" android:label="@string/app_name">
        *<Activity List Here>*
    </application>
    <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="7" />

</manifest>

ContentLicense: CC BY-SA 3.0


问:
How should I interpret or intuitively explain the following results for my CNN model?
I am training a CNN model that has to classify 4 objects. 3 mugs (white, black, blue) and 1 glass. When I train my model for only 10 epochs, I get a validation accuracy of 25%, where everything is being labeled as the white mug. However when I would train the same model for longer, it eventually diverts from this 25% accuracy and climbs up to 80%, the only problem it has, is classifying the white mug.

In other words, if I am able to find why my classifier classifies the white mug wrongly, then I could potentially reach validation_accuracy of 90%. My question thus is, what are some things I could try to find out why it mispredicts, or things to improve. I have already used LIME to check why my model classifies something, but I could not get any wiser from it.

Some specs of the model:

No data augmentation

5 convolutional layers (32, 64, 128, 256, 512) -> into GlobalMaxPooling, Flatten, and 2 dense layers (128, 4)

Activation layers (relu)

2000 training images, 1000 validation images (classes are balanced)

Extra: The model gets 100% accuracy on the training data after 2 epochs, and slowly climbs up to 80% on the validation data (after about 40-50 epochs).

Extra 2: Sometimes the model gets 80%, sometimes only 74%

答: The model is reaching 100% training accuracy when validation accuracy is still only 25%. A 75% gap between training and validation accuracy is enormous and indicates the model is overfitting to the training data, likely due to the small size of the training data set (2000). Data augmentation would likely significantly reduce overfitting and improve validation accuracy - I would start with random cropping, brightness, and saturation. Collecting more training data with varied backgrounds, orientations, and lighting conditions would also help.</p>


问:
Find all the maximum directed connected groups from a list of pairs
I would like to find out the maximum directed connected groups from the following pairs.

```<code>pairs = [
    ('creepy', 'sports'),
    ('AskReddit', 'creepy'),
    ('AskReddit', 'boardgames'),
    ('AskReddit', 'television'),
    ('AskReddit', 'movies'),
    ('AskReddit', 'history'),
    ('sports', 'television'),
    ('creepy', 'movies'),
    ('history', 'television'),
    ('movies', 'sports'),
    ('creepy', 'television'),
    ('movies', 'television')
]
</code>```

The output that I need to have is:

Group 1: ('creepy', 'sports', 'television', 'movies')

Group 2: ('creepy', 'AskReddit', 'movies', 'television')

Group 3: ('AskReddit', 'boardgames')

Group 4: ('AskReddit', 'history', 'television')

For example, I do not want to have the group ('AskReddit', 'history', 'television', 'boardgames') because there is not a directed connection from 'boardgames' both to 'television' and 'history'.

I made many many tries using directed graphs. I think that this is that I want to find has a specific name in graph theory but I really can not remember it. My first try was with DFS and how can I create a chain of them but the output contains the group that I refer above and I do not want to have it.

I use Python.

All your comments are welcome! Thanks in advance.

答:
It looks like you want to find the maximal cliques containing each node in the graph, where a maximal clique for v is a largest complete subgraph containing v.

In NetworkX we have nx.find_cliques, which does exactly that:

```<code>G=nx.Graph()
G.add_edges_from(pairs)
max_cliques = list(nx.find_cliques(G))
</code>```

```<code>print(max_cliques)
[['boardgames', 'AskReddit'],
 ['television', 'sports', 'creepy', 'movies'],
 ['television', 'AskReddit', 'history'],
 ['television', 'AskReddit', 'creepy', 'movies']]
</code>```

Body:
I would like to find out the maximum directed connected groups from the following pairs.

pairs = [
    ('creepy', 'sports'),
    ('AskReddit', 'creepy'),
    ('AskReddit', 'boardgames'),
    ('AskReddit', 'television'),
    ('AskReddit', 'movies'),
    ('AskReddit', 'history'),
    ('sports', 'television'),
    ('creepy', 'movies'),
    ('history', 'television'),
    ('movies', 'sports'),
    ('creepy', 'television'),
    ('movies', 'television')
]

The output that I need to have is:

Group 1: ('creepy', 'sports', 'television', 'movies')

Group 2: ('creepy', 'AskReddit', 'movies', 'television')

Group 3: ('AskReddit', 'boardgames')

Group 4: ('AskReddit', 'history', 'television')

For example, I do not want to have the group ('AskReddit', 'history', 'television', 'boardgames') because there is not a directed connection from 'boardgames' both to 'television' and 'history'.

I made many many tries using directed graphs. I think that this is that I want to find has a specific name in graph theory but I really can not remember it. My first try was with DFS and how can I create a chain of them but the output contains the group that I refer above and I do not want to have it.

I use Python.

All your comments are welcome! Thanks in advance.

Body:
It looks like you want to find the maximal cliques containing each node in the graph, where a maximal clique for v is a largest complete subgraph containing v.

In NetworkX we have nx.find_cliques, which does exactly that:

G=nx.Graph()
G.add_edges_from(pairs)
max_cliques = list(nx.find_cliques(G))

print(max_cliques)
[['boardgames', 'AskReddit'],
 ['television', 'sports', 'creepy', 'movies'],
 ['television', 'AskReddit', 'history'],
 ['television', 'AskReddit', 'creepy', 'movies']]


问:
vigenere encryption probleme with 'spaces' on python
i can t pinpoint the reason why the encryption goes wrong after 'spaces'
here is the code :

```<code>def chiffre_vigenere(message,key):
        message = message.lower()
        key = key.lower()
        encrypted = []
        d = dict(a=0,b=1,c=2,d=3,e=4,f=5,g=6,h=7,i=8,j=9,k=10,l=11,m=12,n=13,o=14,p=15,q=16,r=17,s=18,t=19,u=20,v=21,w=22,x=23,y=24,z=25)
        long_key = key
        while len(message) > len(long_key) :
                long_key = long_key + key
        i=0
        while i < len(message) :
                decalage = d.get(long_key[i])
                if message[i].isalpha() :
                        c = ord(message[i]) + decalage
                        if c > 122 :
                                c = c - 26
                        encrypted.append(chr(c))
                else :
                        encrypted.append(message[i])
                i = i+1
        print(listToString(encrypted))

</code>```

for example when i do : chiffre_vigenere('stack overflow','apple')
it gives : sipno dkpvfadh
the first word is encrypted right but after the space the encryption is wrong
any help is appreciated thanks in advance

答:
The problem is that you're using the same counter variable i to mark your place in two different strings: message and long_key. Whenever you encounter a non-alphabet character in message, you're stepping to the next character, but you're also stepping to the next character in long_key, which is not what you want to do.

If you just use i to count characters in long_key then the problem goes away. For example:

```<code>def chiffre_vigenere(message,key):
    message = message.lower()
    key = key.lower()
    encrypted = []
    d = dict(a=0,b=1,c=2,d=3,e=4,f=5,g=6,h=7,i=8,j=9,k=10,l=11,m=12,n=13,o=14,p=15,q=16,r=17,s=18,t=19,u=20,v=21,w=22,x=23,y=24,z=25)
    long_key = key
    while len(message) > len(long_key):
        long_key = long_key + key
    i=0
    for ch in message:
        decalage = d.get(long_key[i])
        if ch.isalpha() :
            c = ord(ch) + decalage
            if c > 122 :
                c = c - 26
            encrypted.append(chr(c))
            i = i+1
        else :
            encrypted.append(ch)
    print(listToString(encrypted))
</code>```

You might also consider simplifying your code a little. You can use the ord function to convert ASCII values to integers, and a modulus operator to cycle through the values of key without having to expand it to the size of the input message.

```<code>def chiffre_vigenere(message,key):
    key = key.lower()
    encrypted = ''
    i = 0
    for ch in message.lower():
        if 'a' <= ch <= 'z':
            a = ord(ch) + ord(key[i]) - ord('a')
            if a > ord('z'):
                a -= 26
            encrypted += chr(a)
            i = (i + 1) % len(key)
        else:
            encrypted += ch
    print(encrypted)
</code>```

Body:
i can t pinpoint the reason why the encryption goes wrong after 'spaces'
here is the code :

def chiffre_vigenere(message,key):
        message = message.lower()
        key = key.lower()
        encrypted = []
        d = dict(a=0,b=1,c=2,d=3,e=4,f=5,g=6,h=7,i=8,j=9,k=10,l=11,m=12,n=13,o=14,p=15,q=16,r=17,s=18,t=19,u=20,v=21,w=22,x=23,y=24,z=25)
        long_key = key
        while len(message) > len(long_key) :
                long_key = long_key + key
        i=0
        while i < len(message) :
                decalage = d.get(long_key[i])
                if message[i].isalpha() :
                        c = ord(message[i]) + decalage
                        if c > 122 :
                                c = c - 26
                        encrypted.append(chr(c))
                else :
                        encrypted.append(message[i])
                i = i+1
        print(listToString(encrypted))

for example when i do : chiffre_vigenere('stack overflow','apple')
it gives : sipno dkpvfadh
the first word is encrypted right but after the space the encryption is wrong
any help is appreciated thanks in advance

Body:
The problem is that you're using the same counter variable i to mark your place in two different strings: message and long_key. Whenever you encounter a non-alphabet character in message, you're stepping to the next character, but you're also stepping to the next character in long_key, which is not what you want to do.

If you just use i to count characters in long_key then the problem goes away. For example:

def chiffre_vigenere(message,key):
    message = message.lower()
    key = key.lower()
    encrypted = []
    d = dict(a=0,b=1,c=2,d=3,e=4,f=5,g=6,h=7,i=8,j=9,k=10,l=11,m=12,n=13,o=14,p=15,q=16,r=17,s=18,t=19,u=20,v=21,w=22,x=23,y=24,z=25)
    long_key = key
    while len(message) > len(long_key):
        long_key = long_key + key
    i=0
    for ch in message:
        decalage = d.get(long_key[i])
        if ch.isalpha() :
            c = ord(ch) + decalage
            if c > 122 :
                c = c - 26
            encrypted.append(chr(c))
            i = i+1
        else :
            encrypted.append(ch)
    print(listToString(encrypted))

You might also consider simplifying your code a little. You can use the ord function to convert ASCII values to integers, and a modulus operator to cycle through the values of key without having to expand it to the size of the input message.

def chiffre_vigenere(message,key):
    key = key.lower()
    encrypted = ''
    i = 0
    for ch in message.lower():
        if 'a' <= ch <= 'z':
            a = ord(ch) + ord(key[i]) - ord('a')
            if a > ord('z'):
                a -= 26
            encrypted += chr(a)
            i = (i + 1) % len(key)
        else:
            encrypted += ch
    print(encrypted)


问:
how to get the response object from a single query in cloud firestore using nodejs?
I am trying to query in cloud firestore and trying to extract document id and there is one other value also called cc i am able to extract the information but using .forEach and but i wanted to ask is there another way to do it here is my query</p>

```<code>const recipient = await db
    .collection("Active")
    .where("office", "==", "d")
    .where("template", "==", "dt")
    .where("attachment.Name.value", "==", "xyz")
    .get();

const id = [];
  const cc = [];
  recipient.forEach((doc) => {
    id.push(doc.id);
    cc.push(doc.data().cc);
    // console.log(JSON.stringify(doc.data()));
  });
</code>```

答:
If there is only one document in the query result,

const recipient = await db
    .collection("Active")
    .where("office", "==", "d")
    .where("template", "==", "dt")
    .where("attachment.Name.value", "==", "xyz")
    .get();

const id = [];
const cc = [];

id.push(recipient.docs[0].id);
cc.push(recipient.docs[0].data().cc);```

Body:
I am trying to query in cloud firestore and trying to extract document id and there is one other value also called cc i am able to extract the information but using .forEach and but i wanted to ask is there another way to do it here is my query

const recipient = await db
    .collection("Active")
    .where("office", "==", "d")
    .where("template", "==", "dt")
    .where("attachment.Name.value", "==", "xyz")
    .get();

const id = [];
  const cc = [];
  recipient.forEach((doc) => {
    id.push(doc.id);
    cc.push(doc.data().cc);
    // console.log(JSON.stringify(doc.data()));
  });


问:
What does CG_INLINE do?
I was poking around the definitions for things like CGPoint for hints on how to create my own functions but I don't know the purpose of CG_INLINE. What is happening behind the scenes here?

```<code>CG_INLINE CGPoint
CGPointMake(CGFloat x, CGFloat y)
{
  CGPoint p; p.x = x; p.y = y; return p;
}

CG_INLINE CGSize
CGSizeMake(CGFloat width, CGFloat height)
{
  CGSize size; size.width = width; size.height = height; return size;
}
</code>```

答: CG_INLINE is a #define for static inline.  This causes the compiler to create the code for the function inline, rather that creating a function call on the stack. See here and here for more information.

Title: What does CG_INLINE do?

Body:
I was poking around the definitions for things like CGPoint for hints on how to create my own functions but I don't know the purpose of CG_INLINE. What is happening behind the scenes here?

CG_INLINE CGPoint
CGPointMake(CGFloat x, CGFloat y)
{
  CGPoint p; p.x = x; p.y = y; return p;
}

CG_INLINE CGSize
CGSizeMake(CGFloat width, CGFloat height)
{
  CGSize size; size.width = width; size.height = height; return size;
}


问:
Vue Js transition only works when entering, not leaving
I'm trying to apply a bottom to top, and top to bottom vue js transition. The bottom to top works on enter, but I get no transition on leave.

Here is my css transition:

```<code>.slide-details-mobile-enter-active {
    @include transition(all 0.5s ease-in);
}

.slide-details-mobile-enter-active {
    @include transition(all 0.5s cubic-bezier(0, 1, 0.5, 1));
}

.slide-details-mobile-enter-to, .slide-details-mobile-leave {
    transform: translateY(0vh);
}

.slide-details-mobile-enter, .slide-details-mobile-leave-to {
    transform: translateY(100vh);
}
</code>```

The vue template looks like this:

```<code>    <transition :name="detailsTransition">
        <sc-fcst-details
            v-if="viewDetails"
            @changeactiveday="changeActiveFcstDay($event)">
        </sc-fcst-details>
    </transition>
</code>```

The first element in the vue template has the following css:

```<code>#fcst-details {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  overflow-y: hidden;
  z-index: 4;
}
</code>```

Any suggestions on why the leave transition does not work?

Also, I was hoping to use the top style instead of transform, but that wasn't working at all.

答:
This seems to be working fine for me:

```<code>.details-transition-enter-active, .details-transition-leave-active {
  transform: translateY(0vh);
  transition: all 0.4s ease-in-out;
}

.details-transition-enter, .details-transition-leave-to {
  transform: translateY(100vh);
}
</code>```

Give it a go

Later edit (using top instead of transform):

```<code>.details-transition-enter-active, .details-transition-leave-active {
  top: 0vh;
  transition: all 0.4s ease-in-out;
}

.details-transition-enter, .details-transition-leave-to {
  top: 100vh;
}
</code>```

And then remove the top: 0 from #fcst-details.

Body:
I'm trying to apply a bottom to top, and top to bottom vue js transition. The bottom to top works on enter, but I get no transition on leave.

Here is my css transition:

.slide-details-mobile-enter-active {
    @include transition(all 0.5s ease-in);
}

.slide-details-mobile-enter-active {
    @include transition(all 0.5s cubic-bezier(0, 1, 0.5, 1));
}

.slide-details-mobile-enter-to, .slide-details-mobile-leave {
    transform: translateY(0vh);
}

.slide-details-mobile-enter, .slide-details-mobile-leave-to {
    transform: translateY(100vh);
}

The vue template looks like this:

    <transition :name="detailsTransition">
        <sc-fcst-details
            v-if="viewDetails"
            @changeactiveday="changeActiveFcstDay($event)">
        </sc-fcst-details>
    </transition>

The first element in the vue template has the following css:

#fcst-details {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  overflow-y: hidden;
  z-index: 4;
}

Any suggestions on why the leave transition does not work?

Also, I was hoping to use the top style instead of transform, but that wasn't working at all.

Body:
This seems to be working fine for me:

.details-transition-enter-active, .details-transition-leave-active {
  transform: translateY(0vh);
  transition: all 0.4s ease-in-out;
}

.details-transition-enter, .details-transition-leave-to {
  transform: translateY(100vh);
}

Give it a go

Later edit (using top instead of transform):

.details-transition-enter-active, .details-transition-leave-active {
  top: 0vh;
  transition: all 0.4s ease-in-out;
}

.details-transition-enter, .details-transition-leave-to {
  top: 100vh;
}

And then remove the top: 0 from #fcst-details.


问:
jq null unix timestamps parsing issue
I'm trying to parse a big json file which I receive using curl.

By following this answer I could parse the next file:

```<code>$ cat test.json
{"items": [{"id": 110, "date1": 1590590723, "date2": 1590110000, "name": "somename"}]}
</code>```

using the next command:

```<code>TZ=Europe/Kyiv jq -r '.[] | .[] | .name + "; " + (.date1|strftime("%B %d %Y %I:%M%p")) + "; " + (.date2|strftime("%B %d %Y %I:%M%p"))' test.json
</code>```

Output is:

```<code>somename; May 27 2020 02:45PM; May 22 2020 01:13AM
</code>```

But when I try to parse the next file using the same command:

```<code>$ cat test2.json
{"items": [{"id": 110, "date1": 1590590723, "date2": null, "name": "somename"}]}
</code>```

Output is:

```<code>jq: error (at test2.json:1): strftime/1 requires parsed datetime inputs
</code>```

I could replace those null values using sed by some valid values before parsing. But maybe there is a better way to skip (ignore) those values, leaving nulls in output:

```<code>somename; May 27 2020 02:45PM; null
</code>```

答:
You could tweak your jq program so that it reads:

```<code>def tod: if type=="number" then strftime("%B %d %Y %I:%M%p") else tostring end;

.[] | .[] | .name + "; " + (.date1|tod) + "; " + (.date2|tod)
</code>```

An alternative would be:

```<code>def tod: (tonumber? | strftime("%B %d %Y %I:%M%p")) // null;

.[] | .[] | "\(.name); \(.date1|tod); \(.date2|tod)"
</code>```

Title: jq null unix timestamps parsing issue

Body:
I'm trying to parse a big json file which I receive using curl.

By following this answer I could parse the next file:

$ cat test.json
{"items": [{"id": 110, "date1": 1590590723, "date2": 1590110000, "name": "somename"}]}

using the next command:

TZ=Europe/Kyiv jq -r '.[] | .[] | .name + "; " + (.date1|strftime("%B %d %Y %I:%M%p")) + "; " + (.date2|strftime("%B %d %Y %I:%M%p"))' test.json

Output is:

somename; May 27 2020 02:45PM; May 22 2020 01:13AM

But when I try to parse the next file using the same command:

$ cat test2.json
{"items": [{"id": 110, "date1": 1590590723, "date2": null, "name": "somename"}]}

Output is:

jq: error (at test2.json:1): strftime/1 requires parsed datetime inputs

I could replace those null values using sed by some valid values before parsing. But maybe there is a better way to skip (ignore) those values, leaving nulls in output:

somename; May 27 2020 02:45PM; null

Body:
You could tweak your jq program so that it reads:

def tod: if type=="number" then strftime("%B %d %Y %I:%M%p") else tostring end;

.[] | .[] | .name + "; " + (.date1|tod) + "; " + (.date2|tod)

An alternative would be:

def tod: (tonumber? | strftime("%B %d %Y %I:%M%p")) // null;

.[] | .[] | "\(.name); \(.date1|tod); \(.date2|tod)"


问:
How to convert json output to array/list using Powershell (to json output)
Want to convert json output to array or list using Powershell.

I have tried converting the output using ConvertFrom-Json, then fetching the key Name and Values.  Need suggestion.

json Output:

```<code>{
    "demo1": {
        "type": [
            "tuple",
            [
                [
                    "list",
                    "string"
                ],
                [
                    "list",
                    "string"
                ]
            ]
        ],
        "value": [
            [
                "123"
            ],
            [
                "456"
            ]
        ]
    },
    "demo2": {
        "type": [
            "tuple",
            [
                "string",
                "string"
            ]
        ],
        "value": [
            "abc",
            "xyz"
        ]
    }
}
</code>```

Using Powershell want to convert it as below:

```<code>demo1 = [["123"],["456"]]
demo2 = ["abc","xyz"]
</code>```

Thanks in advance.

答:
It should be something like:

```<code>$t = '{
    "demo1": {
        "type": [
            "tuple",
            [
                [
                    "list",
                    "string"
                ],
                [
                    "list",
                    "string"
                ]
            ]
        ],
        "value": [
            [
                "123"
            ],
            [
                "456"
            ]
        ]
    },
    "demo2": {
        "type": [
            "tuple",
            [
                "string",
                "string"
            ]
        ],
        "value": [
            "abc",
            "xyz"
        ]
    }
}'

$t = ConvertFrom-Json $t

$t | Get-Member | Where-Object {$_.MemberType -eq 'NoteProperty'} | foreach {
$element = $_.Name

echo 'Property Name: '
echo $element
echo 'Elements: '
echo ($t.$element.value | ConvertTo-Json -Depth 99)

}
</code>```

At this point, powershell core seems to behave slightly different than v3-5, so you while powershell core will give you directly the correct result older versions will need some extra handling at this point, see here: Why does powershell give different result in one-liner than two-liner when converting JSON?

Body:
Want to convert json output to array or list using Powershell.

I have tried converting the output using ConvertFrom-Json, then fetching the key Name and Values.  Need suggestion.

json Output:

{
    "demo1": {
        "type": [
            "tuple",
            [
                [
                    "list",
                    "string"
                ],
                [
                    "list",
                    "string"
                ]
            ]
        ],
        "value": [
            [
                "123"
            ],
            [
                "456"
            ]
        ]
    },
    "demo2": {
        "type": [
            "tuple",
            [
                "string",
                "string"
            ]
        ],
        "value": [
            "abc",
            "xyz"
        ]
    }
}

Using Powershell want to convert it as below:

demo1 = [["123"],["456"]]
demo2 = ["abc","xyz"]

Thanks in advance.

Body:
It should be something like:

$t = '{
    "demo1": {
        "type": [
            "tuple",
            [
                [
                    "list",
                    "string"
                ],
                [
                    "list",
                    "string"
                ]
            ]
        ],
        "value": [
            [
                "123"
            ],
            [
                "456"
            ]
        ]
    },
    "demo2": {
        "type": [
            "tuple",
            [
                "string",
                "string"
            ]
        ],
        "value": [
            "abc",
            "xyz"
        ]
    }
}'

$t = ConvertFrom-Json $t

$t | Get-Member | Where-Object {$_.MemberType -eq 'NoteProperty'} | foreach {
$element = $_.Name

echo 'Property Name: '
echo $element
echo 'Elements: '
echo ($t.$element.value | ConvertTo-Json -Depth 99)

}

At this point, powershell core seems to behave slightly different than v3-5, so you while powershell core will give you directly the correct result older versions will need some extra handling at this point, see here: Why does powershell give different result in one-liner than two-liner when converting JSON?


问:
How can I pass parameters to inventory script from Ansible Tower Survey instead of configuration file
What I managed to do at the moment, is to pass the parameters to the script via a configuration file.

Is it possible to pass them directly from Tower Template Survey?

The Python script is located in a SCM System.

```<code>myscript.py
config.ini
</code>```

答:
You can access a survey variable the same way as any variable in ansible
For example
Passing a password via survey
Answer varaible name that you set can be used for getting value of the variable in the survey
https://docs.ansible.com/ansible-tower/latest/html/userguide/job_templates.html#create-a-survey

Body:
What I managed to do at the moment, is to pass the parameters to the script via a configuration file.

Is it possible to pass them directly from Tower Template Survey?

The Python script is located in a SCM System.

myscript.py
config.ini


问:
url rewriting + Asp.Net Login Form = Death
on our site we do url rewriting to generate massive amounts of database generated pages. on every page, there is a Login control for users. like this:

Internal aspx page: /DB.aspx?id=123
User visible url: /ABC/123.aspx, /ABC/456.aspx ... (url rewritten)

unfortunately, the  tag on each page has an action attribute of "DB.aspx?id=123". when the user clicks the button the browser is posting to /ABC/DB.aspx?id=123 which of course does not exist.

solutions i tried:
1. change the action attribute by subclassing HtmlForm. this destroys the all other forms on the site.
2. remove the action attribute (so that the browser is always posting to the same url). this works on the rewritten pages but on "/" (the default.aspx in the root dir) i get a message that the verb post is not allowed on "/" (iis 6 and i have no control over mappings)

anybody?

答:
I never did it, but I saw the code using Reflector and I guess you can fix it this way:

On the page:

```<code>this.Form.Action = null;
</code>```

or:

```<code>this.Form.SetAttribute("action", null);
</code>```

If that doesn't work, just set the path you want:

this.Form.SetAttribute("action", "ABC/123.aspx");

Body:
I never did it, but I saw the code using Reflector and I guess you can fix it this way:

On the page:

this.Form.Action = null;

or:

this.Form.SetAttribute("action", null);

If that doesn't work, just set the path you want:

this.Form.SetAttribute("action", "ABC/123.aspx");

OwnerDisplayName: diegojancic


问:
Move mails to folders with the sender's name
It is possible to create a rule which, for a sender, moves all the mails to the folder of your choice (for example, it creates a folder with the name of the sender).

If I want that for all the expeditors, I need to repeat the rule creation for each sender.

What I'd wish would be a macro "meta-rule" for each sender to have a folder with their name with the corresponding mails sorted.

I tried to start from the topic Outlook template rule to sort mails among directories.

I wrote this:

```<code>Sub RulesForFolders(m As MailItem)
Dim fldr As Outlook.Folder
For Each fldr In GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Folders
    if fldr.Name Like m.SenderName Then m.MoveTo(SenderName)
    else folders.add(m.SenderName)
Next
Set fldr = Nothing
End Sub
</code>```

答:
First of all, I'd suggest starting from the NewMailEx event of the Application class which is fired when a new item is received in the Inbox. This event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The EntryIDsCollection string contains the Entry ID that corresponds to that item. The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item.

To find the folder with a sender name you can iterate over all subfolders recursively:

```<code>Private Sub processFolder(ByVal oParent As Outlook.MAPIFolder)

        Dim oFolder As Outlook.MAPIFolder
        Dim oMail As Outlook.MailItem

        For Each oMail In oParent.Items

        'Get your data here ...

        Next

        If (oParent.Folders.Count > 0) Then
            For Each oFolder In oParent.Folders
                processFolder oFolder
            Next
        End If
End Sub
</code>```

Finally, I'd recommend delving deeper with VBA by starting from the Getting started with VBA in Office article.

You can also use the following code if you don't need to iterate over all folders:

```<code>Sub RulesForFolders(m As MailItem)
Dim fldr As Outlook.Folder
Dim new_fldr As Outlook.Folder
Dim ns as Outlook.Namespace
Dim inbox as Outlook.Folder

Set ns = Application.GetNamespace("MAPI")
Set inbox = ns.GetDefaultFolder(olFolderInbox)

For Each fldr In inbox.Folders
    if InStr(fldr.Name,m.SenderName) > 0 Then
       m.MoveTo(fldr)
       Return
    End If
Next

Set new_fldr = folders.add(m.SenderName)
m.MoveTo(new_fldr)

Set fldr = Nothing
Set new_fldr = Nothing
Set inbox = Nothing
Set ns = Nothing

End Sub
</code>```

Body:
It is possible to create a rule which, for a sender, moves all the mails to the folder of your choice (for example, it creates a folder with the name of the sender).

If I want that for all the expeditors, I need to repeat the rule creation for each sender.

What I'd wish would be a macro "meta-rule" for each sender to have a folder with their name with the corresponding mails sorted.

I tried to start from the topic Outlook template rule to sort mails among directories.

I wrote this:

Sub RulesForFolders(m As MailItem)
Dim fldr As Outlook.Folder
For Each fldr In GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Folders
    if fldr.Name Like m.SenderName Then m.MoveTo(SenderName)
    else folders.add(m.SenderName)
Next
Set fldr = Nothing
End Sub

Body:
First of all, I'd suggest starting from the NewMailEx event of the Application class which is fired when a new item is received in the Inbox. This event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The EntryIDsCollection string contains the Entry ID that corresponds to that item. The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item.

To find the folder with a sender name you can iterate over all subfolders recursively:

Private Sub processFolder(ByVal oParent As Outlook.MAPIFolder)

        Dim oFolder As Outlook.MAPIFolder
        Dim oMail As Outlook.MailItem

        For Each oMail In oParent.Items

        'Get your data here ...

        Next

        If (oParent.Folders.Count > 0) Then
            For Each oFolder In oParent.Folders
                processFolder oFolder
            Next
        End If
End Sub

Finally, I'd recommend delving deeper with VBA by starting from the Getting started with VBA in Office article.

You can also use the following code if you don't need to iterate over all folders:

Sub RulesForFolders(m As MailItem)
Dim fldr As Outlook.Folder
Dim new_fldr As Outlook.Folder
Dim ns as Outlook.Namespace
Dim inbox as Outlook.Folder

Set ns = Application.GetNamespace("MAPI")
Set inbox = ns.GetDefaultFolder(olFolderInbox)

For Each fldr In inbox.Folders
    if InStr(fldr.Name,m.SenderName) > 0 Then
       m.MoveTo(fldr)
       Return
    End If
Next

Set new_fldr = folders.add(m.SenderName)
m.MoveTo(new_fldr)

Set fldr = Nothing
Set new_fldr = Nothing
Set inbox = Nothing
Set ns = Nothing

End Sub


问:
Problem with Swift compiler version in GX16u7
I'm trying to compile a GX project using Gx16 u7 in a mac running Xcode 11.3, I checked the swift installed version and it is 5.1.3 so it should not have problems but I still have.

This is the error that I'm getting when building using Xcode.

:0: error: module compiled with Swift 5.1.2 cannot be imported by the Swift 5.1 compiler: /Users/genexus/Library/GeneXus/GeneXus/16.0.138086_U7/iphonesimulator/GXFoundation.framework/Modules/GXFoundation.swiftmodule/x86_64-apple-ios-simulator.swiftmodule

Please I really need your help, thanks.

答:
According to this documentation for GeneXus V16 U7 you should install:

XCode   11.2(required)  11.3 (recommended)  with Swift 5.1.2

Could you try with a lower version of XCode (11.2) with Swift 5.1.2?


问:
Difference between `"%[^\n]"` and `"%[^\n]\n"` and `"%[^\n]%*c"` in C how do they work?
I could not find the answer anywhere else.

%[^\n] - When I run this one, scanf is getting input and terminating after I press enter. ( Probably leaving \n in the input system)

%[^\n]\n -  this one is getting the input but scanf is NOT terminating immediately after I press enter like the one above. I hit more enter and it makes more newlines. When I give a character and then press enter it finally terminates. Example:

```<code>int main(void)
{
    char s[100];

    scanf("%[^\n]\n", s);

    printf("%s", s);

    return 0;
}
</code>```

The results:

Last one:

%[^\n]%*c -  When I give some input and press enter. scanf immediately terminates.

How do those 3 work and how do they differ?

答:
All 3 format begin with "%[^\n]".

"%[^\n]" is poor code2 that lacks a width limit and is susceptible to buffer overrun.  Use a width limit like "%99[^\n]"  with char s[100];.

"%[...]" does not consume leading whitespace like many other specifiers.

This specifier directs reading input until a '\n'1 is encountered.  The '\n' is put back into stdin.  All other characters are saved in the matching destination's array s.

If no characters were read (not counting the '\n'), the specifier fails and scanf() returns without changing s - rest of the format is not used.  No null character appended.

If characters were read, they are saved and a null character is appended to s and scanning continues with the next portion of the format.

"\n" acts just like " ",  "\t", "any_white_space_chracter" and reads and tosses 0 or more whitespace characters.  It continues to do so until a non-white-space1 is read.  That non-whitespace character is put back into stdin.

Given line buffered input, this means a line with  non-whitespace following input is needed to see the next non-whitespace and allow scanf() to move on.

With scanf(), a "\n" at the end of a format is bad and caused OP's problem.

"%*c" reads 1 character1 and throws it away - even if it is not a '\n'.  This specifier does not contribute to the return count due to the '*'.

A better alternative is to use fgets().

```<code>char s[100];
if (fgets(s, sizeof s, stdin)) {
   s[strcspn(s, "\n")] = '\0';  // To lop off potential trailing \n
</code>```

A lesser alternative is

```<code>char s[100] = { 0 };
scanf("%99[^\n]", s);
// With a separate scanf ....
scanf("%*1[\n]");  // read the next character if it is a \n and toss it.
</code>```

1 ...  or end-of-file or rare input error.

2 IMO, worse than gets().

Body:
I could not find the answer anywhere else.

%[^\n] - When I run this one, scanf is getting input and terminating after I press enter. ( Probably leaving \n in the input system)

%[^\n]\n -  this one is getting the input but scanf is NOT terminating immediately after I press enter like the one above. I hit more enter and it makes more newlines. When I give a character and then press enter it finally terminates. Example:

int main(void)
{
    char s[100];

    scanf("%[^\n]\n", s);

    printf("%s", s);

    return 0;
}

The results:

Last one:

%[^\n]%*c -  When I give some input and press enter. scanf immediately terminates.

How do those 3 work and how do they differ?

Body:
All 3 format begin with "%[^\n]".

"%[^\n]" is poor code2 that lacks a width limit and is susceptible to buffer overrun.  Use a width limit like "%99[^\n]"  with char s[100];.

"%[...]" does not consume leading whitespace like many other specifiers.

This specifier directs reading input until a '\n'1 is encountered.  The '\n' is put back into stdin.  All other characters are saved in the matching destination's array s.

If no characters were read (not counting the '\n'), the specifier fails and scanf() returns without changing s - rest of the format is not used.  No null character appended.

If characters were read, they are saved and a null character is appended to s and scanning continues with the next portion of the format.

"\n" acts just like " ",  "\t", "any_white_space_chracter" and reads and tosses 0 or more whitespace characters.  It continues to do so until a non-white-space1 is read.  That non-whitespace character is put back into stdin.

Given line buffered input, this means a line with  non-whitespace following input is needed to see the next non-whitespace and allow scanf() to move on.

With scanf(), a "\n" at the end of a format is bad and caused OP's problem.

"%*c" reads 1 character1 and throws it away - even if it is not a '\n'.  This specifier does not contribute to the return count due to the '*'.

A better alternative is to use fgets().

char s[100];
if (fgets(s, sizeof s, stdin)) {
   s[strcspn(s, "\n")] = '\0';  // To lop off potential trailing \n

A lesser alternative is

char s[100] = { 0 };
scanf("%99[^\n]", s);
// With a separate scanf ....
scanf("%*1[\n]");  // read the next character if it is a \n and toss it.

1 ...  or end-of-file or rare input error.

2 IMO, worse than gets().


问:
UNITY | Method return null (A: Order of execution)
Im new to c# and Unity, can't solve this problem about 2 days.

I don't know why, but in ItemOnGround class on Debug.Log line always getting this error:

NullReferenceException: Object reference not set to an instance of an object

I tried use FetchItemById method, but it still wont work. Even if i just copy and paste everything from Slot class, it still wont work. I tried to attach it to different GameObject but it still wont work. Is it some thread problem or i do something wrong?

Thank you for any help

Here how scripts attached in Unity :  Screenshot

So i have 3 .cs

ItemDatabase

```<code>using System.Collections;
using System.Collections.Generic;
using System.IO;
using LitJson;
using UnityEngine;

public class ItemDatabase : MonoBehaviour
{
    private List<Item> database = new List<Item>();
    private JsonData itemData;

    void Start()
    {
        SetLanguagePath();
        ConstructItemDatabase();
    }

    public void SetLanguagePath()
    {
        itemData = JsonMapper.ToObject(File.ReadAllText(Application.streamingAssetsPath + "/en_Items.json"));
    }

    public Item FetchItemById(int id)
    {
        for (int i = 0; i < database.Count; i++)
        {
            if (database[i].Id == id)
            {
                return database[i];
            }
        }
        return null;
    }

    public Item FetchItemBySlug(string slug)
    {
        for (int i = 0; i < database.Count; i++)
        {
            if(database[i].Slug == slug)
            {
                return database[i];
            }
        }
        return null;
    }

    void ConstructItemDatabase()
    {
        for (int i = 0; i < itemData.Count; i++)
        {
            Item newItem = new Item();
            newItem.Id = (int)itemData[i]["id"];
            newItem.Title = itemData[i]["title"].ToString();
            newItem.Value = (int)itemData[i]["value"];
            newItem.Power = (int)itemData[i]["stats"]["power"];
            newItem.Defense = (int)itemData[i]["stats"]["defense"];
            newItem.Vitality = (int)itemData[i]["stats"]["vitality"];
            newItem.Description = itemData[i]["description"].ToString();
            newItem.Stackable = (bool)itemData[i]["stackable"];
            newItem.Type = itemData[i]["type"].ToString();
            newItem.Slug = itemData[i]["slug"].ToString();
            newItem.Sprite = Resources.Load<Sprite>("Sprites/Items/" + newItem.Slug);

            database.Add(newItem);
        }
    }
}

public class Item
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Value { get; set; }
    public int Power { get; set; }
    public int Defense { get; set; }
    public int Vitality { get; set; }
    public string Description { get; set; }
    public bool Stackable { get; set; }
    public string Type { get; set; }
    public string Slug { get; set; }
    public Sprite Sprite { get; set; }
}
</code>```

Slot

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Slot : MonoBehaviour
{
    bool hasItem = true;

    private void Start()
    {
        InitializeSlot();
    }

    void InitializeSlot()
    {
        if (hasItem)
        {
            ItemDatabase database = GameObject.Find("Inventory").GetComponent<ItemDatabase>();
            Item item = database.FetchItemById(0);

            Debug.Log(item.Slug);
        }
    }
}
</code>```

ItemOnGround

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemOnGround : MonoBehaviour
{
    void Start()
    {
        InitializeItem();
    }

    void InitializeItem()
    {
        ItemDatabase database = GameObject.Find("Inventory").GetComponent<ItemDatabase>();
        Item item = database.FetchItemBySlug("apple");

        Debug.Log(item.Slug);
    }
}
</code>```

And en_Items.json

```<code>[
    {
        "id": 0,
        "title": "Apple",
        "value": 1,
        "stats": {
            "power": 1,
            "defense": 1,
            "vitality": 10
        },
        "description": "Tasty apple",
        "stackable": true,
        "type": "food",
        "slug":  "apple"
    },
    {
        "id": 1,
        "title": "Plum",
        "value": 1,
        "stats": {
            "power": 1,
            "defense": 1,
            "vitality": 10
        },
        "description": "Juicy plum",
        "stackable": true,
        "type": "food",
        "slug": "plum"
    }
]
</code>```

答:
Unity Engine has a specific Order of Execution.

This defines the order at which Unity Callbacks are executed in every script.

For instance, all the Awake() callbacks in your MonoBehaviours will be executed before any Start() callback.

That said, it doesn't mean that it governs the order of execution of individual Start() callbacks from different behaviours.

In your example. It is possible that the Start() callback of the ItemOnGround behaviour is invoked before ItemDatabase's. In which case, you're making calls to an ItemDatabase that hasn't been initialized yet. So here is what I suggest:

Approach 1:

Knowing that Awake() is called before Start() you could initialize your ItemDatabase by changing Start() to:

```<code>void Awake()
{
    SetLanguagePath();
    ConstructItemDatabase();
}
</code>```

Approach 2:

You could adjust the Script Execution Order settings. in Edit > Project Settings.

This allows you to give a priority order to each of your MonoBehaviours.

By giving the script ItemDatabase a lower number (higher priority) than ItemOnGround's, you're telling the engine to invoke ItemDatabase.Start() before ItemOnGround.Start().

Body:
Im new to c# and Unity, can't solve this problem about 2 days.

I don't know why, but in ItemOnGround class on Debug.Log line always getting this error:

NullReferenceException: Object reference not set to an instance of an object

I tried use FetchItemById method, but it still wont work. Even if i just copy and paste everything from Slot class, it still wont work. I tried to attach it to different GameObject but it still wont work. Is it some thread problem or i do something wrong?

Thank you for any help

Here how scripts attached in Unity :  Screenshot

So i have 3 .cs

ItemDatabase

using System.Collections;
using System.Collections.Generic;
using System.IO;
using LitJson;
using UnityEngine;

public class ItemDatabase : MonoBehaviour
{
    private List<Item> database = new List<Item>();
    private JsonData itemData;

    void Start()
    {
        SetLanguagePath();
        ConstructItemDatabase();
    }

    public void SetLanguagePath()
    {
        itemData = JsonMapper.ToObject(File.ReadAllText(Application.streamingAssetsPath + "/en_Items.json"));
    }

    public Item FetchItemById(int id)
    {
        for (int i = 0; i < database.Count; i++)
        {
            if (database[i].Id == id)
            {
                return database[i];
            }
        }
        return null;
    }

    public Item FetchItemBySlug(string slug)
    {
        for (int i = 0; i < database.Count; i++)
        {
            if(database[i].Slug == slug)
            {
                return database[i];
            }
        }
        return null;
    }

    void ConstructItemDatabase()
    {
        for (int i = 0; i < itemData.Count; i++)
        {
            Item newItem = new Item();
            newItem.Id = (int)itemData[i]["id"];
            newItem.Title = itemData[i]["title"].ToString();
            newItem.Value = (int)itemData[i]["value"];
            newItem.Power = (int)itemData[i]["stats"]["power"];
            newItem.Defense = (int)itemData[i]["stats"]["defense"];
            newItem.Vitality = (int)itemData[i]["stats"]["vitality"];
            newItem.Description = itemData[i]["description"].ToString();
            newItem.Stackable = (bool)itemData[i]["stackable"];
            newItem.Type = itemData[i]["type"].ToString();
            newItem.Slug = itemData[i]["slug"].ToString();
            newItem.Sprite = Resources.Load<Sprite>("Sprites/Items/" + newItem.Slug);

            database.Add(newItem);
        }
    }
}

public class Item
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Value { get; set; }
    public int Power { get; set; }
    public int Defense { get; set; }
    public int Vitality { get; set; }
    public string Description { get; set; }
    public bool Stackable { get; set; }
    public string Type { get; set; }
    public string Slug { get; set; }
    public Sprite Sprite { get; set; }
}

Slot

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Slot : MonoBehaviour
{
    bool hasItem = true;

    private void Start()
    {
        InitializeSlot();
    }

    void InitializeSlot()
    {
        if (hasItem)
        {
            ItemDatabase database = GameObject.Find("Inventory").GetComponent<ItemDatabase>();
            Item item = database.FetchItemById(0);

            Debug.Log(item.Slug);
        }
    }
}

ItemOnGround

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemOnGround : MonoBehaviour
{
    void Start()
    {
        InitializeItem();
    }

    void InitializeItem()
    {
        ItemDatabase database = GameObject.Find("Inventory").GetComponent<ItemDatabase>();
        Item item = database.FetchItemBySlug("apple");

        Debug.Log(item.Slug);
    }
}

And en_Items.json

[
    {
        "id": 0,
        "title": "Apple",
        "value": 1,
        "stats": {
            "power": 1,
            "defense": 1,
            "vitality": 10
        },
        "description": "Tasty apple",
        "stackable": true,
        "type": "food",
        "slug":  "apple"
    },
    {
        "id": 1,
        "title": "Plum",
        "value": 1,
        "stats": {
            "power": 1,
            "defense": 1,
            "vitality": 10
        },
        "description": "Juicy plum",
        "stackable": true,
        "type": "food",
        "slug": "plum"
    }
]

Body:
Unity Engine has a specific Order of Execution.

This defines the order at which Unity Callbacks are executed in every script.

For instance, all the Awake() callbacks in your MonoBehaviours will be executed before any Start() callback.

That said, it doesn't mean that it governs the order of execution of individual Start() callbacks from different behaviours.

In your example. It is possible that the Start() callback of the ItemOnGround behaviour is invoked before ItemDatabase's. In which case, you're making calls to an ItemDatabase that hasn't been initialized yet. So here is what I suggest:

Approach 1:

Knowing that Awake() is called before Start() you could initialize your ItemDatabase by changing Start() to:

void Awake()
{
    SetLanguagePath();
    ConstructItemDatabase();
}

Approach 2:

You could adjust the Script Execution Order settings. in Edit > Project Settings.

This allows you to give a priority order to each of your MonoBehaviours.

By giving the script ItemDatabase a lower number (higher priority) than ItemOnGround's, you're telling the engine to invoke ItemDatabase.Start() before ItemOnGround.Start().


问:
What is the point of using types when declaring a variable in Typescript?
I'm newbie in Typescript, and I know its great benefits when working with big apps and teams : )

Let's suppose I have this TypeScript:

```<code>declare const num = 5: number;
</code>```

Why is that better than:

```<code>const num = 5
</code>```

Should I explicitly declare (with type) simple variables always in TypeScript?

Fortunately, the variable’s type is inferred from the data type of the value.
So can I use normal JS (like in the second example)?

答:
You are using typescript to avoid wrong value assignment. For instance, typescript will throw an error when you try to use a string for a number variable.

```<code>let num: number = 5;
</code>```

You can't change it to num = "this is a string";. Typescript will throw a type error.

Body:
I'm newbie in Typescript, and I know its great benefits when working with big apps and teams : )

Let's suppose I have this TypeScript:

declare const num = 5: number;

Why is that better than:

const num = 5

Should I explicitly declare (with type) simple variables always in TypeScript?

Fortunately, the variable’s type is inferred from the data type of the value.
So can I use normal JS (like in the second example)?

Body:
You are using typescript to avoid wrong value assignment. For instance, typescript will throw an error when you try to use a string for a number variable.

let num: number = 5;

You can't change it to num = "this is a string";. Typescript will throw a type error.


问:
QML console.log() and console.debug() don't write to console
I'm using Qt 5.6 on Fedora 23 and I noticed that console.log() and console.debug() don't write anything to console. My example code:

```<code>import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true

    Text {
        text: qsTr("Hello World")
        anchors.centerIn: parent

        Component.onCompleted: {
            console.warn("warn completed")
            console.log("log completed")
            console.error("error completed")
            console.debug("debug completed")
            console.exception("exception completed")
            console.info("info completed")
        }
    }
}
</code>```

prints to console:

```<code>QML debugging is enabled. Only use this in a safe environment.
qml: warn completed
qml: error completed
qml: exception completed
onCompleted (qrc:/main.qml:16)
qml: info completed
</code>```

so warn, error, exception, and info work fine. What am I doing wrong?

Edit #1:
Project is freshly created, all my sources:

main.cpp

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}
</code>```

project.pro

```<code>TEMPLATE = app

QT += qml quick
CONFIG += c++11

SOURCES += main.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Default rules for deployment.
include(deployment.pri)
</code>```

Edit #2:
Compile Output from Qt Creator shows that there are no QT_NO_DEBUG_OUTPUT, QT_NO_INFO_OUTPUT, or QT_NO_WARNING_OUTPUT:

```<code>14:43:36: Running steps for project project...
14:43:36: Configuration unchanged, skipping qmake step.
14:43:36: Starting: "/usr/bin/make"
g++ -c -pipe -g -std=gnu++0x -Wall -W -D_REENTRANT -fPIC -DQT_QML_DEBUG -DQT_QUICK_LIB -DQT_GUI_LIB -DQT_QML_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -I../project -I. -I../../Qt5.6.0/5.6/gcc_64/include -I../../Qt5.6.0/5.6/gcc_64/include/QtQuick -I../../Qt5.6.0/5.6/gcc_64/include/QtGui -I../../Qt5.6.0/5.6/gcc_64/include/QtQml -I../../Qt5.6.0/5.6/gcc_64/include/QtNetwork -I../../Qt5.6.0/5.6/gcc_64/include/QtCore -I. -I../../Qt5.6.0/5.6/gcc_64/mkspecs/linux-g++ -o main.o ../project/main.cpp
/home/krzys/Qt5.6.0/5.6/gcc_64/bin/rcc -name qml ../project/qml.qrc -o qrc_qml.cpp
g++ -c -pipe -g -std=gnu++0x -Wall -W -D_REENTRANT -fPIC -DQT_QML_DEBUG -DQT_QUICK_LIB -DQT_GUI_LIB -DQT_QML_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -I../project -I. -I../../Qt5.6.0/5.6/gcc_64/include -I../../Qt5.6.0/5.6/gcc_64/include/QtQuick -I../../Qt5.6.0/5.6/gcc_64/include/QtGui -I../../Qt5.6.0/5.6/gcc_64/include/QtQml -I../../Qt5.6.0/5.6/gcc_64/include/QtNetwork -I../../Qt5.6.0/5.6/gcc_64/include/QtCore -I. -I../../Qt5.6.0/5.6/gcc_64/mkspecs/linux-g++ -o qrc_qml.o qrc_qml.cpp
g++ -Wl,-z,origin -Wl,-rpath,\$ORIGIN -Wl,-rpath,/home/krzys/Qt5.6.0/5.6/gcc_64/lib -o project main.o qrc_qml.o   -L/home/krzys/Qt5.6.0/5.6/gcc_64/lib -lQt5Quick -lQt5Gui -lQt5Qml -lQt5Network -lQt5Core -lGL -lpthread
14:43:37: The process "/usr/bin/make" exited normally.
14:43:37: Elapsed time: 00:01.
</code>```

答:
I found a more convenient solution by adding one of the two - depending
on if you use Qt Quick 1 or 2 to the pro file (rebuild and run QMake again)
according to https://doc.qt.io/qt-5/qtquick-debugging.html:

```<code>Qt Quick 1: CONFIG+=declarative_debug
Qt Quick 2: CONFIG+=qml_debug
</code>```

To put it in your code it would look like:

project.pro

TEMPLATE = app

QT += qml quick
CONFIG += c++11 qml_debug #or CONFIG+=declarative_debug for QtQuick 1

SOURCES += main.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Default rules for deployment.
include(deployment.pri)
```

Now it might look like this:

Body:
I'm using Qt 5.6 on Fedora 23 and I noticed that console.log() and console.debug() don't write anything to console. My example code:

import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true

    Text {
        text: qsTr("Hello World")
        anchors.centerIn: parent

        Component.onCompleted: {
            console.warn("warn completed")
            console.log("log completed")
            console.error("error completed")
            console.debug("debug completed")
            console.exception("exception completed")
            console.info("info completed")
        }
    }
}

prints to console:

QML debugging is enabled. Only use this in a safe environment.
qml: warn completed
qml: error completed
qml: exception completed
onCompleted (qrc:/main.qml:16)
qml: info completed

so warn, error, exception, and info work fine. What am I doing wrong?

Edit #1:
Project is freshly created, all my sources:

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

project.pro

TEMPLATE = app

QT += qml quick
CONFIG += c++11

SOURCES += main.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Default rules for deployment.
include(deployment.pri)

Edit #2:
Compile Output from Qt Creator shows that there are no QT_NO_DEBUG_OUTPUT, QT_NO_INFO_OUTPUT, or QT_NO_WARNING_OUTPUT:

14:43:36: Running steps for project project...
14:43:36: Configuration unchanged, skipping qmake step.
14:43:36: Starting: "/usr/bin/make"
g++ -c -pipe -g -std=gnu++0x -Wall -W -D_REENTRANT -fPIC -DQT_QML_DEBUG -DQT_QUICK_LIB -DQT_GUI_LIB -DQT_QML_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -I../project -I. -I../../Qt5.6.0/5.6/gcc_64/include -I../../Qt5.6.0/5.6/gcc_64/include/QtQuick -I../../Qt5.6.0/5.6/gcc_64/include/QtGui -I../../Qt5.6.0/5.6/gcc_64/include/QtQml -I../../Qt5.6.0/5.6/gcc_64/include/QtNetwork -I../../Qt5.6.0/5.6/gcc_64/include/QtCore -I. -I../../Qt5.6.0/5.6/gcc_64/mkspecs/linux-g++ -o main.o ../project/main.cpp
/home/krzys/Qt5.6.0/5.6/gcc_64/bin/rcc -name qml ../project/qml.qrc -o qrc_qml.cpp
g++ -c -pipe -g -std=gnu++0x -Wall -W -D_REENTRANT -fPIC -DQT_QML_DEBUG -DQT_QUICK_LIB -DQT_GUI_LIB -DQT_QML_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -I../project -I. -I../../Qt5.6.0/5.6/gcc_64/include -I../../Qt5.6.0/5.6/gcc_64/include/QtQuick -I../../Qt5.6.0/5.6/gcc_64/include/QtGui -I../../Qt5.6.0/5.6/gcc_64/include/QtQml -I../../Qt5.6.0/5.6/gcc_64/include/QtNetwork -I../../Qt5.6.0/5.6/gcc_64/include/QtCore -I. -I../../Qt5.6.0/5.6/gcc_64/mkspecs/linux-g++ -o qrc_qml.o qrc_qml.cpp
g++ -Wl,-z,origin -Wl,-rpath,\$ORIGIN -Wl,-rpath,/home/krzys/Qt5.6.0/5.6/gcc_64/lib -o project main.o qrc_qml.o   -L/home/krzys/Qt5.6.0/5.6/gcc_64/lib -lQt5Quick -lQt5Gui -lQt5Qml -lQt5Network -lQt5Core -lGL -lpthread
14:43:37: The process "/usr/bin/make" exited normally.
14:43:37: Elapsed time: 00:01.

Body:
I found a more convenient solution by adding one of the two - depending
on if you use Qt Quick 1 or 2 to the pro file (rebuild and run QMake again)
according to https://doc.qt.io/qt-5/qtquick-debugging.html:

Qt Quick 1: CONFIG+=declarative_debug
Qt Quick 2: CONFIG+=qml_debug

To put it in your code it would look like:

project.pro

TEMPLATE = app

QT += qml quick
CONFIG += c++11 qml_debug #or CONFIG+=declarative_debug for QtQuick 1

SOURCES += main.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Default rules for deployment.
include(deployment.pri)

Now it might look like this:


问:
Start-Process with Process Priority in Loop doesn't recognize variable
I'm using FFmpeg with PowerShell.

I have a loop that goes through a folder of mpg files and grabs the names to a variable $inputName.

FFmpeg then converts each one to an mp4.

Works

Batch Processing

```<code>$files = Get-ChildItem "C:\Path\" -Filter *.mpg;

foreach ($f in $files) {

    $inputName = $f.Name; #name + extension
    $outputName = (Get-Item $inputName).Basename; #name only

    ffmpeg -y -i "C:\Users\Matt\Videos\$inputName" -c:v libx264 -crf 25 "C:\Users\Matt\Videos\$outputName.mp4"
}
</code>```

Not Working

Batch Processing with Process Priority

```<code>$files = Get-ChildItem "C:\Path\" -Filter *.mpg;

foreach ($f in $files) {

    $inputName = $f.Name; #name + extension
    $outputName = (Get-Item $inputName).Basename; #name only

    ($Process = Start-Process ffmpeg -NoNewWindow -ArgumentList '-y -i "C:\Users\Matt\Videos\$inputName" -c:v libx264 -crf 25 "C:\Users\Matt\Videos\$outputName.mp4"' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal;
    Wait-Process -Id $Process.id

}
</code>```

If I set the Process Priority using Start-Process PriorityClass, the $inputName variable is no longer recognized.

```<code>Error:
C:\Users\Matt\Videos\$inputName: No such file or directory
</code>```

答:
Lets go over a few basic things.

In powershell we love piping |, It allows use to pass the information from one command to another command.

A good example of this is the ForEach you have.

Instead of Foreach($F in $Files) you can pipe | into a foreach-object

```<code>Get-ChildItem "C:\Path\" -Filter *.mpg | Foreach-Object{
    $_
}
</code>```

When Piping | a command powershell automatically creates the variable $_ which is the object that is passed in the pipe |

The next thing is there are 2 types of quotes " and '.

If you use ' then everthing is taken literally. Example

```<code>$FirstName = "TestName"
'Hey There $FirstName'
</code>```

Will return

```<code>Hey There $FirstName
</code>```

While " allows you to use Variables in it. Example

```<code>$FirstName = "TestName"
'Hey There $FirstName'
</code>```

Will return

```<code>Hey There TestName
</code>```

Now one last thing before we fix this. In powershell we have a escape char ` aka a tick. Its located beside the number 1 on the keyboard with the tilde. You use it to allow the use of char that would otherwise break out of the qoutes. Example

```<code>"`"Hey There`""
</code>```

Would return

```<code>"Hey There"
</code>```

OK so now that we covered the basics lets fix up the script

```<code>Get-ChildItem "C:\Users\Matt\Videos\" -Filter *.mpg -File | Foreach-Object{
    ($Process = Start-Process ffmpeg -NoNewWindow -ArgumentList "-y -i `"$($_.FullName)`" -c:v libx264 -crf 25 `"C:\Users\Matt\Videos\$($_.Name)`"" -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal;
    Try{
        Wait-Process -Id $Process.id
    }catch{
    }
}
</code>```

In the case above I changed

Add -File to the Get-ChildItem to designate that you only want Files returned not folders

Pipe | into a Foreach-Object

Changed the Outside Brackets in the -ArgumentList to be double quotes " instead of literal quotes '

Removed the $InputName and $OutputName in favor of the Foreach-Object variable $_

Body:
I'm using FFmpeg with PowerShell.

I have a loop that goes through a folder of mpg files and grabs the names to a variable $inputName.

FFmpeg then converts each one to an mp4.

Works

Batch Processing

$files = Get-ChildItem "C:\Path\" -Filter *.mpg;

foreach ($f in $files) {

    $inputName = $f.Name; #name + extension
    $outputName = (Get-Item $inputName).Basename; #name only

    ffmpeg -y -i "C:\Users\Matt\Videos\$inputName" -c:v libx264 -crf 25 "C:\Users\Matt\Videos\$outputName.mp4"
}

Not Working

Batch Processing with Process Priority

$files = Get-ChildItem "C:\Path\" -Filter *.mpg;

foreach ($f in $files) {

    $inputName = $f.Name; #name + extension
    $outputName = (Get-Item $inputName).Basename; #name only

    ($Process = Start-Process ffmpeg -NoNewWindow -ArgumentList '-y -i "C:\Users\Matt\Videos\$inputName" -c:v libx264 -crf 25 "C:\Users\Matt\Videos\$outputName.mp4"' -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal;
    Wait-Process -Id $Process.id

}

If I set the Process Priority using Start-Process PriorityClass, the $inputName variable is no longer recognized.

Error:
C:\Users\Matt\Videos\$inputName: No such file or directory

Body:
Lets go over a few basic things.

In powershell we love piping |, It allows use to pass the information from one command to another command.

A good example of this is the ForEach you have.

Instead of Foreach($F in $Files) you can pipe | into a foreach-object

Get-ChildItem "C:\Path\" -Filter *.mpg | Foreach-Object{
    $_
}

When Piping | a command powershell automatically creates the variable $_ which is the object that is passed in the pipe |

The next thing is there are 2 types of quotes " and '.

If you use ' then everthing is taken literally. Example

$FirstName = "TestName"
'Hey There $FirstName'

Will return

Hey There $FirstName

While " allows you to use Variables in it. Example

$FirstName = "TestName"
'Hey There $FirstName'

Will return

Hey There TestName

Now one last thing before we fix this. In powershell we have a escape char ` aka a tick. Its located beside the number 1 on the keyboard with the tilde. You use it to allow the use of char that would otherwise break out of the qoutes. Example

"`"Hey There`""

Would return

"Hey There"

OK so now that we covered the basics lets fix up the script

Get-ChildItem "C:\Users\Matt\Videos\" -Filter *.mpg -File | Foreach-Object{
    ($Process = Start-Process ffmpeg -NoNewWindow -ArgumentList "-y -i `"$($_.FullName)`" -c:v libx264 -crf 25 `"C:\Users\Matt\Videos\$($_.Name)`"" -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal;
    Try{
        Wait-Process -Id $Process.id
    }catch{
    }
}

In the case above I changed

Add -File to the Get-ChildItem to designate that you only want Files returned not folders

Pipe | into a Foreach-Object

Changed the Outside Brackets in the -ArgumentList to be double quotes " instead of literal quotes '

Removed the $InputName and $OutputName in favor of the Foreach-Object variable $_


问:
What is the easiest way to represent a DFA transition table in C# code?
Here is what I go so far, so in DFAs right, you have states and you have transitions between those states, to go from state A to state B you consume a symbol ex: 'a'. Now I am trying to write a DFA transition function that takes a current state (int) and a transition symbol (char) and returns the next state (int), Now to do that you have to have access to a transition table, now what is the best way to represent that transition table, Here is what I got so far:

```<code>Dictionary<int, Dictionary<char, int>> transitionMap = new Dictionary<int, Dictionary<char, int>>();
</code>```

that is my transition map, it's a dictionary where the first int key is current state and nested dictionary consists of symbol consumed and the other int is the next state that I have to return, The problem I'm running into is that a dictionary Can't have duplicate keys (in this case state) and DFAs can have multiple transitions for same state. For example, if I try to do this:

```<code>  Dictionary<char, int> dict = new Dictionary<char, int>();
  dict.Add('a', 1);  // 'a' here is the symbol consumed to go to state 1 from state 0
  transitionMap.Add(0, dict); // 0 is the current state
</code>```

Now when I add this, It works, but when I try to add another transition for state 0, It doesn't because Dictionaries can't have duplicate keys, So what to do here?

答:
Yeah, so I had a problem understanding dictionaries, I got it now:

```<code>if (transitionMap.ContainsKey(state))
{
      Dictionary<char, int> res = new Dictionary<char, int>();
      transitionMap.TryGetValue(state, out res);
      res.Add(symbol, nextState);
      transitionMap[state] = res;
}
</code>```

I just had to check if It the state existed, then grab the the dictionary, add another transition to it and add to the transitionMap.

Body:
Here is what I go so far, so in DFAs right, you have states and you have transitions between those states, to go from state A to state B you consume a symbol ex: 'a'. Now I am trying to write a DFA transition function that takes a current state (int) and a transition symbol (char) and returns the next state (int), Now to do that you have to have access to a transition table, now what is the best way to represent that transition table, Here is what I got so far:

Dictionary<int, Dictionary<char, int>> transitionMap = new Dictionary<int, Dictionary<char, int>>();

that is my transition map, it's a dictionary where the first int key is current state and nested dictionary consists of symbol consumed and the other int is the next state that I have to return, The problem I'm running into is that a dictionary Can't have duplicate keys (in this case state) and DFAs can have multiple transitions for same state. For example, if I try to do this:

  Dictionary<char, int> dict = new Dictionary<char, int>();
  dict.Add('a', 1);  // 'a' here is the symbol consumed to go to state 1 from state 0
  transitionMap.Add(0, dict); // 0 is the current state

Now when I add this, It works, but when I try to add another transition for state 0, It doesn't because Dictionaries can't have duplicate keys, So what to do here?

Body:
Yeah, so I had a problem understanding dictionaries, I got it now:

if (transitionMap.ContainsKey(state))
{
      Dictionary<char, int> res = new Dictionary<char, int>();
      transitionMap.TryGetValue(state, out res);
      res.Add(symbol, nextState);
      transitionMap[state] = res;
}

I just had to check if It the state existed, then grab the the dictionary, add another transition to it and add to the transitionMap.


问:
Trying to display text when input values are empty for form validation
I am diving into form validation for the first time.  Right now, when there are empty values in any of the input boxes, the borders highlight themselves into red.

However, I tried to get a message to display underneath each input box with its respective error, but no luck. I added that line of code in the conditionals for each function.

Was wondering if someone can take a look and see what is wrong and why there message is not displaying.

function customerFormValidation() {
  reason = "";
  reason += validateName(customer_form.firstname);
  reason += validateEmail(customer_form.email);
  reason += validatePhone(customer_form.phone);
  reason += validateAddress(customer_form.address);
  reason += validateCity(customer_form.city);
  reason += validateState(customer_form.state);
  reason += validateZip(customer_form.zip);

  console.log(reason);
  if (reason.length > 0) {
    return false;
  } else {
    return false;
  }
}

function validateName(firstname) {
  var error = "";
  if (firstname.value == "") {
    document.getElementById("firstname").style.display = "block";
    document.getElementById("firstname").innerText = "Please enter your first name";
    document.getElementById("firstname").style.borderColor = "red";
    document.getElementById("firstname").focus();
  } else {
    firstname.style.background = 'White';
    document.getElementById('firstname').innerHTML = "";
  }
  return error;
}

function validateEmail(email) {
  var error = "";
  if (email.value == "") {
    document.getElementById("email").style.display = "block";
    document.getElementById("email").innerText = "Please enter an email address";
    document.getElementById("email").style.borderColor = "red";
    document.getElementById("email").focus();
  } else {
    email.style.background = 'White';
    document.getElementById('email').innerHTML = "";
  }
  return error;
}

function validatePhone(phone) {
  var error = "";
  if (phone.value == "") {
    document.getElementById("phone").style.display = "block";
    document.getElementById("phone").innerText = "Please enter a phone number";
    document.getElementById("phone").style.borderColor = "red";
    document.getElementById("phone").focus();
  } else {
    phone.style.background = "White";
    document.getElementById("phone").innerHTML = "";
  }
  return error;
}

function validateAddress(address) {
  var error = "";
  if (address.value == "") {
    document.getElementById("address").style.display = "block";
    document.getElementById("address").innerText = "Please enter an address";
    document.getElementById("address").style.borderColor = "red";
    document.getElementById("address").focus();
  } else {
    address.style.background = "White";
    document.getElementById("address").innerHTML = "";
  }
  return error;
}

function validateCity(city) {
  var error = "";
  if (address.value == "") {
    document.getElementById("city").style.display = "block";
    document.getElementById("city").innerText = "Please enter your city";
    document.getElementById("city").style.borderColor = "red";
    document.getElementById("city").focus();
  } else {
    city.style.background = "White";
    document.getElementById("city").innerHTML = "";
  }
  return error;
}

function validateState(state) {
  var error = "";
  if (state.value == "") {
    document.getElementById("state").style.display = "block";
    document.getElementById("state").innerText = "Please your state";
    document.getElementById("state").style.borderColor = "red";
    document.getElementById("state").focus();
  } else {
    state.style.background = "White";
    document.getElementById("state").innerHTML = "";
  }
  return error;
}

function validateZip(zip) {
  var error = "";
  if (zip.value == "") {
    document.getElementById("zip").style.display = "block";
    document.getElementById("zip").innerText = "Please your zip code";
    document.getElementById("zip").style.borderColor = "red";
    document.getElementById("zip").focus();
  } else {
    zip.style.background = "White";
    document.getElementById("zip").innerHTML = "";
  }
  return error;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="customer_form" onsubmit="return customerFormValidation(this)" action="">
  <h1 style="text-align: center">Billing Address</h1>
  <div class="row">
    <label for="fname"><i class="fa fa-user"></i> Full Name</label>
    <input type="text" id="firstname" name="firstname" placeholder="John M. Doe">
    <label for="email"><i class="fa fa-envelope"></i> Email</label>
    <input type="text" id="email" name="email" placeholder="john@example.com">
    <label for="phone"><i class="fa fa-address-card-o"></i> Phone #</label>
    <input type="text" id="phone" name="phone" placeholder="(123)-456-7890">
    <label for="adr"><i class="fa fa-address-card-o"></i> Address</label>
    <input type="text" id="address" name="address" placeholder="542 W. 15th Street">
    <label for="city"><i class="fa fa-institution"></i> City</label>
    <input type="text" id="city" name="city" placeholder="New York">

    <div class="col-50">
      <label for="state">State</label>
      <input type="text" id="state" name="state" placeholder="NY">
    </div>
    <div class="col-50">
      <label for="zip">Zip</label>
      <input type="text" id="zip" name="zip" placeholder="10001">
    </div>

  </div>
  <button class="fa orange btn" type="submit" onclick="HideForm()" id="customerBtn">Next</button>

</form></code>```

答:
The elements that you are trying to enter the innerText into are the actual input fields. You have to add an extra element for each input field. On the example of firstname:

```<code><input type="text" id="firstname" name="firstname" placeholder="John M. Doe">
<div id="firstnameError" style="display: none"></div>
</code>```

And then in your checking function just change the the element ID from firstname to the new div firstnameError:

```<code>document.getElementById("firstnameError").style.display = "block";
document.getElementById("firstnameError").innerText = "Please enter your first name";
document.getElementById("firstnameError").style.borderColor = "red";
</code>```

Same goes for the rest of the fields. Other than that your code seems fine.

Body:
I am diving into form validation for the first time.  Right now, when there are empty values in any of the input boxes, the borders highlight themselves into red.

However, I tried to get a message to display underneath each input box with its respective error, but no luck. I added that line of code in the conditionals for each function.

Was wondering if someone can take a look and see what is wrong and why there message is not displaying.

function customerFormValidation() {
  reason = "";
  reason += validateName(customer_form.firstname);
  reason += validateEmail(customer_form.email);
  reason += validatePhone(customer_form.phone);
  reason += validateAddress(customer_form.address);
  reason += validateCity(customer_form.city);
  reason += validateState(customer_form.state);
  reason += validateZip(customer_form.zip);

  console.log(reason);
  if (reason.length > 0) {
    return false;
  } else {
    return false;
  }
}

function validateName(firstname) {
  var error = "";
  if (firstname.value == "") {
    document.getElementById("firstname").style.display = "block";
    document.getElementById("firstname").innerText = "Please enter your first name";
    document.getElementById("firstname").style.borderColor = "red";
    document.getElementById("firstname").focus();
  } else {
    firstname.style.background = 'White';
    document.getElementById('firstname').innerHTML = "";
  }
  return error;
}

function validateEmail(email) {
  var error = "";
  if (email.value == "") {
    document.getElementById("email").style.display = "block";
    document.getElementById("email").innerText = "Please enter an email address";
    document.getElementById("email").style.borderColor = "red";
    document.getElementById("email").focus();
  } else {
    email.style.background = 'White';
    document.getElementById('email').innerHTML = "";
  }
  return error;
}

function validatePhone(phone) {
  var error = "";
  if (phone.value == "") {
    document.getElementById("phone").style.display = "block";
    document.getElementById("phone").innerText = "Please enter a phone number";
    document.getElementById("phone").style.borderColor = "red";
    document.getElementById("phone").focus();
  } else {
    phone.style.background = "White";
    document.getElementById("phone").innerHTML = "";
  }
  return error;
}

function validateAddress(address) {
  var error = "";
  if (address.value == "") {
    document.getElementById("address").style.display = "block";
    document.getElementById("address").innerText = "Please enter an address";
    document.getElementById("address").style.borderColor = "red";
    document.getElementById("address").focus();
  } else {
    address.style.background = "White";
    document.getElementById("address").innerHTML = "";
  }
  return error;
}

function validateCity(city) {
  var error = "";
  if (address.value == "") {
    document.getElementById("city").style.display = "block";
    document.getElementById("city").innerText = "Please enter your city";
    document.getElementById("city").style.borderColor = "red";
    document.getElementById("city").focus();
  } else {
    city.style.background = "White";
    document.getElementById("city").innerHTML = "";
  }
  return error;
}

function validateState(state) {
  var error = "";
  if (state.value == "") {
    document.getElementById("state").style.display = "block";
    document.getElementById("state").innerText = "Please your state";
    document.getElementById("state").style.borderColor = "red";
    document.getElementById("state").focus();
  } else {
    state.style.background = "White";
    document.getElementById("state").innerHTML = "";
  }
  return error;
}

function validateZip(zip) {
  var error = "";
  if (zip.value == "") {
    document.getElementById("zip").style.display = "block";
    document.getElementById("zip").innerText = "Please your zip code";
    document.getElementById("zip").style.borderColor = "red";
    document.getElementById("zip").focus();
  } else {
    zip.style.background = "White";
    document.getElementById("zip").innerHTML = "";
  }
  return error;
}

<form id="customer_form" onsubmit="return customerFormValidation(this)" action="">

Billing Address

     Full Name
    <input type="text" id="firstname" name="firstname" placeholder="John M. Doe">
     Email
    <input type="text" id="email" name="email" placeholder="john@example.com">
     Phone #
    <input type="text" id="phone" name="phone" placeholder="(123)-456-7890">
     Address
    <input type="text" id="address" name="address" placeholder="542 W. 15th Street">
     City
    <input type="text" id="city" name="city" placeholder="New York">

      State
      <input type="text" id="state" name="state" placeholder="NY">

      Zip
      <input type="text" id="zip" name="zip" placeholder="10001">

  <button class="fa orange btn" type="submit" onclick="HideForm()" id="customerBtn">Next</button>

</form>

Body:
The elements that you are trying to enter the innerText into are the actual input fields. You have to add an extra element for each input field. On the example of firstname:

<input type="text" id="firstname" name="firstname" placeholder="John M. Doe">
<div id="firstnameError" style="display: none"></div>

And then in your checking function just change the the element ID from firstname to the new div firstnameError:

document.getElementById("firstnameError").style.display = "block";
document.getElementById("firstnameError").innerText = "Please enter your first name";
document.getElementById("firstnameError").style.borderColor = "red";

Same goes for the rest of the fields. Other than that your code seems fine.


问:
Visual Studio, Nuget package sources, Order doesn't stick
for our work, we have three local nuget repos along with nuget.org and M$.  I tried to reorder them like this:

but when I saved that, then opened the settings again, my new order was gone:

What am I doing wrong?

答:
So this is indeed a bug in the VS 2017 and VS 2019 UI, in that it sometimes (often?) can't save your chosen order.  I poked around a bit, having been bitten by the same bug today myself, and the good news is that you can fix the package order yourself, outside of Visual Studio, because it's just stored in a text file on disk.

Close Visual Studio, and then go into C:\Users\[your name]\AppData\Roaming\NuGet\, and you'll find a NuGet.Config file that contains XML that looks something like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
        <add key="Microsoft Visual Studio Offline Packages" value="C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\" />
        <add key="My Local Packages" value="C:\Code\NugetPackages" />
        ...
     </packageSources>

     ...

 </configuration>
</code>```

Notice that those <add ... /> elements exactly match what you see in the Nuget Package Manager UI, in the same order.  So you can manually reorder the <add ... /> elements in this file to whatever order you want your package sources in, and save it; and both Nuget and Visual Studio will respect the new order you've chosen.

Body:
So this is indeed a bug in the VS 2017 and VS 2019 UI, in that it sometimes (often?) can't save your chosen order.  I poked around a bit, having been bitten by the same bug today myself, and the good news is that you can fix the package order yourself, outside of Visual Studio, because it's just stored in a text file on disk.

Close Visual Studio, and then go into C:\Users\[your name]\AppData\Roaming\NuGet\, and you'll find a NuGet.Config file that contains XML that looks something like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
        <add key="Microsoft Visual Studio Offline Packages" value="C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\" />
        <add key="My Local Packages" value="C:\Code\NugetPackages" />
        ...
     </packageSources>

     ...

 </configuration>

Notice that those <add ... /> elements exactly match what you see in the Nuget Package Manager UI, in the same order.  So you can manually reorder the <add ... /> elements in this file to whatever order you want your package sources in, and save it; and both Nuget and Visual Studio will respect the new order you've chosen.


问:
lang.NumberFormatException in android
I have the following code which does nothing but reading some values from a DB in a background thread and using the values I draw a Line chart using a jar.For the line chart I use for value for each array and the problem is that the third that I pass to the constructor that draws the LineChart is float....

```<code>float[] viteza;

String[] time;

int contor=0;
</code>```

```<code>public void onResume() {

    super.onResume();

    init_task = new InitTask();

    init_task.execute(db);

}

public class InitTask extends AsyncTask<DBAdapter,String, Void> {

    String TABLE_3;

    protected Void doInBackground(DBAdapter... db) {
        try {
            db[0].createDatabase();
            db[0].openDataBase();
            Cursor c = db[0].getCursor3(db[0].TABLE_3, user_id);

            String[] array=new String[2];
            viteza = new float[c.getCount()];
            time = new String[c.getCount()];

            if (c.moveToFirst()) {

                do {

                    publishProgress(c.getString(3),c.getString(4));
                    Thread.sleep(500);

                } while (c.moveToNext());

            }
            c.close();
            db[0].close();

        } catch (Exception e) {
            Log.d("Eroare", "doInBackground", e);
        }

        return null;
    }

    protected void onProgressUpdate(String...values) {

        Aitem items[] = new Aitem[1];

        viteza[contor]=Float.valueOf(values[0]);
        time[contor]=values[1];
        if(contor>3)
        {
        items[0]=new Aitem(Color.RED, "Evolution",viteza);
        lv.setTitle("Evolutia vitezei");

        lv.setAxisValueX(time);

        setContentView(lv);
        }
        contor++;
    }

}

}
</code>```

I get error at this line:

```<code>viteza[contor]=Float.valueOf(values[0]);

java.lang.NumberFormatException:
   at org.apache.harmony.luni.util.FloatingPointParser.parseFltImpl(Native Method)
 at org.apache.harmony.luni.util.FloatingPointParser.parseFloat(FloatingPointParser.java:321)
</code>```

Has anyone any clue what is gooing wrong???

EDIT:

In my humble opinion values[0]=c.getString(3)  and values[1]=c.getString(4) so ....are Strings...aren't they?

答:
Obviously the first element isn't a proper string containing a float.

So obviously the content of c.getString(3) must be wrong. Check that this is a string, and that this string contains strictly a float. Check for invalid characters, spaces, etc.

Title: lang.NumberFormatException in android

Body:
I have the following code which does nothing but reading some values from a DB in a background thread and using the values I draw a Line chart using a jar.For the line chart I use for value for each array and the problem is that the third that I pass to the constructor that draws the LineChart is float....

float[] viteza;

String[] time;

int contor=0;

public void onResume() {

    super.onResume();

    init_task = new InitTask();

    init_task.execute(db);

}

public class InitTask extends AsyncTask<DBAdapter,String, Void> {

    String TABLE_3;

    protected Void doInBackground(DBAdapter... db) {
        try {
            db[0].createDatabase();
            db[0].openDataBase();
            Cursor c = db[0].getCursor3(db[0].TABLE_3, user_id);

            String[] array=new String[2];
            viteza = new float[c.getCount()];
            time = new String[c.getCount()];

            if (c.moveToFirst()) {

                do {

                    publishProgress(c.getString(3),c.getString(4));
                    Thread.sleep(500);

                } while (c.moveToNext());

            }
            c.close();
            db[0].close();

        } catch (Exception e) {
            Log.d("Eroare", "doInBackground", e);
        }

        return null;
    }

    protected void onProgressUpdate(String...values) {

        Aitem items[] = new Aitem[1];

        viteza[contor]=Float.valueOf(values[0]);
        time[contor]=values[1];
        if(contor>3)
        {
        items[0]=new Aitem(Color.RED, "Evolution",viteza);
        lv.setTitle("Evolutia vitezei");

        lv.setAxisValueX(time);

        setContentView(lv);
        }
        contor++;
    }

}

}

I get error at this line:

viteza[contor]=Float.valueOf(values[0]);

java.lang.NumberFormatException:
   at org.apache.harmony.luni.util.FloatingPointParser.parseFltImpl(Native Method)
 at org.apache.harmony.luni.util.FloatingPointParser.parseFloat(FloatingPointParser.java:321)

Has anyone any clue what is gooing wrong???

EDIT:

In my humble opinion values[0]=c.getString(3)  and values[1]=c.getString(4) so ....are Strings...aren't they?


问:
How to increase the memory limits in Google Cloud Run?
I'm building a simple Flask based app using Cloud Run + Cloud Firestore. There is one method that brings a lot of data, and the logs are showing this error:

```<code>`Memory limit of 244M exceeded with 248M used. Consider increasing the memory limit, see https://cloud.google.com/run/docs/configuring/memory-limits`
</code>```

How I can increase the memory limit in the cloudbuild.yaml? Our YAML file contains the following:

```<code># cloudbuild.yaml
steps:
  # build & push the container image
- name: "gcr.io/kaniko-project/executor:latest"
  args: ["--cache=true", "--cache-ttl=48h", "--destination=gcr.io/$PROJECT_ID/todo:latest"]
  # Deploy container image to Cloud Run
- name: "gcr.io/cloud-builders/gcloud"
  args: ['beta', 'run', 'deploy', 'todo', '--image', 'gcr.io/$PROJECT_ID/todo:latest', '--region', 'us-central1', '--allow-unauthenticated', '--platform', 'managed']
</code>```

Thank you

答:
In the args of the last step, add '--memory', '512Mi'

The format for size is a fixed or floating point number followed by a unit: G, M, or K corresponding to gigabyte, megabyte, or kilobyte, respectively, or use the power-of-two equivalents: Gi, Mi, Ki corresponding to gibibyte, mebibyte or kibibyte respectively.

Body:
I'm building a simple Flask based app using Cloud Run + Cloud Firestore. There is one method that brings a lot of data, and the logs are showing this error:

`Memory limit of 244M exceeded with 248M used. Consider increasing the memory limit, see https://cloud.google.com/run/docs/configuring/memory-limits`

How I can increase the memory limit in the cloudbuild.yaml? Our YAML file contains the following:

# cloudbuild.yaml
steps:
  # build & push the container image
- name: "gcr.io/kaniko-project/executor:latest"
  args: ["--cache=true", "--cache-ttl=48h", "--destination=gcr.io/$PROJECT_ID/todo:latest"]
  # Deploy container image to Cloud Run
- name: "gcr.io/cloud-builders/gcloud"
  args: ['beta', 'run', 'deploy', 'todo', '--image', 'gcr.io/$PROJECT_ID/todo:latest', '--region', 'us-central1', '--allow-unauthenticated', '--platform', 'managed']

Thank you