问:
how can i get the value of an azure cli list command into a variable?
When i run the following command in azure, I want to place the value of the "name" in a variable like $ipconfigname. The output lists out many other values but I only need this one value "name" in the variable, how can i accomplish this?

az network nic ip-config list -g rg01 --nic-name vmnic01

答:
The az cli outputs JSON so if you run your command from a PowerShell prompt you can use ConvertFrom-Json to create an object from the output and then get the property you need</p>

```<code>$IpConfig = az network nic ip-config list -g rg01 --nic-name vmnic01 | ConvertFrom-Json
$IpConfigName = $IpConfig.name
</code>```

Body:
The az cli outputs JSON so if you run your command from a PowerShell prompt you can use ConvertFrom-Json to create an object from the output and then get the property you need

$IpConfig = az network nic ip-config list -g rg01 --nic-name vmnic01 | ConvertFrom-Json
$IpConfigName = $IpConfig.name


来源: stackexchange

问:
How to implement the Luhn alorithm in OCL
I am trying to find the Luhn algorithm in OCL to check the validity of ISIN. Can anyone provide a code example would it be great!   </p>

答:
In pure OCL using the example from https://en.wikipedia.org/wiki/Luhn_algorithm</p>

```<code>let s = Sequence{7,9,9,2,7,3,9,8,7,1} in
(Sequence{1..s->size()}
    ->collect(i |
        let t = s->at(i) in
        if i.mod(2) = 1
        then t
        else let tt = 2 * t in tt.div(10) + tt.mod(10)
        endif)
    ->sum()*9)
.mod(10)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In pure OCL using the example from https://en.wikipedia.org/wiki/Luhn_algorithm

let s = Sequence{7,9,9,2,7,3,9,8,7,1} in
(Sequence{1..s->size()}
    ->collect(i |
        let t = s->at(i) in
        if i.mod(2) = 1
        then t
        else let tt = 2 * t in tt.div(10) + tt.mod(10)
        endif)
    ->sum()*9)
.mod(10)


问:
Multiple <http> elements in Spring security
Recently Spring Security has given the opportunity to configure several <http> elements. I'm trying to set a configuration for all the urls which maps the pattern /foo/* and another for the rest. Now I have two login pages one set in /login and the other in /foo login. So I want that all the urls which map /foo/** do the login against /foo/login.

I have created a configuration like the one below, but when I enter an url like /foo/something (which shouldn't be allowed to the anonymous user) instead of going to /foo/login it goes to /login.

The Spring Security version is 3.1.0.RC1.
Any idea of what may be happening?

```<code><sec:http auto-config="true" pattern="/foo/**" entry-point-ref="ajaxAuthenticationEntryPoint">
    <sec:intercept-url pattern="/foo/login" access="ROLE_ANONYMOUS,ROLE_BASIC,ROLE_ADMIN" />
    ...
    <!-- other sec:intercepts for some /foo/* urls -->
    ...
    <sec:intercept-url pattern="/foo/**" access="ROLE_BASIC" />

    <sec:custom-filter before="SECURITY_CONTEXT_FILTER" ref="basicProcessingFilter" />

    <sec:form-login login-page="/foo/login" authentication-failure-url="/foo/login" default-target-url="/index" always-use-default-target="true" />

    <sec:session-management>
        <sec:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/login" />
    </sec:session-management>
</sec:http>

<sec:http auto-config="true" pattern="/**" entry-point-ref="ajaxAuthenticationEntryPoint">
    <!-- some sec:intercepts for some urls -->
    ...

    <sec:intercept-url pattern="/**" access="ROLE_ADMIN" />

    <sec:custom-filter before="SECURITY_CONTEXT_FILTER" ref="basicProcessingFilter" />

    <sec:form-login login-page="/login" default-target-url="/index" always-use-default-target="true" />

    <sec:session-management>
        <sec:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/login" />
    </sec:session-management>
</sec:http>
</code>```

答:
Just a guess. Could it be that the patterns are additive?

So the following annotation:

```<code><sec:http auto-config="true" pattern="/foo/**" entry-point-ref="ajaxAuthenticationEntryPoint">
    <sec:intercept-url pattern="/foo/**" access="ROLE_BASIC" />
</sec:http>
</code>```

intercepts /foo/foo/**. That will cause a foo/something request to be intercepted by your second http definition, the one with pattern="/**"

Body:
Recently Spring Security has given the opportunity to configure several <http> elements. I'm trying to set a configuration for all the urls which maps the pattern /foo/* and another for the rest. Now I have two login pages one set in /login and the other in /foo login. So I want that all the urls which map /foo/** do the login against /foo/login.

I have created a configuration like the one below, but when I enter an url like /foo/something (which shouldn't be allowed to the anonymous user) instead of going to /foo/login it goes to /login.

The Spring Security version is 3.1.0.RC1.
Any idea of what may be happening?

<sec:http auto-config="true" pattern="/foo/**" entry-point-ref="ajaxAuthenticationEntryPoint">
    <sec:intercept-url pattern="/foo/login" access="ROLE_ANONYMOUS,ROLE_BASIC,ROLE_ADMIN" />
    ...

    ...
    <sec:intercept-url pattern="/foo/**" access="ROLE_BASIC" />

    <sec:custom-filter before="SECURITY_CONTEXT_FILTER" ref="basicProcessingFilter" />

    <sec:form-login login-page="/foo/login" authentication-failure-url="/foo/login" default-target-url="/index" always-use-default-target="true" />

    <sec:session-management>
        <sec:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/login" />
    </sec:session-management>
</sec:http>

<sec:http auto-config="true" pattern="/**" entry-point-ref="ajaxAuthenticationEntryPoint">

    ...

    <sec:intercept-url pattern="/**" access="ROLE_ADMIN" />

    <sec:custom-filter before="SECURITY_CONTEXT_FILTER" ref="basicProcessingFilter" />

    <sec:form-login login-page="/login" default-target-url="/index" always-use-default-target="true" />

    <sec:session-management>
        <sec:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/login" />
    </sec:session-management>
</sec:http>

Body:
Just a guess. Could it be that the patterns are additive?

So the following annotation:

<sec:http auto-config="true" pattern="/foo/**" entry-point-ref="ajaxAuthenticationEntryPoint">
    <sec:intercept-url pattern="/foo/**" access="ROLE_BASIC" />
</sec:http>

intercepts /foo/foo/**. That will cause a foo/something request to be intercepted by your second http definition, the one with pattern="/**"

ContentLicense: CC BY-SA 3.0


问:
How to select option in drop down protractorjs e2e tests
I am trying to select an option from a drop down for the angular e2e tests using protractor.

Here is the code snippet of the select option:

```<code><select id="locregion" class="create_select ng-pristine ng-invalid ng-invalid-required" required="" ng-disabled="organization.id !== undefined" ng-options="o.id as o.name for o in organizations" ng-model="organization.parent_id">
    <option value="?" selected="selected"></option>
    <option value="0">Ranjans Mobile Testing</option>
    <option value="1">BeaverBox Testing</option>
    <option value="2">BadgerBox</option>
    <option value="3">CritterCase</option>
    <option value="4">BoxLox</option>
    <option value="5">BooBoBum</option>
</select>
</code>```

I have tried:

```<code>ptor.findElement(protractor.By.css('select option:1')).click();
</code>```

This gives me the following error:

An invalid or illegal string was specified
Build info: version: '2.35.0', revision: 'c916b9d', time: '2013-08-12 15:42:01'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.9', java.version: '1.6.0_65'
Driver info: driver.version: unknown

I have also tried:

```<code>ptor.findElement(protractor.By.xpath('/html/body/div[2]/div/div[4]/div/div/div/div[3]/ng-include/div/div[2]/div/div/organization-form/form/div[2]/select/option[3]')).click();
</code>```

This gives me the following error:

ElementNotVisibleError: Element is not currently visible and so may not be interacted with
  Command duration or timeout: 9 milliseconds
  Build info: version: '2.35.0', revision: 'c916b9d', time: '2013-08-12 15:42:01'
  System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.9', java.version: '1.6.0_65'
  Session ID: bdeb8088-d8ad-0f49-aad9-82201c45c63f
  Driver info: org.openqa.selenium.firefox.FirefoxDriver
  Capabilities [{platform=MAC, acceptSslCerts=true, javascriptEnabled=true, browserName=firefox, rotatable=false, locationContextEnabled=true, version=24.0, cssSelectorsEnabled=true, databaseEnabled=true, handlesAlerts=true, browserConnectionEnabled=true, nativeEvents=false, webStorageEnabled=true, applicationCacheEnabled=false, takesScreenshot=true}]

Can anyone please help me with this problem or throw some light on what i might be doing wrong here.

答:
This is a simple one line answer in which angular has special locator which can help to select and index from list.</p>

```<code>element.all(by.options('o.id as o.name for o in organizations')).get(Index).click()
</code>```

Body:
I am trying to select an option from a drop down for the angular e2e tests using protractor.

Here is the code snippet of the select option:

<select id="locregion" class="create_select ng-pristine ng-invalid ng-invalid-required" required="" ng-disabled="organization.id !== undefined" ng-options="o.id as o.name for o in organizations" ng-model="organization.parent_id">
    <option value="?" selected="selected"></option>
    <option value="0">Ranjans Mobile Testing</option>
    <option value="1">BeaverBox Testing</option>
    <option value="2">BadgerBox</option>
    <option value="3">CritterCase</option>
    <option value="4">BoxLox</option>
    <option value="5">BooBoBum</option>
</select>

I have tried:

ptor.findElement(protractor.By.css('select option:1')).click();

This gives me the following error:

An invalid or illegal string was specified
Build info: version: '2.35.0', revision: 'c916b9d', time: '2013-08-12 15:42:01'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.9', java.version: '1.6.0_65'
Driver info: driver.version: unknown

I have also tried:

ptor.findElement(protractor.By.xpath('/html/body/div[2]/div/div[4]/div/div/div/div[3]/ng-include/div/div[2]/div/div/organization-form/form/div[2]/select/option[3]')).click();

This gives me the following error:

ElementNotVisibleError: Element is not currently visible and so may not be interacted with
  Command duration or timeout: 9 milliseconds
  Build info: version: '2.35.0', revision: 'c916b9d', time: '2013-08-12 15:42:01'
  System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.9', java.version: '1.6.0_65'
  Session ID: bdeb8088-d8ad-0f49-aad9-82201c45c63f
  Driver info: org.openqa.selenium.firefox.FirefoxDriver
  Capabilities [{platform=MAC, acceptSslCerts=true, javascriptEnabled=true, browserName=firefox, rotatable=false, locationContextEnabled=true, version=24.0, cssSelectorsEnabled=true, databaseEnabled=true, handlesAlerts=true, browserConnectionEnabled=true, nativeEvents=false, webStorageEnabled=true, applicationCacheEnabled=false, takesScreenshot=true}]

Can anyone please help me with this problem or throw some light on what i might be doing wrong here.

Body:
This is a simple one line answer in which angular has special locator which can help to select and index from list.

element.all(by.options('o.id as o.name for o in organizations')).get(Index).click()


问:
Cursor bug in VSCode, deletes last character
After I restarted my computer, VSCode started to behave oddly. When I open any file:

The cursor's style seems to be "block", although in the settings it's "line".

If I type any character, the character doesn't get written into the file - VSCode actually deletes the character located where the cursor is

After that, I can finally write new characters and the cursor returns back to normal (a line)

Here's how it looks:

Does anyone know if this is bug on their end? I'm using VSCode@1.45.1.

答: Nevermind, it seems that this was caused by the Vim extension I recently installed. There's a thread opened about it.</p>


问:
How to find a whole word in a sentence in Python?
Say I have a sentence

```<code>sent = "Luxred is a great,awesome and amazing but, they make a lot of money too"
ents = ['L'Oreal', 'Maybelline', 'Garnier Natural', 'Luxred', 'Lux']
</code>```

The sentences will be like this. The sentences will have commas and other words too. I want to find the exact word match for Luxred. It shouldn't match for Lux either and also want the starting index & ending index of the word. Here it is (0, 5). The sentence might change and the search words might come in between etc. How do I do this ?

Already tried using find.

```<code>def annotFinal (label, entities, sentences) :
finaldict = []
for sent in sentences :
    sent = str(sent).lower()
    inner_list = []
    for ent in entities :
        if (sent.find(ent) != -1) :
            inner_tup = (sent.find(ent), sent.find(ent) + len(ent), label)
            inner_list.append(inner_tup)
    inner_dict={'entities': sorted(inner_list, key=lambda x: x[0])}
    finaldict.append((sent, inner_dict))
return finaldict
</code>```

答:
I was able to get it done by using the following -

```<code>re.search(r"\b" + word + r"\b", sentence)
</code>```

Gets the complete word & doesn't return out substrings like "cat" from "caterpillar" alone.

Body:
Say I have a sentence

sent = "Luxred is a great,awesome and amazing but, they make a lot of money too"
ents = ['L'Oreal', 'Maybelline', 'Garnier Natural', 'Luxred', 'Lux']

The sentences will be like this. The sentences will have commas and other words too. I want to find the exact word match for Luxred. It shouldn't match for Lux either and also want the starting index & ending index of the word. Here it is (0, 5). The sentence might change and the search words might come in between etc. How do I do this ?

Already tried using find.

def annotFinal (label, entities, sentences) :
finaldict = []
for sent in sentences :
    sent = str(sent).lower()
    inner_list = []
    for ent in entities :
        if (sent.find(ent) != -1) :
            inner_tup = (sent.find(ent), sent.find(ent) + len(ent), label)
            inner_list.append(inner_tup)
    inner_dict={'entities': sorted(inner_list, key=lambda x: x[0])}
    finaldict.append((sent, inner_dict))
return finaldict

Body:
I was able to get it done by using the following -

re.search(r"\b" + word + r"\b", sentence)

Gets the complete word & doesn't return out substrings like "cat" from "caterpillar" alone.


问:
Are Quartz jobs running in the same JVM in their own threads?
Quartz scheduler is used to schedule timed java jobs at my workplace. The scheduler itself is deployed as an application to a Weblogic servers (a cluster of machines). This scheduler can schedule jobs which implement the Job interface and override the execute() method. These jobs are deployed to the Weblogic servers as libraries which are then used by the scheduler. (One library includes multiple jobs.)

I have not managed to find informative sources on how these jobs are run or how they share resources.
I looked at the Quartz documentation but could not find what I was looking for.

I have multiple questions, though I believe a single answer may cover all of them.

Do all the jobs created through the scheduler share a single JVM? If they don't, then based on what is a job allocated to a given JVM?

I assume that a separate thread is allocated to each job - is that correct?

If all scheduled jobs run in the same JVM and each has its own thread, then concurrent execution of the same job with different parameters will create a need for making the job thread safe or a need to disable concurrent execution of the job, will not it?

Thank you.

答:
You may want to read Quartz scheduler tutorial to find out how Quartz works. To answer your questions:

This depends on whether you run a Quartz scheduler cluster (i.e. multiple Quartz scheduler instances sharing the same job store) or a standalone Quartz scheduler instance. In clustered deployments, individual Quartz scheduler instances compete to execute jobs by creating DB row locks. The scheduler instance that first manages to create the row lock, is the scheduler instance that executes a particular job. In a standalone Quartz scheduler deployment, the completion does not exist and it is always the single Quartz scheduler instance that ends up executing all jobs.

Quartz uses a thread pool and when it needs to execute a job, it simply allocates a free thread from the pool and uses it to execute the job. After the job finishes executing, Quartz returns the thread back to the pool.

Instances of Quartz job implementation classes are not shared. That means, when Quartz is about to execute a job, it instantiates the configured org.quartz.Job class and invokes its execute method passing it the job execution context as a parameter. Once the job execution completes, the org.quartz.Job instance is discarded and eventually garbage-collected, i.e. it is not reused by Quartz. If your org.quartz.Job class declares / accesses some static fields, singletons etc., then you may need to synchronize access to these shared resources where necessary.


问:
Difftime giving a larger than expected value
When I print the result of difftime, I get the result: -4334284568731237.000000.  Why is this?</p>

```<code>    //time1 and time2 are both of type time_t

    time_t temp;

    char val[] = "06:02";
    struct tm tm;
    strptime(val, "%H:%M", &tm);
    temp = mktime(&tm);
    items[0].time1 = temp;

    char val2[] = "06:43";
    struct tm tm;
    strptime(val2, "%H:%M", &tm);
    temp = mktime(&tm);
    items[0].time2 = temp;

    printf("%f\n", difftime(items[0].time1, items[0].time2));
</code>```

答:
I assuming tm variables are declared at block scope with automatic storage duration.

Why is this?

You only set the hour and minutes:

```<code>struct tm tm;                  // uninitialized
strptime(val2, "%H:%M", &tm);  // sets only tm.tm_hour and tm.tm_min
</code>```

strptime doesn't initialize tm, only stores what it reads. The rest of members of struct tm are uninitialized, so they have "indeterminate" values - any values. So it may just happen that the first tm has different value of a year from the other tm, which results in a big difference in what mktime returns when it parses tm.

From the strptime man page: tm should be initialized before the call. So do initialize the structure before calling strptime:

```<code>struct tm tm = {0};
strptime(val2, "%H:%M", &tm);
</code>```

Body:
When I print the result of difftime, I get the result: -4334284568731237.000000.  Why is this?

    //time1 and time2 are both of type time_t

    time_t temp;

    char val[] = "06:02";
    struct tm tm;
    strptime(val, "%H:%M", &tm);
    temp = mktime(&tm);
    items[0].time1 = temp;

    char val2[] = "06:43";
    struct tm tm;
    strptime(val2, "%H:%M", &tm);
    temp = mktime(&tm);
    items[0].time2 = temp;

    printf("%f\n", difftime(items[0].time1, items[0].time2));

Body:
I assuming tm variables are declared at block scope with automatic storage duration.

Why is this?

You only set the hour and minutes:

struct tm tm;                  // uninitialized
strptime(val2, "%H:%M", &tm);  // sets only tm.tm_hour and tm.tm_min

strptime doesn't initialize tm, only stores what it reads. The rest of members of struct tm are uninitialized, so they have "indeterminate" values - any values. So it may just happen that the first tm has different value of a year from the other tm, which results in a big difference in what mktime returns when it parses tm.

From the strptime man page: tm should be initialized before the call. So do initialize the structure before calling strptime:

struct tm tm = {0};
strptime(val2, "%H:%M", &tm);


问:
How to change format to standard time JavaScript
I have a date string in JavaScript which is arranged in a particular manner. How do I rearrange this in order to fit standard time?

let date = "2020-06-01T00:00:00Z"```

How do I rearrange the date variable in order to match the format MM/DD, YYYY ?

答:
Change your code to as follows:</p>

```<code>  let date = "2020-06-01T00:00:00Z";
  date = new Date(date);
  var dd = date.getDate();
  var mm = date.getMonth()+1;
  var yyyy = date.getFullYear();
  if(dd<10){dd='0'+dd}
  if(mm<10){mm='0'+mm};
  console.log(mm+'/'+dd+', '+yyyy)
</code>```

Body:
I have a date string in JavaScript which is arranged in a particular manner. How do I rearrange this in order to fit standard time?

let date = "2020-06-01T00:00:00Z"

How do I rearrange the date variable in order to match the format MM/DD, YYYY ?

Body:
Change your code to as follows:

  let date = "2020-06-01T00:00:00Z";
  date = new Date(date);
  var dd = date.getDate();
  var mm = date.getMonth()+1;
  var yyyy = date.getFullYear();
  if(dd<10){dd='0'+dd}
  if(mm<10){mm='0'+mm};
  console.log(mm+'/'+dd+', '+yyyy)


问:
A little bit lost with goQuery selection
I'm new to Go and I'm trying to learn it by making a repost bot. Anyway, I'm having a problem that I don't know how to solve exactly.

I have the following Struct:

```<code>type Post struct {
    Title string
    Url   string
}
</code>```

And I'm trying to get these values using goQuery, like this:

```<code>var title = doc.Find(".title.title.may-blank").Each(func(i int, s *goquery.Selection) {
        fmt.Println("Title:", s.Text())
})
</code>```

But when I try to set the value to the Post struct, I get this error:

```<code>cannot use title (type *goQuery.Selection) as type string in field value.
</code>```

Ok, that makes sense, but how can I cast it to string? I've tried s.Text() but it doesn't works. I thought about making a function that returns a string, but I'm not sure if this would work.

I'll appreciate if someone can help me, thanks in advance!

答:
The issue is that .Each returns the original *goquery.Selection so that you can chain calls.  If you need to get the string value, you just assign it directly, like this:

```<code>var title string
doc.Find(".title.title.may-blank").Each(func(i int, s *goquery.Selection) {
    title = s.Text()
})
</code>```

Body:
I'm new to Go and I'm trying to learn it by making a repost bot. Anyway, I'm having a problem that I don't know how to solve exactly.

I have the following Struct:

type Post struct {
    Title string
    Url   string
}

And I'm trying to get these values using goQuery, like this:

var title = doc.Find(".title.title.may-blank").Each(func(i int, s *goquery.Selection) {
        fmt.Println("Title:", s.Text())
})

But when I try to set the value to the Post struct, I get this error:

cannot use title (type *goQuery.Selection) as type string in field value.

Ok, that makes sense, but how can I cast it to string? I've tried s.Text() but it doesn't works. I thought about making a function that returns a string, but I'm not sure if this would work.

I'll appreciate if someone can help me, thanks in advance!

Body:
The issue is that .Each returns the original *goquery.Selection so that you can chain calls.  If you need to get the string value, you just assign it directly, like this:

var title string
doc.Find(".title.title.may-blank").Each(func(i int, s *goquery.Selection) {
    title = s.Text()
})


问:
How to reliably measure computed height of all combined child elements in React Native
I'm using onLayout to measure the height of a View in which are rendered an arbitrary number of child components containing multiple nested Views and at least one Text node. The returned height value is consistently just the value of the total vertical margin applied to the outermost View, however, and does not include the height of any other nodes, including the Text -- which has a nonzero height that I can successfully measure by using onLayout on it:

```<code><View onLayout={/*only ever returns 40 as the height*/}>
  <View style={{marginBottom: 40}}>
    <Text>This node has a computed height of 60</Text>
  </View>
</View>
</code>```

Is the issue here that onLayout is not firing consistently, or is it that the computed height will never actually include the computed heights of these child nodes? What's the preferred workaround for this type of situation?

答:
For future reference:

It looks like there is indeed an undocumented issue with measuring the heights of React Native Views that contain Text nodes nested more than one level deep.

I moved the Text outside of its parent View, so that it's an immediate child of the node whose height I'm measuring, and the measured height is now correct:

```<code><View onLayout={/*This now returns 100 as the height*/}>
  <View style={{marginBottom: 40}}>
  </View>
  <Text>This node has a computed height of 60</Text>
</View>
</code>```

As far as a workaround, this will depend on the use case. In my situation I wound up having to apply various styles to each individual Text instead of using a wrapper.

Body:
I'm using onLayout to measure the height of a View in which are rendered an arbitrary number of child components containing multiple nested Views and at least one Text node. The returned height value is consistently just the value of the total vertical margin applied to the outermost View, however, and does not include the height of any other nodes, including the Text -- which has a nonzero height that I can successfully measure by using onLayout on it:

<View onLayout={/*only ever returns 40 as the height*/}>
  <View style={{marginBottom: 40}}>
    <Text>This node has a computed height of 60</Text>
  </View>
</View>

Is the issue here that onLayout is not firing consistently, or is it that the computed height will never actually include the computed heights of these child nodes? What's the preferred workaround for this type of situation?

Body:
For future reference:

It looks like there is indeed an undocumented issue with measuring the heights of React Native Views that contain Text nodes nested more than one level deep.

I moved the Text outside of its parent View, so that it's an immediate child of the node whose height I'm measuring, and the measured height is now correct:

<View onLayout={/*This now returns 100 as the height*/}>
  <View style={{marginBottom: 40}}>
  </View>
  <Text>This node has a computed height of 60</Text>
</View>

As far as a workaround, this will depend on the use case. In my situation I wound up having to apply various styles to each individual Text instead of using a wrapper.


问:
How to convert string to double in PowerShell?
I have a script in PowerShell that I am using to import data from a CSV. I am receiving an error

Cannot convert value "Journal Amount" to type "System.Double". Error: "Input string was not in a correct format."
At C:\TestPowerShell\TestPowerShell1.ps1:98 char:1
+ $JournalAmount = [double] $_.PSObject.Properties['Journal Amount'].Va ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToDoubleOrSingle

Here is my code:

```<code>Get-Content "config.txt" | foreach-object -begin {$h=@{}} -process { $k = [regex]::split($_,'='); if(($k[0].CompareTo("") -ne 0) -and ($k[0].StartsWith("[") -ne $True)) { $h.Add($k[0], $k[1]) } }

$FileBrowserInitialDir = $h.FileBrowserInitialDir
$Header = 'Terminal','Company','Journal Account Code','Project','Task','Line of Business','Date','Journal Amount','Report Entry Vendor Description'

$TIDataFilePath = $h.TIDataFilePath
$TIDataFileBaseName = $h.TIDataFileBaseName

$TIScreenID = $h.TIScreenID
$TIControlFile = $h.TIControlFile
$TIErrLog = $h.TIErrLog

$ResultsFilePath = $h.ResultsFilePath
$ResultsFileBaseName = $h.ResultsFileBaseName

$dt = Get-Date -Format "MMddyyyyHHmmss"
$TIDataFile = "$($TIDataFileBaseName)$($dt).txt"
$ResultsFile = "$($ResultsFileBaseName)$($dt).txt"

Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
    InitialDirectory = $FileBrowserInitialDir
    Filter = 'CSV (*.csv)|*.csv'
    Title = "Select Expense csv file"
}
$null = $FileBrowser.ShowDialog()

if($FileBrowser.FileName -eq ""){
    exit
}

 $EXPENSECSV = Import-CSV $FileBrowser.FileName -Header $Header
 New-Item -path $TIDataFilePath -name $TIDataFile -type "file"
 $EXPENSECSV |foreach-object{

$Terminal =  $_.PSObject.Properties['Terminal'].Value
$Terminal = $Terminal.Insert(0,'0')

$CompanyTemp =  $_.PSObject.Properties['Company'].Value
$CompanyTemp = $CompanyTemp.Insert(0,'0')
#$Company= [String]::Concat($_.Terminal,$CompanyTemp)
$Company= [String]::Concat($Terminal,$CompanyTemp)
$LineofB =  $_.PSObject.Properties['Line of Business'].Value
#$JournalAmount = [double] $_.PSObject.Properties["Journal Amount"].Value
 $LineofB = $LineofB.Insert(0,'0')

 $Account = $_.PSObject.Properties['Journal Account Code'].Value
$Sub = $LineofB

$TranDateStr =  $_.PSObject.Properties['Date'].Value
$JournalAmount = [double] $_.PSObject.Properties['Journal Amount'].Value
$Description =  $_.PSObject.Properties['Report Entry Vendor Description'].Value

    $row = ""
    $row +=  "`"Level1`","
    $row +=  "`"$($Company)`","
    $row +=  "`"$($Account)`","
    $row +=  "`"$($Sub)`","
    $row +=  "`"$($TranDateStr)`","

    # Convert Concur Amount to Credit/Debit Amount
    # Postive Amount  --> Debit Amount
    # Negative Amount --> Credit Amount
    if($JournalAmount -lt 0){
        $JournalAmount*= -1
        $row += "`"$($JournalAmount)`","   #Credit Amount
        $row += "`"`","             #Debit Amount
    }
    else {
        $row += "`"`","             #Credit Amount
        $row += "`"$($JournalAmount)`","   #Debit Amount
    }

    $row += "`"$($Description)`""

   Add-Content -Path "$($TIDataFilePath)$($TIDataFile)" -Value $row
 }

 #Results
 New-Item -path $ResultsFilePath -name $ResultsFile -type "file"

 $ResultsStr =   "----------------------------------------------------------------------------------`n"
$ResultsStr +=  "                             Concur to Dynamics SL                                   `n"
$ResultsStr +=  "----------------------------------------------------------------------------------`n"
$ResultsStr +=  "Copy and paste the following into the Transaction Import screen.`n"
$ResultsStr += "Line 1: Data File Name`n"
$ResultsStr += "Line 2: Screen ID`n"
$ResultsStr += "Line 3: Control File Name`n"
$ResultsStr += "Line 4: Output Log File`n`n`n"
$ResultsStr += "$($TIDataFilePath)$($TIDataFile)`n"
$ResultsStr += "$($TIScreenID)`n"
$ResultsStr += "$($TIControlFile)`n"
$ResultsStr += "$($TIErrLog)"

 Add-Content -path "$($ResultsFilePath)$($ResultsFile)" -value $ResultsStr

Start-Process "$($ResultsFilePath)$($ResultsFile)"
</code>```

答:
This fixed the issue: </p>

```<code>$JournalAmount = $JournalAmount -as [double]
$JournalAmount = $_.PSObject.Properties['Journal Amount'].Value
</code>```

Body:
I have a script in PowerShell that I am using to import data from a CSV. I am receiving an error

Cannot convert value "Journal Amount" to type "System.Double". Error: "Input string was not in a correct format."
At C:\TestPowerShell\TestPowerShell1.ps1:98 char:1
+ $JournalAmount = [double] $_.PSObject.Properties['Journal Amount'].Va ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToDoubleOrSingle

Here is my code:

Get-Content "config.txt" | foreach-object -begin {$h=@{}} -process { $k = [regex]::split($_,'='); if(($k[0].CompareTo("") -ne 0) -and ($k[0].StartsWith("[") -ne $True)) { $h.Add($k[0], $k[1]) } }

$FileBrowserInitialDir = $h.FileBrowserInitialDir
$Header = 'Terminal','Company','Journal Account Code','Project','Task','Line of Business','Date','Journal Amount','Report Entry Vendor Description'

$TIDataFilePath = $h.TIDataFilePath
$TIDataFileBaseName = $h.TIDataFileBaseName

$TIScreenID = $h.TIScreenID
$TIControlFile = $h.TIControlFile
$TIErrLog = $h.TIErrLog

$ResultsFilePath = $h.ResultsFilePath
$ResultsFileBaseName = $h.ResultsFileBaseName

$dt = Get-Date -Format "MMddyyyyHHmmss"
$TIDataFile = "$($TIDataFileBaseName)$($dt).txt"
$ResultsFile = "$($ResultsFileBaseName)$($dt).txt"

Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
    InitialDirectory = $FileBrowserInitialDir
    Filter = 'CSV (*.csv)|*.csv'
    Title = "Select Expense csv file"
}
$null = $FileBrowser.ShowDialog()

if($FileBrowser.FileName -eq ""){
    exit
}

 $EXPENSECSV = Import-CSV $FileBrowser.FileName -Header $Header
 New-Item -path $TIDataFilePath -name $TIDataFile -type "file"
 $EXPENSECSV |foreach-object{

$Terminal =  $_.PSObject.Properties['Terminal'].Value
$Terminal = $Terminal.Insert(0,'0')

$CompanyTemp =  $_.PSObject.Properties['Company'].Value
$CompanyTemp = $CompanyTemp.Insert(0,'0')
#$Company= [String]::Concat($_.Terminal,$CompanyTemp)
$Company= [String]::Concat($Terminal,$CompanyTemp)
$LineofB =  $_.PSObject.Properties['Line of Business'].Value
#$JournalAmount = [double] $_.PSObject.Properties["Journal Amount"].Value
 $LineofB = $LineofB.Insert(0,'0')

 $Account = $_.PSObject.Properties['Journal Account Code'].Value
$Sub = $LineofB

$TranDateStr =  $_.PSObject.Properties['Date'].Value
$JournalAmount = [double] $_.PSObject.Properties['Journal Amount'].Value
$Description =  $_.PSObject.Properties['Report Entry Vendor Description'].Value

    $row = ""
    $row +=  "`"Level1`","
    $row +=  "`"$($Company)`","
    $row +=  "`"$($Account)`","
    $row +=  "`"$($Sub)`","
    $row +=  "`"$($TranDateStr)`","

    # Convert Concur Amount to Credit/Debit Amount
    # Postive Amount  --> Debit Amount
    # Negative Amount --> Credit Amount
    if($JournalAmount -lt 0){
        $JournalAmount*= -1
        $row += "`"$($JournalAmount)`","   #Credit Amount
        $row += "`"`","             #Debit Amount
    }
    else {
        $row += "`"`","             #Credit Amount
        $row += "`"$($JournalAmount)`","   #Debit Amount
    }

    $row += "`"$($Description)`""

   Add-Content -Path "$($TIDataFilePath)$($TIDataFile)" -Value $row
 }

 #Results
 New-Item -path $ResultsFilePath -name $ResultsFile -type "file"

 $ResultsStr =   "----------------------------------------------------------------------------------`n"
$ResultsStr +=  "                             Concur to Dynamics SL                                   `n"
$ResultsStr +=  "----------------------------------------------------------------------------------`n"
$ResultsStr +=  "Copy and paste the following into the Transaction Import screen.`n"
$ResultsStr += "Line 1: Data File Name`n"
$ResultsStr += "Line 2: Screen ID`n"
$ResultsStr += "Line 3: Control File Name`n"
$ResultsStr += "Line 4: Output Log File`n`n`n"
$ResultsStr += "$($TIDataFilePath)$($TIDataFile)`n"
$ResultsStr += "$($TIScreenID)`n"
$ResultsStr += "$($TIControlFile)`n"
$ResultsStr += "$($TIErrLog)"

 Add-Content -path "$($ResultsFilePath)$($ResultsFile)" -value $ResultsStr

Start-Process "$($ResultsFilePath)$($ResultsFile)"

Body:
This fixed the issue:

$JournalAmount = $JournalAmount -as [double]
$JournalAmount = $_.PSObject.Properties['Journal Amount'].Value


问:
How can I remove a specific item from an array in JavaScript?
How do I remove a specific value from an array? Something like:

array.remove(value);
```

Constraints: I have to use core JavaScript. Frameworks are not allowed.

答:
An immutable and one-liner way:

const newArr = targetArr.filter(e => e !== elementToDelete);
```

Body:
How do I remove a specific value from an array? Something like:

array.remove(value);

Constraints: I have to use core JavaScript. Frameworks are not allowed.


问:
MembershipUser business object
I have a separate project that contains all of my business objects.  One of the business objects, User, holds login information and I want to convert it to be a MembershipUser object (see here).  However, MembershipUser object requires System.Web.  I don't want to add that reference to my BO project.  How do I use my business object as a MembershipUser without the dependency living in my BO project?

答: You really can't, at least not directly.  The only way I can think of is to write a wrapper class in your web project which inherits from MembershipUser and takes in one of your BOs as a constructor param, then delegates all its functionality to the BO.  It's not pretty, but it's pretty much the only way I'm aware of to solve your problem.</p>

Title: MembershipUser business object


问:
How to fetch documents from subcollection in firestore using spring data
How to fetch documents from subcollection using spring FirestoreReactiveRepository?

Ask is: how subcollection name or path can be given dynamically to @Document annotation?

My firestore collection: (cities is first level collection and apartments is subcollection of this)

```<code>cities - nyc (id)- |- name: New York City
                   |- country: USA
                   └ apartments - part_avenue (document id)
                                ├ name: Park Avenue
                                └ zip: 10022
                                - plaza (document id)
                                ├ name: Plaza Riverhouse
                                └ zip: 10132
</code>```

City POJO is

```<code>@Document(collectionName = "cities")
public class City {

  @DocumentId
  private String id;
  private String name;
  private String country;
  private List<Apartment> apartments;
}
</code>```

Apartment POJO is:

```<code>@Document(collectionName = "apartments")
public class Apartment {

  @DocumentId
  private String id;
  private String name;
  private Integer zip;
}
</code>```

CityRepository which fetches data from cities collection

```<code>public interface CityRepository extends FirestoreReactiveRepository<City> {

}
</code>```

On calling findById(nyc) returns apartments as null. I want to populate subcollection as well in city object.

Hi Dmirty,

In the given example pets are stored as part of user object(collection) but I want to store pets in a separate sub collection under users collection.

Result of given example:

Actual ask is pets should be subcollection like below:
So, it would be helpful if you can provide an example to store pets as subcollection and then how to retrieve it.

答:
That should work. Take a look at this sample - it does something similar.
You can run it and see if it works for you (it definitely works for me).

One potential issue is - are you missing public setters in your City class? They are required in order for conversion to work properly.

If that doesn't help, could you create a minimal application that replicates the issue (maybe on github) so I can take a closer look?

Body:
How to fetch documents from subcollection using spring FirestoreReactiveRepository?

Ask is: how subcollection name or path can be given dynamically to @Document annotation?

My firestore collection: (cities is first level collection and apartments is subcollection of this)

cities - nyc (id)- |- name: New York City
                   |- country: USA
                   └ apartments - part_avenue (document id)
                                ├ name: Park Avenue
                                └ zip: 10022
                                - plaza (document id)
                                ├ name: Plaza Riverhouse
                                └ zip: 10132

City POJO is

@Document(collectionName = "cities")
public class City {

  @DocumentId
  private String id;
  private String name;
  private String country;
  private List<Apartment> apartments;
}

Apartment POJO is:

@Document(collectionName = "apartments")
public class Apartment {

  @DocumentId
  private String id;
  private String name;
  private Integer zip;
}

CityRepository which fetches data from cities collection

public interface CityRepository extends FirestoreReactiveRepository<City> {

}

On calling findById(nyc) returns apartments as null. I want to populate subcollection as well in city object.

Hi Dmirty,

In the given example pets are stored as part of user object(collection) but I want to store pets in a separate sub collection under users collection.

Result of given example:

Actual ask is pets should be subcollection like below:
So, it would be helpful if you can provide an example to store pets as subcollection and then how to retrieve it.


问:
undefined object rendered when fetching in react
I am building a simple cryptocurrency app with coinmarketcap api. my get request is inside of componentDidMount. When I console.log the received object inside of the async function and inside the render - it works. But When I actually trying to display the received data inside of return (h3 element), the received object becomes undefined. I get a typeError "cannot read property urls of undefined". What am I doing wrong here?

```<code>import React, { Component } from "react";
import axios from "axios";
import { Row, Col, Badge } from "react-bootstrap";

class Crypto extends Component {
  constructor(props) {
    super(props);
    this.state = {
      singleCrypto: {},
      id: this.props.match.params.id
    };
  }

  componentDidMount() {
    this.getEachCrypto();
  }

  async getEachCrypto() {
    try {
      const proxyurl = "https://cors-anywhere.herokuapp.com/";
      const id = this.props.match.params.id;
      let data = await axios.get(
        proxyurl +
          "https://pro-api.coinmarketcap.com/v1/cryptocurrency/info?id=" +
          id,
        {
          headers: {
            "X-CMC_PRO_API_KEY": "e1eb1f30-5c4e-43aa-be04-4b50df00807a"
          }
        }
      );
      this.setState({ singleCrypto: data.data.data });
    } catch (error) {
      console.log("request failed", error);
    }
    console.log(
      this.state.singleCrypto[this.props.match.params.id].urls.website[0]
    ); // this works
  }

  render() {
    const { singleCrypto } = this.state;

    if (Object.keys(singleCrypto).length === 0) {
      console.log("Loading");
    } else {
      console.log(singleCrypto[this.props.match.params.id].urls.website[0]); // this works
    }

    return (
      <div>
        <div className="crypto fluid">
          <Row>
            <Col lg md={3}>
              <h3>
                {singleCrypto[this.props.match.params.id].urls.website[0]} // fails!!!
              </h3>
              <div>
                <ul>
                  <li>Rank</li>
                  <li>Website</li>
                  <li>Explorer</li>
                  <li>Message Board</li>
                  <li>Source Code</li>
                  <li>Tech Docs</li>
                  <li>Tags</li>
                </ul>
              </div>
            </Col>
            <Col lg md={7}>
              <h3>Price, % change</h3>
              <Badge variant="primary">Buy</Badge>
              <Badge variant="primary">Exchange</Badge>
              <Badge variant="primary">Gamble</Badge>
              <Badge variant="primary">Earn Crypto</Badge>
            </Col>
            <Col lg md={2}>
              2 parts
            </Col>
          </Row>
        </div>
      </div>
    );
  }
}

export default Crypto;
</code>```

here is my data sample:

```<code>"data": {
        "1": {
            "urls": {
                "website": [
                    "https://bitcoin.org/"
                ],
                "technical_doc": [
                    "https://bitcoin.org/bitcoin.pdf"
                ],
                "twitter": [],
                "reddit": [
                    "https://reddit.com/r/bitcoin"
                ],
                "message_board": [
                    "https://bitcointalk.org"
                ],
</code>```

答:
You must return null or a loading state when the data isn't available

```<code>if (Object.keys(singleCrypto).length === 0) {
  return null; // you can maintain a loading state too untill data is available
}
</code>```

With Loading state

```<code>class Crypto extends Component {
  constructor(props) {
    super(props);
    this.state = {
      singleCrypto: {},
      id: this.props.match.params.id.
      isLoading: true,
    };
  }

  componentDidMount() {
    this.getEachCrypto();
  }

  async getEachCrypto() {
    try {
      const proxyurl = "https://cors-anywhere.herokuapp.com/";
      const id = this.props.match.params.id;
      this.setState({isLoading: true});
      let data = await axios.get(
        proxyurl +
          "https://pro-api.coinmarketcap.com/v1/cryptocurrency/info?id=" +
          id,
        {
          headers: {
            "X-CMC_PRO_API_KEY": "e1eb1f30-5c4e-43aa-be04-4b50df00807a"
          }
        }
      );
      this.setState({ singleCrypto: data.data.data, isLoading: false });
    } catch (error) {
      console.log("request failed", error);
      this.setState({ isLoading: false });
    }
  }

  render() {
    const { singleCrypto } = this.state;
    if(this.state.isLoading) {
        return <div>Loading...<div>
    }
    ...
  }
}

export default Crypto;
</code>```

Body:
I am building a simple cryptocurrency app with coinmarketcap api. my get request is inside of componentDidMount. When I console.log the received object inside of the async function and inside the render - it works. But When I actually trying to display the received data inside of return (h3 element), the received object becomes undefined. I get a typeError "cannot read property urls of undefined". What am I doing wrong here?

import React, { Component } from "react";
import axios from "axios";
import { Row, Col, Badge } from "react-bootstrap";

class Crypto extends Component {
  constructor(props) {
    super(props);
    this.state = {
      singleCrypto: {},
      id: this.props.match.params.id
    };
  }

  componentDidMount() {
    this.getEachCrypto();
  }

  async getEachCrypto() {
    try {
      const proxyurl = "https://cors-anywhere.herokuapp.com/";
      const id = this.props.match.params.id;
      let data = await axios.get(
        proxyurl +
          "https://pro-api.coinmarketcap.com/v1/cryptocurrency/info?id=" +
          id,
        {
          headers: {
            "X-CMC_PRO_API_KEY": "e1eb1f30-5c4e-43aa-be04-4b50df00807a"
          }
        }
      );
      this.setState({ singleCrypto: data.data.data });
    } catch (error) {
      console.log("request failed", error);
    }
    console.log(
      this.state.singleCrypto[this.props.match.params.id].urls.website[0]
    ); // this works
  }

  render() {
    const { singleCrypto } = this.state;

    if (Object.keys(singleCrypto).length === 0) {
      console.log("Loading");
    } else {
      console.log(singleCrypto[this.props.match.params.id].urls.website[0]); // this works
    }

    return (

          <Row>
            <Col lg md={3}>

                {singleCrypto[this.props.match.params.id].urls.website[0]} // fails!!!

Rank

Website

Explorer

Message Board

Source Code

Tech Docs

Tags

            </Col>
            <Col lg md={7}>

Price, % change

              <Badge variant="primary">Buy</Badge>
              <Badge variant="primary">Exchange</Badge>
              <Badge variant="primary">Gamble</Badge>
              <Badge variant="primary">Earn Crypto</Badge>
            </Col>
            <Col lg md={2}>
              2 parts
            </Col>
          </Row>

    );
  }
}

export default Crypto;

here is my data sample:

"data": {
        "1": {
            "urls": {
                "website": [
                    "https://bitcoin.org/"
                ],
                "technical_doc": [
                    "https://bitcoin.org/bitcoin.pdf"
                ],
                "twitter": [],
                "reddit": [
                    "https://reddit.com/r/bitcoin"
                ],
                "message_board": [
                    "https://bitcointalk.org"
                ],

Body:
You must return null or a loading state when the data isn't available

if (Object.keys(singleCrypto).length === 0) {
  return null; // you can maintain a loading state too untill data is available
}

With Loading state

class Crypto extends Component {
  constructor(props) {
    super(props);
    this.state = {
      singleCrypto: {},
      id: this.props.match.params.id.
      isLoading: true,
    };
  }

  componentDidMount() {
    this.getEachCrypto();
  }

  async getEachCrypto() {
    try {
      const proxyurl = "https://cors-anywhere.herokuapp.com/";
      const id = this.props.match.params.id;
      this.setState({isLoading: true});
      let data = await axios.get(
        proxyurl +
          "https://pro-api.coinmarketcap.com/v1/cryptocurrency/info?id=" +
          id,
        {
          headers: {
            "X-CMC_PRO_API_KEY": "e1eb1f30-5c4e-43aa-be04-4b50df00807a"
          }
        }
      );
      this.setState({ singleCrypto: data.data.data, isLoading: false });
    } catch (error) {
      console.log("request failed", error);
      this.setState({ isLoading: false });
    }
  }

  render() {
    const { singleCrypto } = this.state;
    if(this.state.isLoading) {
        return <div>Loading...<div>
    }
    ...
  }
}

export default Crypto;


问:
Localhost to local network port redirection on Windows
I have a server that listen on http://localhost:8001 and I want to make it available in the local network. Unfortunately I don't have access to the code and can't modify the above. It doesn't listen to requests from outside the network on port 8001.

I want to make it both available in the local network and change the port to 9001. Is there some tool or way to use OS functionality to solve this?

It's a Windows computer and I don't have admin rights.

Edit:

I noticed both python -m SimpleHTTPServer and http-serv on node works if I use 0.0.0.0 as the address but I don't have the power to modify this program so I wanted some way to redirect the calls in a bidirectional way

Edit2:

It's a OWIN Selfhosted .NET Framework Application.

答:
Simply using your hostname should be enough.

You only need a reverse proxy in order to change the port.

This is easy enough with a caddyfile:

```<code>caddy reverse-proxy --from :9001 --to 127.0.0.1:8001
</code>```

And a caddy Windows release (like caddy_2.0.0_windows_amd64.zip) does not require any administration/elevated privilege: just use the caddy.exe. That is it. No setup, no installation, no registry modification.

Then:

```<code>https://<yourHostname>:9001
</code>```

Body:
Simply using your hostname should be enough.

You only need a reverse proxy in order to change the port.

This is easy enough with a caddyfile:

caddy reverse-proxy --from :9001 --to 127.0.0.1:8001

And a caddy Windows release (like caddy_2.0.0_windows_amd64.zip) does not require any administration/elevated privilege: just use the caddy.exe. That is it. No setup, no installation, no registry modification.

Then:

https://<yourHostname>:9001


问:
How to get app market version information from google play store?
How can I get the application version information from google play store for prompting the user for force/recommended an update of the application when play store application is updated i.e. in case of the user is using old version application. I have already gone through andorid-market-api which is not the official way and also requires oauth login authentication from google. I have also gone through android query
which provides in-app version check, but it is not working in my case.
I found the following two alternatives:

Use server API which will store version info

Use google tags and access it in-app, which is not a preferred way to go.

Are there any other ways to do it easily?

答:
For PHP
It helps for the php developers to get the version code of a particular play store app serverside

```<code>$package='com.whatsapp';
        $html = file_get_contents('https://play.google.com/store/apps/details?id='.$package.'&hl=en');
        preg_match_all('/<span class="htlgb"><div class="IQ1z0d"><span class="htlgb">(.*?)<\/span><\/div><\/span>/s', $html, $output);
print_r($output[1][3]);
</code>```

Body:
For PHP
It helps for the php developers to get the version code of a particular play store app serverside

$package='com.whatsapp';
        $html = file_get_contents('https://play.google.com/store/apps/details?id='.$package.'&hl=en');
        preg_match_all('/<span class="htlgb"><div class="IQ1z0d"><span class="htlgb">(.*?)<\/span><\/div><\/span>/s', $html, $output);
print_r($output[1][3]);


问:
Taking JSON values in a response and mapping them to a state object with keys?
[Noob to Javascript and React] I am using an API that returns an object with values like this. AAPL, AMZN, FB, GOOGL, can be anything based on the function's string array input.

```<code>{
        AAPL: { price: 329.99 },
        AMZN: { price: 2563.05 },
        FB: { price: 239.93 },
        GOOGL: { price: 1469.12 }
}
</code>```

How could I consider dynamically mapping a response like this into a state object like this? The id property doesn't exist, it needs to be created.

```<code>state = {
 stocks: [ { id: 1, name: 'AAPL', price: 329.99 }, { id: 2, name: 'AMZN', price: 2563.05 }, ...]
}
</code>```

I'm able to successfully print the stock names and their prices separately but I am having trouble figuring out how I could wire them into a state object like what's above.

```<code>    function getCurrentPriceOfBatchStocks(_stocks) {
        iex
            .symbols(_stocks)
            .price()
            .then(res => {
                console.log(typeof res);
                console.log(res);
                console.log(Object.keys(res));
                console.log(Object.values(res));
            });
    }
</code>```

答:
Not sure where you're getting id from, so I'm using idx as an example.</p>

```<code>const stocks = Object.keys(resp).map((key, idx) => ({ id: idx + 1, name: key, price: resp[key] }))
</code>```

Body:
[Noob to Javascript and React] I am using an API that returns an object with values like this. AAPL, AMZN, FB, GOOGL, can be anything based on the function's string array input.

{
        AAPL: { price: 329.99 },
        AMZN: { price: 2563.05 },
        FB: { price: 239.93 },
        GOOGL: { price: 1469.12 }
}

How could I consider dynamically mapping a response like this into a state object like this? The id property doesn't exist, it needs to be created.

state = {
 stocks: [ { id: 1, name: 'AAPL', price: 329.99 }, { id: 2, name: 'AMZN', price: 2563.05 }, ...]
}

I'm able to successfully print the stock names and their prices separately but I am having trouble figuring out how I could wire them into a state object like what's above.

    function getCurrentPriceOfBatchStocks(_stocks) {
        iex
            .symbols(_stocks)
            .price()
            .then(res => {
                console.log(typeof res);
                console.log(res);
                console.log(Object.keys(res));
                console.log(Object.values(res));
            });
    }

Body:
Not sure where you're getting id from, so I'm using idx as an example.

const stocks = Object.keys(resp).map((key, idx) => ({ id: idx + 1, name: key, price: resp[key] }))


问:
Form Closing on X C#
After an immense amount of reasearch I am still no closer to a solution.

I have a simple app, 2 forms .NETv3.5 C#.

The application loads the first form, i press 'X' on the windows bar.

The application hides the form and continues to run without exiting the application even though the only form loaded is closed.

The main form Closing method does not get called when the X is pressed because the form is hidden when the x is pressed. Form.Deactivated is called but not Form.Closing.

How can i catch the the even when the X is pressed ? (Then I can implement Application.Exit())

答:
I guess in Program.cs, you call Application.Run passing the main form as parameter. If so, the app won't exit until the main form closes.

To catch the event when X button is pressed, add event handler to secondary form's Closed event, not the main form's. In that event, call main form's Close method (or Application.Exit).

Title: Form Closing on X C#


问:
How to save date type dd/mm/yyyy format in mongodb
Tried to save date format like dd/mm/yyyy in mongodb but this is saved like 2020-06-01T18:30:00.000Z.I want to save like 2020-06-01 in mongodb.How to do it?
Here my code:

data.model.js:

```<code>const mongoose = require('mongoose');

var userSchemaData = new mongoose.Schema({
    p_id: {
        type: String
    },
    product_today: {
        type: Date
    },
    product_afterfive: {
        type: Date
    }
}, {
    versionKey: false,
    collection: 'data'
});

module.exports = mongoose.model('Data', userSchemaData);
</code>```

data.controller.js:

```<code>var moment = require('moment');
var todayDate = new Date();
var afterfiveDays = new Date(new Date().getTime() + (5 * 24 * 60 * 60 * 1000));

module.exports.insertData = (req, res, next) => {
    let collectionName = req.query.collection;
    var Product= mongoose.model(collectionName);
    var todayDateFormat = moment(todayDate, 'DD-MM-YYYY').format('MM-DD-YYYY');
    var afterfiveDaysFormat = moment(afterfiveDays, 'DD-MM-YYYY').format('MM-DD-YYYY');

    var product = new Product({
            p_id: "CS1",
            product_today:todayDateFormat,
            product_afterfive: afterfiveDaysFormat
    });

        product.save(function(error, document) {
            if (error) { console.log(error); } else {
                console.log("Successful inserted");

                res.json({ success: true, msg: 'User inserted.', cname: collectionName });
            }
});
</code>```

答:
As stated in the documentation, mongoose will create a native Date object from the provided date value (see https://mongoosejs.com/docs/tutorials/dates.html)

The reason for this is probably that MongoDB's underlying type for "date" is

BSON Date is a 64-bit integer that represents the number of
  milliseconds since the Unix epoch (Jan 1, 1970). This results in a
  representable date range of about 290 million years into the past and
  future.

so there's no date-type without the time. You can make sure in your application-code to insert dates with the time set to 00:00:00 or store the the "YYYY-MM-DD"-value as a String instead of a Date.

Body:
Tried to save date format like dd/mm/yyyy in mongodb but this is saved like 2020-06-01T18:30:00.000Z.I want to save like 2020-06-01 in mongodb.How to do it?
Here my code:

data.model.js:

const mongoose = require('mongoose');

var userSchemaData = new mongoose.Schema({
    p_id: {
        type: String
    },
    product_today: {
        type: Date
    },
    product_afterfive: {
        type: Date
    }
}, {
    versionKey: false,
    collection: 'data'
});

module.exports = mongoose.model('Data', userSchemaData);

data.controller.js:

var moment = require('moment');
var todayDate = new Date();
var afterfiveDays = new Date(new Date().getTime() + (5 * 24 * 60 * 60 * 1000));

module.exports.insertData = (req, res, next) => {
    let collectionName = req.query.collection;
    var Product= mongoose.model(collectionName);
    var todayDateFormat = moment(todayDate, 'DD-MM-YYYY').format('MM-DD-YYYY');
    var afterfiveDaysFormat = moment(afterfiveDays, 'DD-MM-YYYY').format('MM-DD-YYYY');

    var product = new Product({
            p_id: "CS1",
            product_today:todayDateFormat,
            product_afterfive: afterfiveDaysFormat
    });

        product.save(function(error, document) {
            if (error) { console.log(error); } else {
                console.log("Successful inserted");

                res.json({ success: true, msg: 'User inserted.', cname: collectionName });
            }
});


问:
Deploy Tkinter : error loading Python dll/ LoadLibrary
I am trying to freeze my tkinter application. But I have this problem that suddenly appears. The apps I had freeze don't open either. How can I solve this problem?

I have a second question: if I freeze with cx_freeze, can I open it on another computer that doesn't have python?

答:
Refer to this issue on Github,And I found a solution:

Solution: paths were missing from my PATH. Using the Anaconda Prompt fixed the issue. Then I copied the anaconda paths from echo %PATH%, and I can now run it everywhere, after adjusting the local PATH.

if I freeze with cx_freeze, can I open it on another computer that doesn't have python

If it could work normally in your PC, it could work well mostly on another computer with windows system.


问:
Hazelcast: LinkageError "attempted duplicate class definition for name"
I saw this error in our hazelcast cluster.

The code is trying to call executeOnKey() on an IMap.  e.g.

```<code>    IMap<MyKey, MyCachedClass> myMap = hz.getMap("my-map");
    myMap.executeOnKey(myKey, new EntryProcessor() {
        @Override
        public Object process(Map.Entry entry) {
            return entry.getValue().setItem(item);
        }

        @Override
        public EntryBackupProcessor getBackupProcessor() {
            return null;
        }
    });
</code>```

...and am getting this exception:

```<code>Exception in thread "MYTHREAD" java.lang.LinkageError: loader (instance of com/hazelcast/internal/usercodedeployment/impl/ClassSource): attempted duplicate class definition for name: "com/mycompany/model/Item$ItemEnum"
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
at com.hazelcast.internal.usercodedeployment.impl.ClassSource.define(ClassSource.java:50)
at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.tryToGetClassFromRemote(ClassLocator.java:163)
at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.handleClassNotFoundException(ClassLocator.java:95)
at com.hazelcast.internal.usercodedeployment.impl.ClassSource.loadClass(ClassSource.java:65)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
at com.hazelcast.internal.usercodedeployment.impl.ClassSource.define(ClassSource.java:50)
at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.tryToGetClassFromRemote(ClassLocator.java:161)
at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.handleClassNotFoundException(ClassLocator.java:95)
at com.hazelcast.internal.usercodedeployment.UserCodeDeploymentService.handleClassNotFoundException(UserCodeDeploymentService.java:89)
at com.hazelcast.internal.usercodedeployment.UserCodeDeploymentClassLoader.loadClass(UserCodeDeploymentClassLoader.java:57)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.hazelcast.nio.ClassLoaderUtil.tryLoadClass(ClassLoaderUtil.java:288)
at com.hazelcast.nio.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:237)
at com.hazelcast.nio.IOUtil$ClassLoaderAwareObjectInputStream.resolveClass(IOUtil.java:646)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1868)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1751)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2042)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at java.util.ArrayList.readObject(ArrayList.java:797)
at sun.reflect.GeneratedMethodAccessor18.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1170)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2178)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:82)
at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:75)
at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.read(StreamSerializerAdapter.java:48)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.readObject(AbstractSerializationService.java:269)
at com.hazelcast.internal.serialization.impl.ByteArrayObjectDataInput.readObject(ByteArrayObjectDataInput.java:574)
at com.hazelcast.map.impl.operation.EntryOperation.readInternal(EntryOperation.java:263)
at com.hazelcast.spi.Operation.readData(Operation.java:728)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.readInternal(DataSerializableSerializer.java:160)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.read(DataSerializableSerializer.java:106)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.read(DataSerializableSerializer.java:51)
at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.read(StreamSerializerAdapter.java:48)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toObject(AbstractSerializationService.java:187)
at com.hazelcast.spi.impl.NodeEngineImpl.toObject(NodeEngineImpl.java:323)
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:398)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:153)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:123)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.run(OperationThread.java:110)
at ------ submitted from ------.(Unknown Source)
at com.hazelcast.spi.impl.operationservice.impl.InvocationFuture.resolve(InvocationFuture.java:127)
at com.hazelcast.spi.impl.operationservice.impl.InvocationFuture.resolveAndThrowIfException(InvocationFuture.java:79)
at com.hazelcast.spi.impl.AbstractInvocationFuture.get(AbstractInvocationFuture.java:162)
at com.hazelcast.map.impl.proxy.MapProxySupport.executeOnKeyInternal(MapProxySupport.java:1099)
at com.hazelcast.map.impl.proxy.MapProxyImpl.executeOnKeyInternal(MapProxyImpl.java:109)
at com.hazelcast.map.impl.proxy.MapProxyImpl.executeOnKey(MapProxyImpl.java:757)
at com.mycompany.Processor.java
</code>```

So to me this seemed like:

The 'executeOnKey(item)' command is being sent to the 'other' node in
the cluster where this data is located.

The other node is attempting to deserialize the 'item'.

The other node cannot find the class for the inner enum 'Item$ItemEnum'

The other node makes a request to UserCodeDeploymentService to fetch class definition.

Once the class definition is fetched, and it attempts to create the new class, a
LinkageError occurs.

I just cannot understand why it's getting a duplicate class exception, when it first claimed it couldn't find the class.  And this error is proving difficult to replicate.

We do have 'userCodeDeployment' set to allow loading of remote class definitions.  Our config looks like this:

```<code>UserCodeDeploymentConfig ucdConfig = new UserCodeDeploymentConfig();
ucdConfig.setEnabled(true);
ucdConfig.setClassCacheMode(UserCodeDeploymentConfig.ClassCacheMode.ETERNAL);
ucdConfig.setProviderMode(UserCodeDeploymentConfig.ProviderMode.LOCAL_AND_CACHED_CLASSES);
config.setUserCodeDeploymentConfig(ucdConfig);
</code>```

So it sort of looks like it's doing what I'd expect.  i.e. getting a remote class definition because it can't find it locally.  Is just a puzzle as to why the exception is occurring.

答:
Eventually worked this one out.

A simple example.

Assume two Hazelcast nodes.  Both have userCodeDeployment switched on. (The ability to share class definitions over the wire.)

Node 1 has MyClass on it's classpath, Node 2 does not.

MyClass definition, note the inner enum (I think the inner enum can be swapped for an inner class and the same thing will happen).

```<code>public class MyClass implements Serializable {

    private final InnerEnum enumVal;

    public MyClass(InnerEnum enumVal) {
        this.enumVal = enumVal;
    }

    public enum InnerEnum {
        ONE, TWO, THREE;
    }
}
</code>```

From Node 1, the following code is run:

```<code>hz.getMap("myClassMap").put("myClassKey", new MyClass(MyClass.InnerEnum.ONE));
hz.getMap("myInnerEnumMap").put("myInnerEnumKey", MyClass.InnerEnum.TWO);
</code>```

Then, on Node 2, the following code is run:

```<code>System.out.println(hz.getMap("myInnerEnumMap").get("myInnerEnumKey"));
System.out.println(hz.getMap("myClassMap").get("myClassKey"));
</code>```

On Node 2, I see the following logged:

```<code>[TRACE] ClassLocator Loaded class com.mycompany.MyClass$InnerEnum from Member [myhost]:5701 - cc0b2872-7f5b-484b-a40f-7c7ba1fdc165
TWO
[TRACE] ClassLocator Loaded class com.mycompany.MyClass from Member [myhost]:5701 - cc0b2872-7f5b-484b-a40f-7c7ba1fdc165

Exception in thread "main" java.lang.LinkageError: loader (instance of  com/hazelcast/internal/usercodedeployment/impl/ClassSource): attempted  duplicate class definition for name: "com/mycompany/MyClass$InnerEnum"
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
    at com.hazelcast.internal.usercodedeployment.impl.ClassSource.define(ClassSource.java:50)
    at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.tryToGetClassFromRemote(ClassLocator.java:163)
    at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.handleClassNotFoundException(ClassLocator.java:95)
    at com.hazelcast.internal.usercodedeployment.UserCodeDeploymentService.handleClassNotFoundException(UserCodeDeploymentService.java:89)
    at com.hazelcast.internal.usercodedeployment.UserCodeDeploymentClassLoader.loadClass(UserCodeDeploymentClassLoader.java:57)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at com.hazelcast.nio.ClassLoaderUtil.tryLoadClass(ClassLoaderUtil.java:288)
    at com.hazelcast.nio.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:237)
    at com.hazelcast.nio.IOUtil$ClassLoaderAwareObjectInputStream.resolveClass(IOUtil.java:646)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1868)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1751)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2042)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
    at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:82)
    at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:75)
    at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.read(StreamSerializerAdapter.java:48)
    at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toObject(AbstractSerializationService.java:187)
    at com.hazelcast.map.impl.proxy.MapProxySupport.toObject(MapProxySupport.java:1245)
    at com.hazelcast.map.impl.proxy.MapProxyImpl.get(MapProxyImpl.java:120)
    at com.mycompany.main(Node2.java:74)
</code>```

So:

Node 2 is first trying to fetch and display an instance of MyClass$InnerEnum.  It fetches the InnerEnum class definition from Node 1 over hazelcast.

Node 2 then tries to fetch and display an instance of MyClass.  It fetches the MyClass class definition from Node 1.

Hazelcast then loops through the inner classes of MyClass (which just contains InnerEnum) and asks the class loader to define them without checking whether they already exist.

See (from Hazelcast 3.11.1)
 com.hazelcast.internal.usercodedeployment.impl.ClassLocator:160

```<code>Map<String, byte[]> innerClassDefinitions = classData.getInnerClassDefinitions();
classSource.define(name, classData.getMainClassDefinition());
for (Map.Entry<String, byte[]> entry : innerClassDefinitions.entrySet()) {
    classSource.define(entry.getKey(), entry.getValue());
}
</code>```

The easiest solution in our case was to pull InnerEnum out as a top level Enum.

Body:
I saw this error in our hazelcast cluster.

The code is trying to call executeOnKey() on an IMap.  e.g.

    IMap<MyKey, MyCachedClass> myMap = hz.getMap("my-map");
    myMap.executeOnKey(myKey, new EntryProcessor() {
        @Override
        public Object process(Map.Entry entry) {
            return entry.getValue().setItem(item);
        }

        @Override
        public EntryBackupProcessor getBackupProcessor() {
            return null;
        }
    });

...and am getting this exception:

Exception in thread "MYTHREAD" java.lang.LinkageError: loader (instance of com/hazelcast/internal/usercodedeployment/impl/ClassSource): attempted duplicate class definition for name: "com/mycompany/model/Item$ItemEnum"
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
at com.hazelcast.internal.usercodedeployment.impl.ClassSource.define(ClassSource.java:50)
at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.tryToGetClassFromRemote(ClassLocator.java:163)
at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.handleClassNotFoundException(ClassLocator.java:95)
at com.hazelcast.internal.usercodedeployment.impl.ClassSource.loadClass(ClassSource.java:65)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
at com.hazelcast.internal.usercodedeployment.impl.ClassSource.define(ClassSource.java:50)
at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.tryToGetClassFromRemote(ClassLocator.java:161)
at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.handleClassNotFoundException(ClassLocator.java:95)
at com.hazelcast.internal.usercodedeployment.UserCodeDeploymentService.handleClassNotFoundException(UserCodeDeploymentService.java:89)
at com.hazelcast.internal.usercodedeployment.UserCodeDeploymentClassLoader.loadClass(UserCodeDeploymentClassLoader.java:57)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.hazelcast.nio.ClassLoaderUtil.tryLoadClass(ClassLoaderUtil.java:288)
at com.hazelcast.nio.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:237)
at com.hazelcast.nio.IOUtil$ClassLoaderAwareObjectInputStream.resolveClass(IOUtil.java:646)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1868)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1751)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2042)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at java.util.ArrayList.readObject(ArrayList.java:797)
at sun.reflect.GeneratedMethodAccessor18.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1170)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2178)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:82)
at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:75)
at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.read(StreamSerializerAdapter.java:48)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.readObject(AbstractSerializationService.java:269)
at com.hazelcast.internal.serialization.impl.ByteArrayObjectDataInput.readObject(ByteArrayObjectDataInput.java:574)
at com.hazelcast.map.impl.operation.EntryOperation.readInternal(EntryOperation.java:263)
at com.hazelcast.spi.Operation.readData(Operation.java:728)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.readInternal(DataSerializableSerializer.java:160)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.read(DataSerializableSerializer.java:106)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.read(DataSerializableSerializer.java:51)
at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.read(StreamSerializerAdapter.java:48)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toObject(AbstractSerializationService.java:187)
at com.hazelcast.spi.impl.NodeEngineImpl.toObject(NodeEngineImpl.java:323)
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:398)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:153)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:123)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.run(OperationThread.java:110)
at ------ submitted from ------.(Unknown Source)
at com.hazelcast.spi.impl.operationservice.impl.InvocationFuture.resolve(InvocationFuture.java:127)
at com.hazelcast.spi.impl.operationservice.impl.InvocationFuture.resolveAndThrowIfException(InvocationFuture.java:79)
at com.hazelcast.spi.impl.AbstractInvocationFuture.get(AbstractInvocationFuture.java:162)
at com.hazelcast.map.impl.proxy.MapProxySupport.executeOnKeyInternal(MapProxySupport.java:1099)
at com.hazelcast.map.impl.proxy.MapProxyImpl.executeOnKeyInternal(MapProxyImpl.java:109)
at com.hazelcast.map.impl.proxy.MapProxyImpl.executeOnKey(MapProxyImpl.java:757)
at com.mycompany.Processor.java

So to me this seemed like:

The 'executeOnKey(item)' command is being sent to the 'other' node in
the cluster where this data is located.

The other node is attempting to deserialize the 'item'.

The other node cannot find the class for the inner enum 'Item$ItemEnum'

The other node makes a request to UserCodeDeploymentService to fetch class definition.

Once the class definition is fetched, and it attempts to create the new class, a
LinkageError occurs.

I just cannot understand why it's getting a duplicate class exception, when it first claimed it couldn't find the class.  And this error is proving difficult to replicate.

We do have 'userCodeDeployment' set to allow loading of remote class definitions.  Our config looks like this:

UserCodeDeploymentConfig ucdConfig = new UserCodeDeploymentConfig();
ucdConfig.setEnabled(true);
ucdConfig.setClassCacheMode(UserCodeDeploymentConfig.ClassCacheMode.ETERNAL);
ucdConfig.setProviderMode(UserCodeDeploymentConfig.ProviderMode.LOCAL_AND_CACHED_CLASSES);
config.setUserCodeDeploymentConfig(ucdConfig);

So it sort of looks like it's doing what I'd expect.  i.e. getting a remote class definition because it can't find it locally.  Is just a puzzle as to why the exception is occurring.

Body:
Eventually worked this one out.

A simple example.

Assume two Hazelcast nodes.  Both have userCodeDeployment switched on. (The ability to share class definitions over the wire.)

Node 1 has MyClass on it's classpath, Node 2 does not.

MyClass definition, note the inner enum (I think the inner enum can be swapped for an inner class and the same thing will happen).

public class MyClass implements Serializable {

    private final InnerEnum enumVal;

    public MyClass(InnerEnum enumVal) {
        this.enumVal = enumVal;
    }

    public enum InnerEnum {
        ONE, TWO, THREE;
    }
}

From Node 1, the following code is run:

hz.getMap("myClassMap").put("myClassKey", new MyClass(MyClass.InnerEnum.ONE));
hz.getMap("myInnerEnumMap").put("myInnerEnumKey", MyClass.InnerEnum.TWO);

Then, on Node 2, the following code is run:

System.out.println(hz.getMap("myInnerEnumMap").get("myInnerEnumKey"));
System.out.println(hz.getMap("myClassMap").get("myClassKey"));

On Node 2, I see the following logged:

[TRACE] ClassLocator Loaded class com.mycompany.MyClass$InnerEnum from Member [myhost]:5701 - cc0b2872-7f5b-484b-a40f-7c7ba1fdc165
TWO
[TRACE] ClassLocator Loaded class com.mycompany.MyClass from Member [myhost]:5701 - cc0b2872-7f5b-484b-a40f-7c7ba1fdc165

Exception in thread "main" java.lang.LinkageError: loader (instance of  com/hazelcast/internal/usercodedeployment/impl/ClassSource): attempted  duplicate class definition for name: "com/mycompany/MyClass$InnerEnum"
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
    at com.hazelcast.internal.usercodedeployment.impl.ClassSource.define(ClassSource.java:50)
    at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.tryToGetClassFromRemote(ClassLocator.java:163)
    at com.hazelcast.internal.usercodedeployment.impl.ClassLocator.handleClassNotFoundException(ClassLocator.java:95)
    at com.hazelcast.internal.usercodedeployment.UserCodeDeploymentService.handleClassNotFoundException(UserCodeDeploymentService.java:89)
    at com.hazelcast.internal.usercodedeployment.UserCodeDeploymentClassLoader.loadClass(UserCodeDeploymentClassLoader.java:57)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at com.hazelcast.nio.ClassLoaderUtil.tryLoadClass(ClassLoaderUtil.java:288)
    at com.hazelcast.nio.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:237)
    at com.hazelcast.nio.IOUtil$ClassLoaderAwareObjectInputStream.resolveClass(IOUtil.java:646)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1868)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1751)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2042)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
    at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:82)
    at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:75)
    at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.read(StreamSerializerAdapter.java:48)
    at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toObject(AbstractSerializationService.java:187)
    at com.hazelcast.map.impl.proxy.MapProxySupport.toObject(MapProxySupport.java:1245)
    at com.hazelcast.map.impl.proxy.MapProxyImpl.get(MapProxyImpl.java:120)
    at com.mycompany.main(Node2.java:74)

So:

Node 2 is first trying to fetch and display an instance of MyClass$InnerEnum.  It fetches the InnerEnum class definition from Node 1 over hazelcast.

Node 2 then tries to fetch and display an instance of MyClass.  It fetches the MyClass class definition from Node 1.

Hazelcast then loops through the inner classes of MyClass (which just contains InnerEnum) and asks the class loader to define them without checking whether they already exist.

See (from Hazelcast 3.11.1)
 com.hazelcast.internal.usercodedeployment.impl.ClassLocator:160

Map<String, byte[]> innerClassDefinitions = classData.getInnerClassDefinitions();
classSource.define(name, classData.getMainClassDefinition());
for (Map.Entry<String, byte[]> entry : innerClassDefinitions.entrySet()) {
    classSource.define(entry.getKey(), entry.getValue());
}

The easiest solution in our case was to pull InnerEnum out as a top level Enum.


答:
i don't real know this is possible but i found the function you can use instead

function GetFormattedDate() {
  var todayTime = new Date();
  var month = todayTime.getMonth() + 1;
  var day = todayTime.getDate();
  var year = todayTime.getFullYear();
  return month + "/" + day + "/" + year;
}
console.log(GetFormattedDate());```

so you can add more in the function or edit what the function will return as a format according to your will

Title: How to change format to standard time JavaScript

Body:
I have a date string in JavaScript which is arranged in a particular manner. How do I rearrange this in order to fit standard time?

let date = "2020-06-01T00:00:00Z"

How do I rearrange the date variable in order to match the format MM/DD, YYYY ?

Body:
i don't real know this is possible but i found the function you can use instead

function GetFormattedDate() {
  var todayTime = new Date();
  var month = todayTime.getMonth() + 1;
  var day = todayTime.getDate();
  var year = todayTime.getFullYear();
  return month + "/" + day + "/" + year;
}
console.log(GetFormattedDate());

so you can add more in the function or edit what the function will return as a format according to your will


问:
How to move the file pointer to next character through "ifstream" without "getting" any character, just like "fseek" does?
seekg uses ios as the second argument, and ios can be set to end or beg or some other values as shown here: http://www.cplusplus.com/reference/iostream/ios/

I just want the pointer to move to the next character, how is that to be accomplished through ifstream?

EDIT
Well, the problem is that I want a function in ifstream similar to fseek, which moves the pointer without reading anything.

答:
Yes. Its called seekg() as you seem to already know?

```<code>std::ifstream is("plop.txt" );

// Do Stuff

is.seekg (1, std::ios::cur);  // Move 1 character forward from the current position.
</code>```

Note this is the same as:

```<code>is.get();

// or

is.ignore();
</code>```

Body:
Yes. Its called seekg() as you seem to already know?

std::ifstream is("plop.txt" );

// Do Stuff

is.seekg (1, std::ios::cur);  // Move 1 character forward from the current position.

Note this is the same as:

is.get();

// or

is.ignore();


问:
Get children for any level in tree structure but without theirs children using Hibernate?
I have a Folder entity in Hibernate, like so:

```<code>@Entity
@Table(name = "folders")
public class Folder {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "folder_id", unique = true, nullable = false)
    private int id;

    @NonNull
    @Column(name = "name", length = 100, unique = true, nullable = false)
    private String name;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", orphanRemoval = true)
    @Column(name = "sub_folders")
    private Set<Folder> childFolders = new HashSet<>();

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JsonIgnore
    @JoinColumn(name = "parent", referencedColumnName = "folder_id", nullable = true)
    private Folder parent;

    public Folder() {
    }

}
</code>```

I'm trying to write a finder method or custom query which will do what I wrote in the subject.

So if I send a request going like folders/{parent_folder_id}, let's say value being 1, I should get objects 4 and 5, but without their children, so not including 6,7,8 and 9.

Ideally, hibernate query would be preferred. If not, any sql language is also fine. I'll try to tumble it up to hibernate.

This is what I got, I still get children...

```<code>@Query(value = "Select * from folders f where f.parent = ?1 ", nativeQuery = true)
Set<Folder> getFolders(int folder_id);
</code>```

答:
I got what I need with following query:

```<code> @Query(value = "Select folder_id, name, parent From folders f Where f.parent = ?1", nativeQuery = true)
</code>```

This will give me just name of the folder and its Id.

Body:
I have a Folder entity in Hibernate, like so:

@Entity
@Table(name = "folders")
public class Folder {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "folder_id", unique = true, nullable = false)
    private int id;

    @NonNull
    @Column(name = "name", length = 100, unique = true, nullable = false)
    private String name;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", orphanRemoval = true)
    @Column(name = "sub_folders")
    private Set<Folder> childFolders = new HashSet<>();

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JsonIgnore
    @JoinColumn(name = "parent", referencedColumnName = "folder_id", nullable = true)
    private Folder parent;

    public Folder() {
    }

}

I'm trying to write a finder method or custom query which will do what I wrote in the subject.

So if I send a request going like folders/{parent_folder_id}, let's say value being 1, I should get objects 4 and 5, but without their children, so not including 6,7,8 and 9.

Ideally, hibernate query would be preferred. If not, any sql language is also fine. I'll try to tumble it up to hibernate.

This is what I got, I still get children...

@Query(value = "Select * from folders f where f.parent = ?1 ", nativeQuery = true)
Set<Folder> getFolders(int folder_id);

Body:
I got what I need with following query:

 @Query(value = "Select folder_id, name, parent From folders f Where f.parent = ?1", nativeQuery = true)

This will give me just name of the folder and its Id.


问:
How can I get the referrer URL in Spring Webflux?
How can I get the referrer URL in Spring Webflux?
I tried to look into the header attributes in ServerWebExchange exchange object but could not found the same.
Can someone please help me here.

答:
You just obtain it as a normal header - it doesn't really matter what mechanism you use to do this, since they all have header access.

I tried to look into the header attributes in ServerWebExchange

If you want it on ServerWebExchange, you can definitely obtain it via the following:

```<code>serverWebExchange.getRequest().getHeaders().getFirst("referer");
</code>```

If you want it as a parameter to a normal REST mapping, you can just use @RequestHeader:

```<code>@GetMapping("/greeting")
public Mono<String> greeting(@RequestHeader("referer") Optional<String> referer) {
    //...
}
</code>```

Or if you're using a ServerRequest:

```<code>public Mono<ServerResponse> greeting(ServerRequest request) {
    String referer = request.headers().firstHeader("referer");
    //...
}
</code>```

Body:
You just obtain it as a normal header - it doesn't really matter what mechanism you use to do this, since they all have header access.

I tried to look into the header attributes in ServerWebExchange

If you want it on ServerWebExchange, you can definitely obtain it via the following:

serverWebExchange.getRequest().getHeaders().getFirst("referer");

If you want it as a parameter to a normal REST mapping, you can just use @RequestHeader:

@GetMapping("/greeting")
public Mono<String> greeting(@RequestHeader("referer") Optional<String> referer) {
    //...
}

Or if you're using a ServerRequest:

public Mono<ServerResponse> greeting(ServerRequest request) {
    String referer = request.headers().firstHeader("referer");
    //...
}


问:
weird behaviour with svelte store and routify $params,
Im doing some kind of a forum where all the messages are linked to each other in some way. To save DB reads, I'm storing messages in a $messageStore as $messageStore[messageId].
I'm using routify's $params to navigate from /message/id1 to /message/id2 etc, where each page contains the message identified in the $params, but also other linked messages that might or might not already be in the store..

My problem is:

1st, the components are not unmounting, so I trigger that when $params change by flicking a value for 1ms that disables the rendering of the main component and forces the init() function to check what it needs to fetch on the DB or not.. It is ugly, it seems to work so far, but I bet this will fail one day depending on the machine it runs on.

2nd, after doing that, I ran into things that I didn't understand. The $messageStore doesn't change while the page is changing, but all of a sudden I get plenty of undefined value. It seems like the $params are going from value1 to nothing to value2.
Also if I check in the init() function if($messageStore[$params.id].someKey==="someValue"), it doesn't pass, although I'm sure it's in the store.

If I did

console.log($messageStore[$params.id].someKey) console.log($messageStore[$params.id].someKey==="someValue") if($messageStore[$params.id].someKey==="someValue"){console.log('passed')}else{console.log("failed")}

I got:

```<code>"someValue"
true
"failed"
</code>```

It is like if console.log() is not giving the result at the time of execution..

Before using Routify, I had the same king of stuff with svelte-spa-router, so It might be something that I don't get with svelte and changing store values and order of execution..

I seemed to find a way around by passing the params with a scoped prop from the top component that flickers on page change, but if somebody could teach me something there, I would be really grateful..

答:
I'm confused by what you're trying to achieve, how you're trying to achieve it and what problem 1 is. To get started I'm just going to throw some bullet points at you which may or may not help. I hope that's okay.

Reactivity should be handled with $:. Ie. to listen for changes on a store you need to write. $: console.log($mystore)

Routify 1.8 beta supports serviceworkers, offline availability, prefetching of external assets and caching. This might help with duplicate requests to your API.

I'm using routify's $params to navigate from /message/id1 to /message/id2 etc

^ What does this mean?

Could you create a replication of the issue on Codesandbox?

I wish I were of more help, but the issue feels somewhat black-boxy.

Body:
Im doing some kind of a forum where all the messages are linked to each other in some way. To save DB reads, I'm storing messages in a $messageStore as $messageStore[messageId].
I'm using routify's $params to navigate from /message/id1 to /message/id2 etc, where each page contains the message identified in the $params, but also other linked messages that might or might not already be in the store..

My problem is:

1st, the components are not unmounting, so I trigger that when $params change by flicking a value for 1ms that disables the rendering of the main component and forces the init() function to check what it needs to fetch on the DB or not.. It is ugly, it seems to work so far, but I bet this will fail one day depending on the machine it runs on.

2nd, after doing that, I ran into things that I didn't understand. The $messageStore doesn't change while the page is changing, but all of a sudden I get plenty of undefined value. It seems like the $params are going from value1 to nothing to value2.
Also if I check in the init() function if($messageStore[$params.id].someKey==="someValue"), it doesn't pass, although I'm sure it's in the store.

If I did

console.log($messageStore[$params.id].someKey) console.log($messageStore[$params.id].someKey==="someValue") if($messageStore[$params.id].someKey==="someValue"){console.log('passed')}else{console.log("failed")}

I got:

"someValue"
true
"failed"

It is like if console.log() is not giving the result at the time of execution..

Before using Routify, I had the same king of stuff with svelte-spa-router, so It might be something that I don't get with svelte and changing store values and order of execution..

I seemed to find a way around by passing the params with a scoped prop from the top component that flickers on page change, but if somebody could teach me something there, I would be really grateful..