问:
How to diff different files in two different directories and store the different files in a new directory
I have two directories, dir1 and dir2 with m and n files in them, respectively. the condition may be either m>n or m

I want to diff the files in both the directories and want to store the diffed files in a new directory, diffdir.

So the diffdir should have only files that differs in both the dir.

I used

```<code>diff -r dir1 dir2 |  grep dir2
</code>```

It gives me the files that are different in both the directories

```<code>diff -r dir1/DISP.case_sc.in.XXX dir2/**DISP.case_sc.in.XXX**
</code>```

where XXX may varies from 001 to 999 (I have manually added ** here to make the name bold).
I need only files (bold one) in diffdir

as  number of files in both the directories are not same so in case of m>n it also gives  as the output of above command (diff -r dir1 dir2 |  grep dir2)

```<code>Only in dir2: DISP.case_sc.in.YYY
</code>```

I also want these DISP.case_sc.in.YYY  files in diffdir. Here YYY are the number of files that are equal to the difference m-n. Example if m=020 and n=010 so this YYY will vary from 011 to 020.

In both the dirs (1&2) some files will be exactly same that are not printed with the diff command, I need those files in a another directory name nodiffdir.

Sample input with files named to indicate their relationship to each other:

```<code>dir1
    dir1_only
    comm_diff
    comm_same

dir2
    dir2_only
    comm_diff
    comm_same
</code>```

Expected output (dir1 and dir2 left unchanged):

```<code>samedir
    comm_same   # copied as-is from dir1 or dir2

diffdir
    comm_diff   # output of "diff dir1/comm_diff dir2/comm_diff"
    dir1_only   # copied as-is from dir1
    dir2_only   # copied as-is from dir2
</code>```

答:
This might work for you (GNU sed):

```<code>mkdir dir3
diff -r dir1 dir2 |
sed '/dir2/!d;s#: #/#;s/.* //;s/.*/cp & &/;s/dir2/dir3/2'
</code>```

Make a new directory dir3

Diff the two directories dir1 and dir2 and pipe the output to a sed invocation.

Convert each line that contains dir2 into a copy command.

If the output, matches what you expect then copy for real by adding an e command:

```<code>mkdir dir3
diff -r dir1 dir2 |
sed '/dir2/!d;s#: #/#;s/.* //;s/.*/cp & &/;s/dir2/dir3/2;e'
</code>```

Body:
I have two directories, dir1 and dir2 with m and n files in them, respectively. the condition may be either m>n or m

I want to diff the files in both the directories and want to store the diffed files in a new directory, diffdir.

So the diffdir should have only files that differs in both the dir.

I used

diff -r dir1 dir2 |  grep dir2

It gives me the files that are different in both the directories

diff -r dir1/DISP.case_sc.in.XXX dir2/**DISP.case_sc.in.XXX**

where XXX may varies from 001 to 999 (I have manually added ** here to make the name bold).
I need only files (bold one) in diffdir

as  number of files in both the directories are not same so in case of m>n it also gives  as the output of above command (diff -r dir1 dir2 |  grep dir2)

Only in dir2: DISP.case_sc.in.YYY

I also want these DISP.case_sc.in.YYY  files in diffdir. Here YYY are the number of files that are equal to the difference m-n. Example if m=020 and n=010 so this YYY will vary from 011 to 020.

In both the dirs (1&2) some files will be exactly same that are not printed with the diff command, I need those files in a another directory name nodiffdir.

Sample input with files named to indicate their relationship to each other:

dir1
    dir1_only
    comm_diff
    comm_same

dir2
    dir2_only
    comm_diff
    comm_same

Expected output (dir1 and dir2 left unchanged):

samedir
    comm_same   # copied as-is from dir1 or dir2

diffdir
    comm_diff   # output of "diff dir1/comm_diff dir2/comm_diff"
    dir1_only   # copied as-is from dir1
    dir2_only   # copied as-is from dir2

Body:
This might work for you (GNU sed):

mkdir dir3
diff -r dir1 dir2 |
sed '/dir2/!d;s#: #/#;s/.* //;s/.*/cp & &/;s/dir2/dir3/2'

Make a new directory dir3

Diff the two directories dir1 and dir2 and pipe the output to a sed invocation.

Convert each line that contains dir2 into a copy command.

If the output, matches what you expect then copy for real by adding an e command:

mkdir dir3
diff -r dir1 dir2 |
sed '/dir2/!d;s#: #/#;s/.* //;s/.*/cp & &/;s/dir2/dir3/2;e'


来源: stackexchange

问:
Android Studio missing essential plugin org.jetbrains.android
I have just updated to Android Studio 4.1 Canary 9, but I am getting the following error:

```<code>Missing essential plugin:

  org.jetbrains.android

Please reinstall Android Studio from scratch.
</code>```

I've tried reinstalling Android Studio from scratch, as the error says, but nothing changes.

答:
On Mac OS

Open ~/Library/Application Support/Google/AndroidStudioXXXX.X

delete disabled_plugins.txt

restart Android Studio

ContentLicense: CC BY-SA 4.0

Body:
I have just updated to Android Studio 4.1 Canary 9, but I am getting the following error:

Missing essential plugin:

  org.jetbrains.android

Please reinstall Android Studio from scratch.

I've tried reinstalling Android Studio from scratch, as the error says, but nothing changes.


问:
Calling a function periodically in C
I want to call a function which creates files periodically on every 5 seconds in C.
The function code is below which creates files.

```<code>void file_create(int time) {
        snprintf(filename, sizeof(filename),"%s_%d", "data", index);
        FILE *fp = fopen (filename, "w");
        index++;
}
</code>```

file name will be data_0, data_1, data_2 and goes on on every call.

how to call the above function periodically every 5 seconds from main function if i put an infinite loop like below

```<code>while(1){
    file_create();
    Sleep(5000);
}
</code>```

this is not allowing to execute the lines below the while loop.

How to achieve this by calling above function periodically without holding execution of rest of the program ?

答:
You do this with multi-threading, which is a big topic by itself. I'd recommend to study how POSIX threads (pthreads) work before anything else.

In Windows, that means that the thread should waiting for a custom event "close the thread" for 5000ms. If you get the event, stop the thread. Otherwise in case of timeout, perform the periodic task. Windows uses a different thread API than POSIX.

And also different Sleep(ms) (Windows) vs sleep(s) (POSIX) functions...

Title: Calling a function periodically in C

Body:
I want to call a function which creates files periodically on every 5 seconds in C.
The function code is below which creates files.

void file_create(int time) {
        snprintf(filename, sizeof(filename),"%s_%d", "data", index);
        FILE *fp = fopen (filename, "w");
        index++;
}

file name will be data_0, data_1, data_2 and goes on on every call.

how to call the above function periodically every 5 seconds from main function if i put an infinite loop like below

while(1){
    file_create();
    Sleep(5000);
}

this is not allowing to execute the lines below the while loop.

How to achieve this by calling above function periodically without holding execution of rest of the program ?


问:
Adding data to createTableViewRow() in appcelerator
How can i add custom data to a TableViewRow?

I'm using createTableViewRow() to setup a TableRow which I'm then added labels and images to it, then finally putting all these TableRows in a TableView. This works fine, but the rows need to have a "date" attribute attached to them, as I'm sorted these rows by dates before they are shown in the TableView.

How would i add a "date" to these TableRows? All these are unixtimestamps.

答:
```<code>var row = Ti.UI.createTableViewRow({height:50, _date_var: date});
</code>```

it can just be attached as a property and retrieved like this

```<code>row._date_var
</code>```

ContentLicense: CC BY-SA 3.0

Body:
var row = Ti.UI.createTableViewRow({height:50, _date_var: date});

it can just be attached as a property and retrieved like this

row._date_var


问:
UPS Shipping REST API
I am wanting to make a dummy REST call using UPS's API to generate a test fake shipment request.

I am following the REST UPS documentation for the shipping package:

```<code>https://www.ups.com/upsdeveloperkit/downloadresource?loc=en_US
</code>```

Page 116 shows an example of a client application creating a shipment and getting a successful response with a shipping label. I would like to re-create this so I have attempted to POST some fake data to the TEST URL address:

```<code>https://wwwcie.ups.com/ship/v1/shipments
</code>```

I make the request (with header and body information), but I keep receiving error code 120100 (missing or invalid shipper number).

A lot of forums posts are saying it has something to do with my address not being setup on my UPS account, but I already have an address setup on my account, and I just want to make a fake request to the TEST URL endpoint.

Here is the body of request:

```<code>{
"ShipmentRequest":{
"Shipment":{ "Description":"1206 PTR", "Shipper":{
"Name":"ShipperName", "AttentionName":"AttentionName", "TaxIdentificationNumber":"TaxID", "Phone":{
"Number":"1234567890" },
"ShipperNumber":"ShipperNumber", "Address":{
"AddressLine":"AddressLine", "City":"City", "StateProvinceCode":"STD", "PostalCode":"PostalCode", "CountryCode":"EN"
} },
"ShipTo":{
"Name":"ShipToName", "AttentionName":"AttentionName", "Phone":{
"Number":"1234567890" },
"FaxNumber":"1234567999", "TaxIdentificationNumber":"456999", "Address":{
"AddressLine":"AddressLine", "City":"City", "StateProvinceCode":"STD", "PostalCode":"PostalCode", "CountryCode":"EN"
} },
"ShipFrom":{ "Name":"ShipperName", "AttentionName":"AttentionName", "Phone":{
"Number":"1234567890" },
"FaxNumber":"1234567999", "TaxIdentificationNumber":"456999", "Address":{
"AddressLine":"AddressLine", "City":"City",
"StateProvinceCode":"STD", "PostalCode":"PsotalCode", "CountryCode":"EN"
} },
"PaymentInformation":{ "ShipmentCharge":{
"Type":"01", "BillShipper":{
"AccountNumber":"AccountNumber" }
} },
"Service":{
"Code":"01", "Description":"Expedited"
},
"Package":[{ "Description":"International Goods", "Packaging":{
"Code":"02" },
"PackageWeight":{ "UnitOfMeasurement":{
"Code":"LBS" },
"Weight":"10" },
"PackageServiceOptions":"" },
{
"Description":"International Goods", "Packaging":{
"Code":"02" },
"PackageWeight":{ "UnitOfMeasurement":{
"Code":"LBS" },
"Weight":"20" },
"PackageServiceOptions":"" }]
, "ItemizedChargesRequestedIndicator":"", "RatingMethodRequestedIndicator":"", "TaxInformationIndicator":"", "ShipmentRatingOptions":{
"NegotiatedRatesIndicator":"" }
}, "LabelSpecification":{
"LabelImageFormat":{ "Code":"GIF"
} }
} }
</code>```

答: I resolved this issue by finding the Shipper Number (Account Number) linked to the UPS developer account.</p>

Title: UPS Shipping REST API

Body:
I am wanting to make a dummy REST call using UPS's API to generate a test fake shipment request.

I am following the REST UPS documentation for the shipping package:

https://www.ups.com/upsdeveloperkit/downloadresource?loc=en_US

Page 116 shows an example of a client application creating a shipment and getting a successful response with a shipping label. I would like to re-create this so I have attempted to POST some fake data to the TEST URL address:

https://wwwcie.ups.com/ship/v1/shipments

I make the request (with header and body information), but I keep receiving error code 120100 (missing or invalid shipper number).

A lot of forums posts are saying it has something to do with my address not being setup on my UPS account, but I already have an address setup on my account, and I just want to make a fake request to the TEST URL endpoint.

Here is the body of request:

{
"ShipmentRequest":{
"Shipment":{ "Description":"1206 PTR", "Shipper":{
"Name":"ShipperName", "AttentionName":"AttentionName", "TaxIdentificationNumber":"TaxID", "Phone":{
"Number":"1234567890" },
"ShipperNumber":"ShipperNumber", "Address":{
"AddressLine":"AddressLine", "City":"City", "StateProvinceCode":"STD", "PostalCode":"PostalCode", "CountryCode":"EN"
} },
"ShipTo":{
"Name":"ShipToName", "AttentionName":"AttentionName", "Phone":{
"Number":"1234567890" },
"FaxNumber":"1234567999", "TaxIdentificationNumber":"456999", "Address":{
"AddressLine":"AddressLine", "City":"City", "StateProvinceCode":"STD", "PostalCode":"PostalCode", "CountryCode":"EN"
} },
"ShipFrom":{ "Name":"ShipperName", "AttentionName":"AttentionName", "Phone":{
"Number":"1234567890" },
"FaxNumber":"1234567999", "TaxIdentificationNumber":"456999", "Address":{
"AddressLine":"AddressLine", "City":"City",
"StateProvinceCode":"STD", "PostalCode":"PsotalCode", "CountryCode":"EN"
} },
"PaymentInformation":{ "ShipmentCharge":{
"Type":"01", "BillShipper":{
"AccountNumber":"AccountNumber" }
} },
"Service":{
"Code":"01", "Description":"Expedited"
},
"Package":[{ "Description":"International Goods", "Packaging":{
"Code":"02" },
"PackageWeight":{ "UnitOfMeasurement":{
"Code":"LBS" },
"Weight":"10" },
"PackageServiceOptions":"" },
{
"Description":"International Goods", "Packaging":{
"Code":"02" },
"PackageWeight":{ "UnitOfMeasurement":{
"Code":"LBS" },
"Weight":"20" },
"PackageServiceOptions":"" }]
, "ItemizedChargesRequestedIndicator":"", "RatingMethodRequestedIndicator":"", "TaxInformationIndicator":"", "ShipmentRatingOptions":{
"NegotiatedRatesIndicator":"" }
}, "LabelSpecification":{
"LabelImageFormat":{ "Code":"GIF"
} }
} }


问:
Design the NDPA for the following grammar (Pushdown Automata)
Im trying to design the NDPA for the following grammar. I'm confused. Can you help me?</p>
```<code>∑ = {a,b}

G = (V,∑,R,S)
V = {S,T,X}

S -> aTXb
T -> XTS|ε
X -> a|b
</code>```

答:
There are at least two approaches: try to figure out what the language is and then write down an efficient PDA that works for that language; or, if you're lazy, you can cheat and use the construction that proves NPDAs are at least as powerful as CFGs. Let's do the latter, since this language doesn't appear to be super easy to describe.

To use the construction, build a NPDA that does the following:

first, push the nonterminal start symbol S

next, pop from the stack

if the symbol is a terminal, consume that symbol from the NPDA's input and push nothing

if the symbol is a nonterminal, nondeterministically push the right-hand side of every production for the symbol, and do not consume any input

repeat step 2 until you crash (you cannot consume from input a symbol matching the popped terminal symbol) or you run out of input. If you run out of input with an empty stack, then accept. Otherwise, if you crash or if the stack still has stuff in it at the end, reject.

This construction works by nondeterministically constructing every possible derivation in the grammar. NPDAs accept a string if and only if some nondeterministic path accepts it; and that would only happen for our NPDA if there were a valid derivation according to the grammar. By definition, the language of a grammar is exactly the set of strings that have a valid derivation, so we're done.

Body:
Im trying to design the NDPA for the following grammar. I'm confused. Can you help me?

∑ = {a,b}

G = (V,∑,R,S)
V = {S,T,X}

S -> aTXb
T -> XTS|ε
X -> a|b


问:
Visually move from one html element to another - Javascript
For context sake this a school work where I type text into input field and I get options from database that suggest items which have same letters as user has written. It has simple name database attached.

I receive AJAX response and make that into array of names.
I have ul element underneath search field and names which come from response I populate as li items in this ul list. This all works.
What I need is functionality when pressing up / down arrow keys to move from input field into those list items.

on my first try I chose to make datalist instead of ul and I populated datalist with option elements, this worked well as I could move from input to datalist options. However, further down the road I needed to attach event listeners to options which is not possible. Hence I then went to ul / li version.
I cant seem to be able to work out how can I switch from input element into li items.

what i have tryed:

I have eventlistener keydown on input field to check if DownArrow is pressed. This works. Then i tryed following (names is the id of ul).

```<code>let list = document.getElementById('names');
list.firstChild.focus();
list.firstChild.select();
</code>```

Here I get error that "list.firstChild.select is not a function" and im stuck.

link to current version

答:
In order for element.focus() to work on list item (which it does not by default) you have to add tabindex property to list item.

for example:

listitem.setAttribute('tabindex',1);

Body:
For context sake this a school work where I type text into input field and I get options from database that suggest items which have same letters as user has written. It has simple name database attached.

I receive AJAX response and make that into array of names.
I have ul element underneath search field and names which come from response I populate as li items in this ul list. This all works.
What I need is functionality when pressing up / down arrow keys to move from input field into those list items.

on my first try I chose to make datalist instead of ul and I populated datalist with option elements, this worked well as I could move from input to datalist options. However, further down the road I needed to attach event listeners to options which is not possible. Hence I then went to ul / li version.
I cant seem to be able to work out how can I switch from input element into li items.

what i have tryed:

I have eventlistener keydown on input field to check if DownArrow is pressed. This works. Then i tryed following (names is the id of ul).

let list = document.getElementById('names');
list.firstChild.focus();
list.firstChild.select();

Here I get error that "list.firstChild.select is not a function" and im stuck.

link to current version


问:
How to use AzureCLI in azure-pipelines.yml to delete old files on Azure Blob Storage
I'm using Azure DevOps and their Build and Release pipelines. As part of my build I'd like to delete old files from my Azure Blob storage. I'm using an ubuntu-latest vmImage.

This task:

```<code>- task: AzureCLI@2
  displayName: Delete old files
  inputs:
    scriptType: pscore
    scriptLocation: inlineScript
    inlineScript: |
        date=`date -d "1 days ago" '+%Y-%m-%dT%H:%MZ'`
        az storage blob delete-batch -s $web --account-name xenobellstorage --if-unmodified-since $date
</code>```

Produces this error, which doesn't match any params in their documentation.

```<code>Script failed with error: Error: Input required: connectedServiceNameARM
</code>```

If I add azureSubscription: 'Main subscription' to the task, I get this error, with an Authorize resources button that doesn't work.

```<code>There was a resource authorization issue: "The pipeline is not valid. Job Job: Step AzureCLI input connectedServiceNameARM references service connection Main subscription which could not be found. The service connection does not exist or has not been authorized for use. For authorization details, refer to https://aka.ms/yamlauthz."
</code>```

The linked page suggests I go to Project Settings to authorize all pipelines, but that toggle doesn't work.

How can I run this AzureCLI task on my Ubuntu VM?

The full YAML file I used that fixed my problem:

```<code># Node.js
# https://learn.microsoft.com/azure/devops/pipelines/languages/javascript

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: NodeTool@0
  inputs:
    versionSpec: '10.x'
  displayName: 'Install Node.js'

- script: |
    npm install
  displayName: 'npm install'

- script: |
    grunt --gruntfile gruntfile.js prod
  displayName: 'grunt production build'

- task: CopyFiles@2
  displayName: 'Copy files'
  inputs:
    SourceFolder: '$(System.DefaultWorkingDirectory)'
    Contents: |
      game/**
    TargetFolder: '$(Build.ArtifactStagingDirectory)'

- task: PublishBuildArtifacts@1
  displayName: 'Publish files'
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'drop'

- task: AzureCLI@2
  displayName: Delete old files
  inputs:
    azureSubscription: 'Main subscription (abc-123-idd)'
    scriptType: pscore
    scriptLocation: inlineScript
    inlineScript: |
        az storage blob delete-batch -s '$web' --account-name mystorage --if-unmodified-since $(date -d "1 days ago" '+%Y-%m-%dT%H:%MZ')
</code>```

答:
using AzureCLI version 2</p>

```<code>- task: AzureCLI@2
  displayName: "Azure Storage - delete old files"
  inputs:
    azureSubscription: 'xxxx-PAYG(xxx-xxx-xxx-xxx-xxx)'
    scriptType: 'ps'
    scriptLocation: 'inlineScript'
    inlineScript: 'az storage remove --account-name ''xxx'' --container-name ''$web'' -r'
</code>```

Body:
I'm using Azure DevOps and their Build and Release pipelines. As part of my build I'd like to delete old files from my Azure Blob storage. I'm using an ubuntu-latest vmImage.

This task:

- task: AzureCLI@2
  displayName: Delete old files
  inputs:
    scriptType: pscore
    scriptLocation: inlineScript
    inlineScript: |
        date=`date -d "1 days ago" '+%Y-%m-%dT%H:%MZ'`
        az storage blob delete-batch -s $web --account-name xenobellstorage --if-unmodified-since $date

Produces this error, which doesn't match any params in their documentation.

Script failed with error: Error: Input required: connectedServiceNameARM

If I add azureSubscription: 'Main subscription' to the task, I get this error, with an Authorize resources button that doesn't work.

There was a resource authorization issue: "The pipeline is not valid. Job Job: Step AzureCLI input connectedServiceNameARM references service connection Main subscription which could not be found. The service connection does not exist or has not been authorized for use. For authorization details, refer to https://aka.ms/yamlauthz."

The linked page suggests I go to Project Settings to authorize all pipelines, but that toggle doesn't work.

How can I run this AzureCLI task on my Ubuntu VM?

The full YAML file I used that fixed my problem:

# Node.js
# https://learn.microsoft.com/azure/devops/pipelines/languages/javascript

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: NodeTool@0
  inputs:
    versionSpec: '10.x'
  displayName: 'Install Node.js'

- script: |
    npm install
  displayName: 'npm install'

- script: |
    grunt --gruntfile gruntfile.js prod
  displayName: 'grunt production build'

- task: CopyFiles@2
  displayName: 'Copy files'
  inputs:
    SourceFolder: '$(System.DefaultWorkingDirectory)'
    Contents: |
      game/**
    TargetFolder: '$(Build.ArtifactStagingDirectory)'

- task: PublishBuildArtifacts@1
  displayName: 'Publish files'
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'drop'

- task: AzureCLI@2
  displayName: Delete old files
  inputs:
    azureSubscription: 'Main subscription (abc-123-idd)'
    scriptType: pscore
    scriptLocation: inlineScript
    inlineScript: |
        az storage blob delete-batch -s '$web' --account-name mystorage --if-unmodified-since $(date -d "1 days ago" '+%Y-%m-%dT%H:%MZ')

Body:
using AzureCLI version 2

- task: AzureCLI@2
  displayName: "Azure Storage - delete old files"
  inputs:
    azureSubscription: 'xxxx-PAYG(xxx-xxx-xxx-xxx-xxx)'
    scriptType: 'ps'
    scriptLocation: 'inlineScript'
    inlineScript: 'az storage remove --account-name ''xxx'' --container-name ''$web'' -r'


问:
Using tf.switch_case or tf.case with string condition
I am learning tensorflow and have some trouble implementing things that are otherwise easy.

I have a toy function:

```<code>def function(fruit, b):
    if fruit == 'apple':
        return b
    elif fruit == 'banana':
        return b+2
    else:
        return b*3
</code>```

The case syntax is:
tf.case(pred_fn_pairs, default=None, exclusive=False, strict=False, name='case')
where pred_fn_pairs refers to a tuple of (condition, output) and I have trouble rewriting the condition in a fully tensorflow way since it is a string.

How would the above function be written using only tensorflow?

答:
Did you know that tensorflow 2.0 is awesome? use @tf.function:

```<code>@tf.function
def function(fruit, b):
    if fruit == 'apple':
        return b
    elif fruit == 'banana':
        return b+2
    else:
        return b*3
</code>```

tf.autograph will convert it to a tensorflow graph for you under the hood! Woohoo.

If you still want the native tensorflow ops:

```<code>def function(fruit, b):
  tf.cond(tf.equal(fruit, 'apple'), lambda: b, tf.cond(tf.equal(fruit, 'banana'), lambda: b+2, lambda: b*3))
</code>```

Body:
I am learning tensorflow and have some trouble implementing things that are otherwise easy.

I have a toy function:

def function(fruit, b):
    if fruit == 'apple':
        return b
    elif fruit == 'banana':
        return b+2
    else:
        return b*3

The case syntax is:
tf.case(pred_fn_pairs, default=None, exclusive=False, strict=False, name='case')
where pred_fn_pairs refers to a tuple of (condition, output) and I have trouble rewriting the condition in a fully tensorflow way since it is a string.

How would the above function be written using only tensorflow?

Body:
Did you know that tensorflow 2.0 is awesome? use @tf.function:

@tf.function
def function(fruit, b):
    if fruit == 'apple':
        return b
    elif fruit == 'banana':
        return b+2
    else:
        return b*3

tf.autograph will convert it to a tensorflow graph for you under the hood! Woohoo.

If you still want the native tensorflow ops:

def function(fruit, b):
  tf.cond(tf.equal(fruit, 'apple'), lambda: b, tf.cond(tf.equal(fruit, 'banana'), lambda: b+2, lambda: b*3))


问:
Can we update any fhir resource on the basis of patient id?
I am trying to update Encounter resource on the basis of patient id but it is only creating one new record of Encounter rather than updating the existing one. But if i try to update Encounter on the basis of identifier i.e. unique value representing Encounter resource then it is able to update it.

Why is that? Can anyone explain?

答:
One patient will potentially have many (even hundreds) of encounters.  Updates are always driven by the record of the resource itself - every resource (Patient, Encounter, Observation, CarePlan, etc.) has an 'id' element that represents the identifier of that resource on that particular server - sort of like a primary key.  Updates are performed by making a RESTful PUT of the new record to a URL that includes that same identifier.

I.e. an update of an Encounter MUST always be performed with a URL of the form:

PUT [somebaseurl]/Encounter/[serverEncounterId]

The patient associated with the encounter will be referenced from within the Encounter object in the body of the RESTful call, but does not appear in the URL.


问:
Unable to fetch user location details by IP
hello im new to react and trying to build a weather site. i have a search functionality which works, but im also trying to get the local weather for the user.

for this i get city from: https://geoip-db.com/json/

weather api: https://api.openweathermap.org/data/2.5/

then i save that city as a variable in the state so i can use it in the api.

here is the code:
`

```<code>state = {
    geoipCity: "",
}

componentDidMount(){
    const geoApiUrl = "https://geoip-db.com/json/";
    fetch(geoApiUrl)

    .then(res => res.json())
    .then(geoip => {
        this.setState({ geoipCity: geoip.city })
    })
    .catch(err => {
        console.log("Fetch error: " + err);
    });

    console.log("prefetch:" + this.state.geoipCity)
    const weatherApiUrl = `${api.base}weather?q=${this.state.geoipCity}&weather&units=metric&APPID=${api.key}`;
    fetch(weatherApiUrl)

    .then(res => res.json())
    .then(result => {
        console.log(result)

        let locationOutput = document.querySelector("#locationOutput");
        if(result.cod === "404"){
            locationOutput.innerHTML = `${this.state.geoipCity} is not a valid city name`;
        }

        /*
        locationOutput.innerHTML = `
        Your live in ${this.state.geoipCity} and it feels like ${result.main.feels_like}°C`;
        */
    })
    .catch(err => {
        console.log("Fetch error: " + err);
    });
}
</code>```

`

so the first fetch gets the city and saves it in the geoipCity state variable. this i try to use it in the api search.
however right before that i have:

```<code>console.log("prefetch:" + this.state.geoipCity)
</code>```

which shows me that this.state.geoipCity is empty.

any ideas?

EDIT: SOLVED, HERE IS THE CODE IN CASE ANYONE BENEFITS FROM IT IN THE FUTURE

`

```<code>componentDidMount(){
    const geoApiUrl = "https://geoip-db.com/json/";
    fetch(geoApiUrl)

    .then(res => res.json())
    .then(result => {
    console.log(result)

        this.setState({ geoipCity: result.city }, () => {
            //console.log(this.state);
            const weatherApiUrl = `${api.base}weather?q=${this.state.geoipCity}&weather&units=metric&APPID=${api.key}`;
            fetch(weatherApiUrl)

            .then(res => res.json())
            .then(result => {
                console.log(result)

                let locationOutput = document.querySelector("#locationOutput");
                if(result.cod === "404"){
                    locationOutput.innerHTML = `${this.state.geoipCity} is not a valid city name`;
                }

                locationOutput.innerHTML = `
                Your live in ${this.state.geoipCity} and it feels like ${result.main.feels_like}°C`;

            })
            .catch(err => {
                console.log("Fetch error: " + err);
            });
        });

        //this.setState({ geoipCity: geoip.city })
    })
    .catch(err => {
        console.log("Fetch error: " + err);
    });
}
</code>```

`

答:
this.setState is async.

You need to use the callback of setState in order to console.log the new state.

```<code>this.setState({ geoipCity: geoip.city }, (newState) => {
    console.log(newState);
});
</code>```

Every setState will re-render the component but componentDidMount only executes on the first render.

Body:
hello im new to react and trying to build a weather site. i have a search functionality which works, but im also trying to get the local weather for the user.

for this i get city from: https://geoip-db.com/json/

weather api: https://api.openweathermap.org/data/2.5/

then i save that city as a variable in the state so i can use it in the api.

here is the code:
`

state = {
    geoipCity: "",
}

componentDidMount(){
    const geoApiUrl = "https://geoip-db.com/json/";
    fetch(geoApiUrl)

    .then(res => res.json())
    .then(geoip => {
        this.setState({ geoipCity: geoip.city })
    })
    .catch(err => {
        console.log("Fetch error: " + err);
    });

    console.log("prefetch:" + this.state.geoipCity)
    const weatherApiUrl = `${api.base}weather?q=${this.state.geoipCity}&weather&units=metric&APPID=${api.key}`;
    fetch(weatherApiUrl)

    .then(res => res.json())
    .then(result => {
        console.log(result)

        let locationOutput = document.querySelector("#locationOutput");
        if(result.cod === "404"){
            locationOutput.innerHTML = `${this.state.geoipCity} is not a valid city name`;
        }

        /*
        locationOutput.innerHTML = `
        Your live in ${this.state.geoipCity} and it feels like ${result.main.feels_like}°C`;
        */
    })
    .catch(err => {
        console.log("Fetch error: " + err);
    });
}

`

so the first fetch gets the city and saves it in the geoipCity state variable. this i try to use it in the api search.
however right before that i have:

console.log("prefetch:" + this.state.geoipCity)

which shows me that this.state.geoipCity is empty.

any ideas?

EDIT: SOLVED, HERE IS THE CODE IN CASE ANYONE BENEFITS FROM IT IN THE FUTURE

`

componentDidMount(){
    const geoApiUrl = "https://geoip-db.com/json/";
    fetch(geoApiUrl)

    .then(res => res.json())
    .then(result => {
    console.log(result)

        this.setState({ geoipCity: result.city }, () => {
            //console.log(this.state);
            const weatherApiUrl = `${api.base}weather?q=${this.state.geoipCity}&weather&units=metric&APPID=${api.key}`;
            fetch(weatherApiUrl)

            .then(res => res.json())
            .then(result => {
                console.log(result)

                let locationOutput = document.querySelector("#locationOutput");
                if(result.cod === "404"){
                    locationOutput.innerHTML = `${this.state.geoipCity} is not a valid city name`;
                }

                locationOutput.innerHTML = `
                Your live in ${this.state.geoipCity} and it feels like ${result.main.feels_like}°C`;

            })
            .catch(err => {
                console.log("Fetch error: " + err);
            });
        });

        //this.setState({ geoipCity: geoip.city })
    })
    .catch(err => {
        console.log("Fetch error: " + err);
    });
}

`

Body:
this.setState is async.

You need to use the callback of setState in order to console.log the new state.

this.setState({ geoipCity: geoip.city }, (newState) => {
    console.log(newState);
});

Every setState will re-render the component but componentDidMount only executes on the first render.


问:
mysqldump under windows 7 powershell converted all my utf-8 string to latin1 or something alike
i just did a plain old mysql dump with something like this

```<code>mysqldump -h "192.168.0.6" -uroot -p db_name > my_sexy_dump_file.sql.
</code>```

What happened is that dumping the database produced a file where all my utf-8 string were converted to latin1. at least it seems to me that that was done cause now i have 2 letters for each one i had previously.
the result looks like this:

╘┐╒Ñ╒╢╒┐╓Ç╒╕╒╢╒í╒»╒í╒╢ ╒ú╓Ç╒í╒╜╒Ñ╒╢╒╡╒í╒»

╘╗╒╢╒Ñ╒»╒╕╒ó╒í╒╢╒»╒╕╓é╒┤

the original text was armenian.

how can i fix this? executing the dump file produces an error. copy and pasting insert queries  into an mysql client application like sqlyog just writes the corrupted string into the table.

答:
I fixed this by creating a map of the whole alphabet and replacing all corrupted characters one by one.
more details on what i did here: http://fictionalrealm.com/coding/2011/05/29/mysqldump-corrupted-utf8-data-when-dumping-on-windows-machine/</p>

Body:
i just did a plain old mysql dump with something like this

mysqldump -h "192.168.0.6" -uroot -p db_name > my_sexy_dump_file.sql.

What happened is that dumping the database produced a file where all my utf-8 string were converted to latin1. at least it seems to me that that was done cause now i have 2 letters for each one i had previously.
the result looks like this:

╘┐╒Ñ╒╢╒┐╓Ç╒╕╒╢╒í╒»╒í╒╢ ╒ú╓Ç╒í╒╜╒Ñ╒╢╒╡╒í╒»

╘╗╒╢╒Ñ╒»╒╕╒ó╒í╒╢╒»╒╕╓é╒┤

the original text was armenian.

how can i fix this? executing the dump file produces an error. copy and pasting insert queries  into an mysql client application like sqlyog just writes the corrupted string into the table.


问:
Unable to navigate to home page in flutter
I have an app comprising of home and update screens.

I am unable to navigate back to the home screen from the update screen.

See below code for home screen

```<code>  // build the list widget
  Widget _buildTaskWidget(task) {
    return ListTile(
      leading: Icon(Icons.assignment),
      title: Text(task['name']),
      subtitle: Text(task['created_at']),
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => UpdateTask(task: task),
          ),
        );
      }
    );
  }
</code>```

See below code for the update screen

```<code>@override
      Widget build(BuildContext context) {
        // final Task task = ModalRoute.of(context).settings.arguments;
        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: AppBar(
            title: Text('Update Task'),
          ),
          body: ListView(
            children: <Widget>[
              inputWidget(),
              inputWidgetForVendor(),
              inputWidgetForAmount(),
              Container(
                margin: EdgeInsets.fromLTRB(45, 1, 45, 1),
                child: RaisedButton(
                  color: Colors.blueAccent,
                  child: Text('Update Task', style: TextStyle(color: Colors.white)),
                  onPressed: () async {
                     var res = await updateNewTask(_taskTextInput.text, _vendorTextInput.text,  _amountTextInput.text, id);
                     print(res);
                      Navigator.pop(context);
                  },
                ),
              )
            ],
          )// This trailing comma makes auto-formatting nicer for build methods.
        );
      }
</code>```

If I remove the current onPressed function and replace with this below, it works

```<code>onPressed: () { Navigator.pop(context); },
</code>```

What am I doing wrong in the initial function?
The update function successfully updates the list items, however I am unable to navigate back.
See below error logs:

```<code>E/flutter (27123): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'
E/flutter (27123): #0      updateNewTask (package:task/repository/services.dart:67:10)
E/flutter (27123): <asynchronous suspension>
</code>```

Please help.

答:
Maybe outsourcing your async update function is a simple solution at this point, when you want to instantly go back to your home screen. You could print the update directly in the function then.

Just leave onpressed() as it is.

```<code>onPressed: () {
  updateNewTask(_taskTextInput.text, _vendorTextInput.text,  _amountTextInput.text, id);
  Navigator.pop(context);
},
</code>```

Body:
I have an app comprising of home and update screens.

I am unable to navigate back to the home screen from the update screen.

See below code for home screen

  // build the list widget
  Widget _buildTaskWidget(task) {
    return ListTile(
      leading: Icon(Icons.assignment),
      title: Text(task['name']),
      subtitle: Text(task['created_at']),
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => UpdateTask(task: task),
          ),
        );
      }
    );
  }

See below code for the update screen

@override
      Widget build(BuildContext context) {
        // final Task task = ModalRoute.of(context).settings.arguments;
        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: AppBar(
            title: Text('Update Task'),
          ),
          body: ListView(
            children: <Widget>[
              inputWidget(),
              inputWidgetForVendor(),
              inputWidgetForAmount(),
              Container(
                margin: EdgeInsets.fromLTRB(45, 1, 45, 1),
                child: RaisedButton(
                  color: Colors.blueAccent,
                  child: Text('Update Task', style: TextStyle(color: Colors.white)),
                  onPressed: () async {
                     var res = await updateNewTask(_taskTextInput.text, _vendorTextInput.text,  _amountTextInput.text, id);
                     print(res);
                      Navigator.pop(context);
                  },
                ),
              )
            ],
          )// This trailing comma makes auto-formatting nicer for build methods.
        );
      }

If I remove the current onPressed function and replace with this below, it works

onPressed: () { Navigator.pop(context); },

What am I doing wrong in the initial function?
The update function successfully updates the list items, however I am unable to navigate back.
See below error logs:

E/flutter (27123): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'
E/flutter (27123): #0      updateNewTask (package:task/repository/services.dart:67:10)
E/flutter (27123): <asynchronous suspension>

Please help.

Body:
Maybe outsourcing your async update function is a simple solution at this point, when you want to instantly go back to your home screen. You could print the update directly in the function then.

Just leave onpressed() as it is.

onPressed: () {
  updateNewTask(_taskTextInput.text, _vendorTextInput.text,  _amountTextInput.text, id);
  Navigator.pop(context);
},


问:
How to prevent UUID from changing state when using copy-to-clipboard function?
I managed to copy the generated UUID into my clipboard but whenever I click on the button, the UUID (and QR code) changes even though the page did not refresh. How to prevent the UUID from changing its state? Please refer to the codes below;</p>

```<code>import React, { useState } from "react";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import FileCopyIcon from "@material-ui/icons/FileCopy";
import { v4 as uuid } from "uuid";
import QRCode from "react-qr-code";
import { CopyToClipboard } from "react-copy-to-clipboard";

export default function QRGenerator() {
  const adminId = uuid();

  const [qrcode, setQrcode] = useState({
    value: "",
    copied: false,
  });

  return (
    <div>
      <CopyToClipboard
        text={adminId}
        onCopy={() => setQrcode({ copied: true })}
      >
        <Button>
          <FileCopyIcon />
        </Button>
      </CopyToClipboard>

      <Typography align="center" variant="caption" paragraph="true">
        Admin ID : {adminId}
        {qrcode.copied ? <span style={{ color: "red" }}>Copied.</span> : null}
      </Typography>
      <QRCode value={adminId} />
    </div>
  );
}
</code>```

答:
Every time the state is changed, render function is called. So the uuid is called again and it is changed.
If you need the uuid to be constant, we can use useState

```<code>  const [adminId] = useState(uuid());
</code>```

Or We have to pass it as prop from the parent component so that for every rerender it wont change.

Body:
I managed to copy the generated UUID into my clipboard but whenever I click on the button, the UUID (and QR code) changes even though the page did not refresh. How to prevent the UUID from changing its state? Please refer to the codes below;

import React, { useState } from "react";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import FileCopyIcon from "@material-ui/icons/FileCopy";
import { v4 as uuid } from "uuid";
import QRCode from "react-qr-code";
import { CopyToClipboard } from "react-copy-to-clipboard";

export default function QRGenerator() {
  const adminId = uuid();

  const [qrcode, setQrcode] = useState({
    value: "",
    copied: false,
  });

  return (

      <CopyToClipboard
        text={adminId}
        onCopy={() => setQrcode({ copied: true })}
      >
        <Button>
          <FileCopyIcon />
        </Button>
      </CopyToClipboard>

      <Typography align="center" variant="caption" paragraph="true">
        Admin ID : {adminId}
        {qrcode.copied ? Copied. : null}
      </Typography>
      <QRCode value={adminId} />

  );
}

Body:
Every time the state is changed, render function is called. So the uuid is called again and it is changed.
If you need the uuid to be constant, we can use useState

  const [adminId] = useState(uuid());

Or We have to pass it as prop from the parent component so that for every rerender it wont change.


问:
How to split a long regular expression into multiple lines in JavaScript?
I have a very long regular expression, which I wish to split into multiple lines in my JavaScript code to keep each line length 80 characters according to JSLint rules. It's just better for reading, I think.
Here's pattern sample:</p>

```<code>var pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
</code>```

答:
@Hashbrown's great answer got me on the right track. Here's my version, also inspired by this blog.

```<code>function regexp(...args) {
  function cleanup(string) {
    // remove whitespace, single and multi-line comments
    return string.replace(/\s+|\/\/.*|\/\*[\s\S]*?\*\//g, '');
  }

  function escape(string) {
    // escape regular expression
    return string.replace(/[-.*+?^${}()|[\]\\]/g, '\\$&');
  }

  function create(flags, strings, ...values) {
    let pattern = '';
    for (let i = 0; i < values.length; ++i) {
      pattern += cleanup(strings.raw[i]);  // strings are cleaned up
      pattern += escape(values[i]);        // values are escaped
    }
    pattern += cleanup(strings.raw[values.length]);
    return RegExp(pattern, flags);
  }

  if (Array.isArray(args[0])) {
    // used as a template tag (no flags)
    return create('', ...args);
  }

  // used as a function (with flags)
  return create.bind(void 0, args[0]);
}
</code>```

Use it like this:

```<code>regexp('i')`
  //so this is a regex

  //here I am matching some numbers
  (\d+)

  //Oh! See how I didn't need to double backslash that \d?
  ([a-z]{1,3}) /*note to self, this is group #2*/
`
</code>```

To create this RegExp object:

```<code>/(\d+)([a-z]{1,3})/i
</code>```

Body:
I have a very long regular expression, which I wish to split into multiple lines in my JavaScript code to keep each line length 80 characters according to JSLint rules. It's just better for reading, I think.
Here's pattern sample:

var pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

Body:
@Hashbrown's great answer got me on the right track. Here's my version, also inspired by this blog.

function regexp(...args) {
  function cleanup(string) {
    // remove whitespace, single and multi-line comments
    return string.replace(/\s+|\/\/.*|\/\*[\s\S]*?\*\//g, '');
  }

  function escape(string) {
    // escape regular expression
    return string.replace(/[-.*+?^${}()|[\]\\]/g, '\\$&');
  }

  function create(flags, strings, ...values) {
    let pattern = '';
    for (let i = 0; i < values.length; ++i) {
      pattern += cleanup(strings.raw[i]);  // strings are cleaned up
      pattern += escape(values[i]);        // values are escaped
    }
    pattern += cleanup(strings.raw[values.length]);
    return RegExp(pattern, flags);
  }

  if (Array.isArray(args[0])) {
    // used as a template tag (no flags)
    return create('', ...args);
  }

  // used as a function (with flags)
  return create.bind(void 0, args[0]);
}

Use it like this:

regexp('i')`
  //so this is a regex

  //here I am matching some numbers
  (\d+)

  //Oh! See how I didn't need to double backslash that \d?
  ([a-z]{1,3}) /*note to self, this is group #2*/
`

To create this RegExp object:

/(\d+)([a-z]{1,3})/i


问:
Stop YouTube embed after clicking outside modal
When a certain button is clicked on my project, a modal opens up with two YouTube videos I embedded. The problem however is when I click outside this modal to close the modal the videos continue playing (whichever video is being played). I would like the video to stop playing when a user clicks outside the modal.

This is what i have tried

```<code><a class="primary-btn text-uppercase" data-toggle="modal" data-target="#workshops">View</a>
<div class="modal fade" id="workshops" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    A sample of some our workshops and tutorials
                </h4>
            </div>
            <div class="modal-body">
                <div class="resp-container">
                    <iframe class="resp-iframe" src="https://www.youtube.com/embed/-EX-zHVVSI8" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                </div>
                <div class="resp-container">
                    <iframe class="resp-iframe" src="https://www.youtube.com/embed/bUPg5BZj7dY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                </div>
                <span onclick="stopVideo(this.getAttribute('vdoId'))" vdoId="resp-iframe" id="CloseModalButton" data-dismiss="modal"></span>
            </div>
        </div>
    </div>
</div>
<script>
    function stopVideo(id){
        var src = $j('iframe.'+id).attr('src');
        $j('iframe.'+id).attr('src','');
        $j('iframe.'+id).attr('src',src);
    }
</script>
</code>```

Right now I am getting a modal with only one of the videos I embedded and it is not stopping when I close the modal.

Update
Based on the answer given this is what I have tried:

```<code><script>
    $('#workshops').on('hide.bs.modal', function () {
        stopVideo("resp-iframe");
    });
</script>
</code>```

I can no longer close the modal when I click the space outside the modal. This is the error message I am getting in my browser console:

```<code>Uncaught ReferenceError: stopVideo is not defined
    at HTMLDivElement.<anonymous> ((index):564)
    at HTMLDivElement.dispatch (jquery-3.2.1.min.js:3)
    at HTMLDivElement.q.handle (jquery-3.2.1.min.js:3)
    at Object.trigger (jquery-3.2.1.min.js:4)
    at HTMLDivElement.<anonymous> (jquery-3.2.1.min.js:4)
    at Function.each (jquery-3.2.1.min.js:2)
    at r.fn.init.each (jquery-3.2.1.min.js:2)
    at r.fn.init.trigger (jquery-3.2.1.min.js:4)
    at r.t.hide (bootstrap.min.js:6)
    at HTMLDivElement.<anonymous> (bootstrap.min.js:6)
</code>```

答:
The bootstrap modals - which i assume you are using - have 2 events in place that are getting fired on closing. #1 hide.bs.modal #2 hidden.bs.modal. Have a look at the full list of modal events

So to run your stop function when closing your modal you would want to create a new eventhandler like so :

```<code>$('#workshops').on('hide.bs.modal', function() {
  // Stop the videos as soon as the modal's hide function gets called
  stopVideo("resp-iframe"); // your id seems to be a static value you could ofcourse also use the value from your #CloseModalButton
});
</code>```

Body:
When a certain button is clicked on my project, a modal opens up with two YouTube videos I embedded. The problem however is when I click outside this modal to close the modal the videos continue playing (whichever video is being played). I would like the video to stop playing when a user clicks outside the modal.

This is what i have tried

View

                    A sample of some our workshops and tutorials

Right now I am getting a modal with only one of the videos I embedded and it is not stopping when I close the modal.

Update
Based on the answer given this is what I have tried:

I can no longer close the modal when I click the space outside the modal. This is the error message I am getting in my browser console:

Uncaught ReferenceError: stopVideo is not defined
    at HTMLDivElement.<anonymous> ((index):564)
    at HTMLDivElement.dispatch (jquery-3.2.1.min.js:3)
    at HTMLDivElement.q.handle (jquery-3.2.1.min.js:3)
    at Object.trigger (jquery-3.2.1.min.js:4)
    at HTMLDivElement.<anonymous> (jquery-3.2.1.min.js:4)
    at Function.each (jquery-3.2.1.min.js:2)
    at r.fn.init.each (jquery-3.2.1.min.js:2)
    at r.fn.init.trigger (jquery-3.2.1.min.js:4)
    at r.t.hide (bootstrap.min.js:6)
    at HTMLDivElement.<anonymous> (bootstrap.min.js:6)

Body:
The bootstrap modals - which i assume you are using - have 2 events in place that are getting fired on closing. #1 hide.bs.modal #2 hidden.bs.modal. Have a look at the full list of modal events

So to run your stop function when closing your modal you would want to create a new eventhandler like so :

$('#workshops').on('hide.bs.modal', function() {
  // Stop the videos as soon as the modal's hide function gets called
  stopVideo("resp-iframe"); // your id seems to be a static value you could ofcourse also use the value from your #CloseModalButton
});


问:
Does pyrebase allow sms verification
pyrebase has sign_in_with_email_and_password method for email login. Is there any method for sms verification using pyrebase?

答:
From a quick scan of the Pyrebase source code it seems to only implement email+password authentication.

A feature request was filed to add phone verification, but it was closed as not feasible.

Title: Does pyrebase allow sms verification


问:
Where should I implement my check for collision method?
I am making a pokemon ripoff in pygame, and I have made a method to test whether the player is in the tall grass. However, I do not know where I should call the method. I have tried in the player move method, in the game loop method, and the update method. When I do it like this, it checks after you have moved out of the grass, which means the first time you move into grass it won't work, and when you first move out of grass it works (when it shouldn't).

in_grass(self) method:

```<code>def in_grass(self):
        for g in self.game.grass:
            if pygame.sprite.collide_rect(self, g):
                print(random.randint(1, 10000))
                if random.randint(1, 180) <= 25:
                    self.battle()
</code>```

player move(self) method:

```<code>def move(self, x_change, y_change):
        if x_change > 0:
            self.dir = 'RIGHT'
        if x_change < 0:
            self.dir = 'LEFT'
        if y_change > 0:
            self.dir = 'DOWN'
        if y_change < 0:
            self.dir = 'UP'

        if not self.collide(x_change, y_change):
            self.x += x_change
            self.y += y_change

            image_list = None
            if self.dir == 'UP':
                image_list = self.image_up
            elif self.dir == 'LEFT':
                image_list = self.image_left
            elif self.dir == 'RIGHT':
                image_list = self.image_right
            elif self.dir == 'DOWN':
                image_list = self.image_down

            if image_list:
                if self.walkcount >= len(image_list):
                    self.walkcount = 0
                self.image = image_list[self.walkcount]
                self.walkcount += 1
                self.image.set_colorkey(BLACK)
</code>```

Main loop:

```<code> def events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    self.player.move(0, -1)
                if event.key == pygame.K_a:
                    self.player.move(-1, 0)
                if event.key == pygame.K_s:
                    self.player.move(0, 1)
                if event.key == pygame.K_d:
                    self.player.move(1, 0)

            if event.type == pygame.KEYUP:
                self.player.image = self.player.default_images[self.player.dir]
                self.player.image.set_colorkey(BLACK)
</code>```

EDIT: I finally got it working! I can't give myself the bounty, so I guess it will just sit there.

答:
So here is some food for thought.

Little disclaimer,
I am in no way a game dev nor am i a very experienced developer.

In a larger game you might want to keep a good grasp on what is happening where. Now say we have a game full of entities (think of entities as things you see on screen that have some sort of impact on the game). We would wanna update all these entities every frame of the gameloop.

Entities might be rendered, moved, collission checked, affected by player input, animated or whatever functionality your game needs.
The order in which we do this is important for our game, suppose we have a list of entities

entities = []
```

<p>We could then do something like this where we loop trough each enemy in our gameloop en execute their behaviour function. we pass in all the entities into the check_collision function to make this code a little more understandable.</p>

<p>Version 1</p>

<pre class="lang-py prettyprint-override"><code>entities = []
def game_loop:
    while(true):
        for entity in entities:
            entity.gather_input()
            entity.move()
            entity.check_collision(entities)
            entity.animate()
            entity.render()
</code>```

Now take a look at this:

Version 2

entities = []
def game_loop:
    while(true):
        for entity in entities:
            entity.gather_input()
        for entity in entities:
            entity.move()
        for entity in entities:
            entity.check_collision(entities)
        for entity in entities:
            entity.animate()
        for entity in entities:
            entity.render()
```

The order in which we execute the entities their behaviour has changed. We now have grouped behaviour, we could say we have defined the update fases of our gameloop. We now know all the movement of entities is updated before we check all of their collisions.

Whereas in Version 1 we do all the logic first for 1 entity and then do the next. We might lose relevant data in a single frame using Version 1 because 1 entity might move and check collision wheres it really should've waited till all entities have moved.

Hope this might spark some more research into the rabbithole that is game design/architecture.

Body:
I am making a pokemon ripoff in pygame, and I have made a method to test whether the player is in the tall grass. However, I do not know where I should call the method. I have tried in the player move method, in the game loop method, and the update method. When I do it like this, it checks after you have moved out of the grass, which means the first time you move into grass it won't work, and when you first move out of grass it works (when it shouldn't).

in_grass(self) method:

def in_grass(self):
        for g in self.game.grass:
            if pygame.sprite.collide_rect(self, g):
                print(random.randint(1, 10000))
                if random.randint(1, 180) <= 25:
                    self.battle()

player move(self) method:

def move(self, x_change, y_change):
        if x_change > 0:
            self.dir = 'RIGHT'
        if x_change < 0:
            self.dir = 'LEFT'
        if y_change > 0:
            self.dir = 'DOWN'
        if y_change < 0:
            self.dir = 'UP'

        if not self.collide(x_change, y_change):
            self.x += x_change
            self.y += y_change

            image_list = None
            if self.dir == 'UP':
                image_list = self.image_up
            elif self.dir == 'LEFT':
                image_list = self.image_left
            elif self.dir == 'RIGHT':
                image_list = self.image_right
            elif self.dir == 'DOWN':
                image_list = self.image_down

            if image_list:
                if self.walkcount >= len(image_list):
                    self.walkcount = 0
                self.image = image_list[self.walkcount]
                self.walkcount += 1
                self.image.set_colorkey(BLACK)

Main loop:

 def events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    self.player.move(0, -1)
                if event.key == pygame.K_a:
                    self.player.move(-1, 0)
                if event.key == pygame.K_s:
                    self.player.move(0, 1)
                if event.key == pygame.K_d:
                    self.player.move(1, 0)

            if event.type == pygame.KEYUP:
                self.player.image = self.player.default_images[self.player.dir]
                self.player.image.set_colorkey(BLACK)

EDIT: I finally got it working! I can't give myself the bounty, so I guess it will just sit there.

Body:
So here is some food for thought.

Little disclaimer,
I am in no way a game dev nor am i a very experienced developer.

In a larger game you might want to keep a good grasp on what is happening where. Now say we have a game full of entities (think of entities as things you see on screen that have some sort of impact on the game). We would wanna update all these entities every frame of the gameloop.

Entities might be rendered, moved, collission checked, affected by player input, animated or whatever functionality your game needs.
The order in which we do this is important for our game, suppose we have a list of entities

entities = []

We could then do something like this where we loop trough each enemy in our gameloop en execute their behaviour function. we pass in all the entities into the check_collision function to make this code a little more understandable.

Version 1

entities = []
def game_loop:
    while(true):
        for entity in entities:
            entity.gather_input()
            entity.move()
            entity.check_collision(entities)
            entity.animate()
            entity.render()

Now take a look at this:

Version 2

entities = []
def game_loop:
    while(true):
        for entity in entities:
            entity.gather_input()
        for entity in entities:
            entity.move()
        for entity in entities:
            entity.check_collision(entities)
        for entity in entities:
            entity.animate()
        for entity in entities:
            entity.render()

The order in which we execute the entities their behaviour has changed. We now have grouped behaviour, we could say we have defined the update fases of our gameloop. We now know all the movement of entities is updated before we check all of their collisions.

Whereas in Version 1 we do all the logic first for 1 entity and then do the next. We might lose relevant data in a single frame using Version 1 because 1 entity might move and check collision wheres it really should've waited till all entities have moved.

Hope this might spark some more research into the rabbithole that is game design/architecture.


问:
ForeignCollection throws SQLException on iterating using streams
I have three entity classes: PlayerData, IpData, and TwinData.
Both TwinData and IpData refer to PlayerData with a foreign key.

Here is the code:

```<code>@DatabaseTable
public class PlayerData {
    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField
    private UUID uuid;

    @ForeignCollectionField
    private ForeignCollection<IpData> ips;

    @ForeignCollectionField
    private ForeignCollection<TwinData> twins;

    // Getters and setters...
}

@DatabaseTable
public class IpData {
    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField(foreign = true)
    private PlayerData playerData;

    @DatabaseField
    private Date firstUsage;

    @DatabaseField
    private String address;

    // Getters and setters...
}

@DatabaseTable
public class TwinData {
    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField(foreign = true)
    private PlayerData mainPlayer;

    @DatabaseField
    private boolean adminNoticed;

    @DatabaseField
    private UUID uuid;

    // Getters and setters...
}
</code>```

When I try to iterate over PlayerData.ips with streams, I get SQLException [SQLITE_ERROR] SQL error or missing database (no such column: playerData_id). Tables are auto-generated with TableUtils.createIfNotExists().

This is the code that throws that exception:

```<code>// playerData is retrieved from Dao<PlayerData, Integer>
playerData.getIps().stream().noneMatch(ip -> ip.getAddress().equals(playerIp))
</code>```

I just don't really get why it attempts to select playerData_id column.
Should I manually create database tables for TwinData and IpData with playerData_id column? Haven't tried this yet, but I don't think it would help.

答:
When I try to iterate over PlayerData.ips with streams, I get SQLException[SQLITE_ERROR] SQL error or missing database (no such column: playerData_id). Tables are auto-generated with TableUtils.createIfNotExists().

You will get that error if playerData_id is not a field in the table.  I'm surprised that TableUtils.createIfNotExists() did not create a field playerData_id in the IpData table.  I suspect that the tables existed already and you are not using ORMLite generated schema.

By default when ORMLite sees a foreign = true field, it will store the id of that type in the entity in question.  See the foreign fields documentation.  If your schema is defining the relationship between the entities differently, for example with another table to define the relationship, then you will need to setup that entity by yourself and query it using the DAO for that entity.

You maybe should look at the foreign object example for more information.

Hope this helps.

Body:
I have three entity classes: PlayerData, IpData, and TwinData.
Both TwinData and IpData refer to PlayerData with a foreign key.

Here is the code:

@DatabaseTable
public class PlayerData {
    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField
    private UUID uuid;

    @ForeignCollectionField
    private ForeignCollection<IpData> ips;

    @ForeignCollectionField
    private ForeignCollection<TwinData> twins;

    // Getters and setters...
}

@DatabaseTable
public class IpData {
    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField(foreign = true)
    private PlayerData playerData;

    @DatabaseField
    private Date firstUsage;

    @DatabaseField
    private String address;

    // Getters and setters...
}

@DatabaseTable
public class TwinData {
    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField(foreign = true)
    private PlayerData mainPlayer;

    @DatabaseField
    private boolean adminNoticed;

    @DatabaseField
    private UUID uuid;

    // Getters and setters...
}

When I try to iterate over PlayerData.ips with streams, I get SQLException [SQLITE_ERROR] SQL error or missing database (no such column: playerData_id). Tables are auto-generated with TableUtils.createIfNotExists().

This is the code that throws that exception:

// playerData is retrieved from Dao<PlayerData, Integer>
playerData.getIps().stream().noneMatch(ip -> ip.getAddress().equals(playerIp))

I just don't really get why it attempts to select playerData_id column.
Should I manually create database tables for TwinData and IpData with playerData_id column? Haven't tried this yet, but I don't think it would help.


问:
Why the dataframe is altered when only df.to_numpy() is involved in the computation?
```<code>import pandas as pd
import numpy as np

url = "https://raw.githubusercontent.com/PawinData/UC/SFBA/DistanceMatrix_shortestnetworks.csv"
Distance_df = pd.read_csv(url, index_col=0)

D = Distance_df.to_numpy()
</code>```

I have a dataframe Distance_df and I convert it to a numpy array D for computation. What happens subsequently only concerns D and doesn't involve Distance_df at all. However, both D and Distance_df are altered (to the same thing) in the end.

Although I can't figure out why D would change either, it's the behavior of Distance_df, the dataframe, that puzzles me the most. How can it be altered when it doesn't even show up in the code? Somehow I sense that this is not about the code but how values and objects are handled behind the scene. Can anybody explain a little bit?

答:
try to get a copy of dataframe not to be altered</p>

```<code>import pandas as pd
import numpy as np

url="https://raw.githubusercontent.com/PawinData/UC/SFBA/DistanceMatrix_shortestnetworks.csv"

Distance_df = pd.read_csv(url, index_col=0)

df=Distance_df.copy()

D = df.to_numpy()
</code>```

Body:
import pandas as pd
import numpy as np

url = "https://raw.githubusercontent.com/PawinData/UC/SFBA/DistanceMatrix_shortestnetworks.csv"
Distance_df = pd.read_csv(url, index_col=0)

D = Distance_df.to_numpy()

I have a dataframe Distance_df and I convert it to a numpy array D for computation. What happens subsequently only concerns D and doesn't involve Distance_df at all. However, both D and Distance_df are altered (to the same thing) in the end.

Although I can't figure out why D would change either, it's the behavior of Distance_df, the dataframe, that puzzles me the most. How can it be altered when it doesn't even show up in the code? Somehow I sense that this is not about the code but how values and objects are handled behind the scene. Can anybody explain a little bit?

Body:
try to get a copy of dataframe not to be altered

import pandas as pd
import numpy as np

url="https://raw.githubusercontent.com/PawinData/UC/SFBA/DistanceMatrix_shortestnetworks.csv"

Distance_df = pd.read_csv(url, index_col=0)

df=Distance_df.copy()

D = df.to_numpy()


问:
Error while publishing website ASP net core website
I've developed a ASP .net core (3.1) application which is successfully running locally, Now I'm trying to publish the web app through Visual Studio 2019, but getting error as:

```<code>An error occurred while processing your request.

Development Mode
Swapping to the Development environment displays detailed information about the error that occurred.

The Development environment shouldn't be enabled for deployed applications. It can result in displaying sensitive information from exceptions to end users. For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development and restarting the app.
</code>```

I've already tried adding value to "ASPNETCORE_ENVIRONMENT": "Production"

I'm using connection string as below:

Data Source=MyDataSource;Initial Catalog=MyDatabase;Integrated Security=True

答:
What you're seeing is the default ASP.NET Core error page, including the Development Mode message.

You will need to debug to find out what the problem is. One thing you can do is to access the exception that was thrown and the original request path in an error handler controller or page by using IExceptionHandlerPathFeature:

```<code>var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
    ExceptionMessage = "File error thrown";
}
if (exceptionHandlerPathFeature?.Path == "/index")
{
    ExceptionMessage += " from home page";
}
</code>```

Here's more info on how to Handle errors in ASP.NET Core.

Some pointers based on the information you provided:

Is your data source MyDataSource available through the internet (with the name you specified)?

Does your data source really provide Integrated Security with an ASP.NET application in Azure?

Enable logging (like Application Insights for ASP.NET Core applications) to find the issue

Body:
I've developed a ASP .net core (3.1) application which is successfully running locally, Now I'm trying to publish the web app through Visual Studio 2019, but getting error as:

An error occurred while processing your request.

Development Mode
Swapping to the Development environment displays detailed information about the error that occurred.

The Development environment shouldn't be enabled for deployed applications. It can result in displaying sensitive information from exceptions to end users. For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development and restarting the app.

I've already tried adding value to "ASPNETCORE_ENVIRONMENT": "Production"

I'm using connection string as below:

Data Source=MyDataSource;Initial Catalog=MyDatabase;Integrated Security=True

Body:
What you're seeing is the default ASP.NET Core error page, including the Development Mode message.

You will need to debug to find out what the problem is. One thing you can do is to access the exception that was thrown and the original request path in an error handler controller or page by using IExceptionHandlerPathFeature:

var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
    ExceptionMessage = "File error thrown";
}
if (exceptionHandlerPathFeature?.Path == "/index")
{
    ExceptionMessage += " from home page";
}

Here's more info on how to Handle errors in ASP.NET Core.

Some pointers based on the information you provided:

Is your data source MyDataSource available through the internet (with the name you specified)?

Does your data source really provide Integrated Security with an ASP.NET application in Azure?

Enable logging (like Application Insights for ASP.NET Core applications) to find the issue


答:
Your code snippet has two issues.

First: adminId

React hook will be called multiple time within its lifecycle, and it will be given different value based on uuid()

To solve it, you can use useState or useRef or move it to outside QRGenerator function.

Second issue: updating state

setQrcode({ copied: true })} mean you will replace the value qrcode value with { copied: true} with value undefined

The below snippet will be the solution to the above issues

```<code>export default function QRGenerator() {
  const [adminId] = useState(uuid()); // or useRef(uuid());

  const [qrcode, setQrcode] = useState({
    value: "",
    copied: false,
  });

  return (
    <div>
      <CopyToClipboard
        text={adminId}
        onCopy={() => setQrcode({...qrcode, copied: true })} // this change only `copied` value
      >
        <Button>
          <FileCopyIcon />
        </Button>
      </CopyToClipboard>

      <Typography align="center" variant="caption" paragraph="true">
        Admin ID : {adminId}
        {qrcode.copied ? <span style={{ color: "red" }}>Copied.</span> : null}
      </Typography>
      <QRCode value={adminId} />
    </div>
  );
}
</code>```

Hope this helps!

Title: How to prevent UUID from changing state when using copy-to-clipboard function?

Body:
Your code snippet has two issues.

First: adminId

React hook will be called multiple time within its lifecycle, and it will be given different value based on uuid()

To solve it, you can use useState or useRef or move it to outside QRGenerator function.

Second issue: updating state

setQrcode({ copied: true })} mean you will replace the value qrcode value with { copied: true} with value undefined

The below snippet will be the solution to the above issues

export default function QRGenerator() {
  const [adminId] = useState(uuid()); // or useRef(uuid());

  const [qrcode, setQrcode] = useState({
    value: "",
    copied: false,
  });

  return (
    <div>
      <CopyToClipboard
        text={adminId}
        onCopy={() => setQrcode({...qrcode, copied: true })} // this change only `copied` value
      >
        <Button>
          <FileCopyIcon />
        </Button>
      </CopyToClipboard>

      <Typography align="center" variant="caption" paragraph="true">
        Admin ID : {adminId}
        {qrcode.copied ? <span style={{ color: "red" }}>Copied.</span> : null}
      </Typography>
      <QRCode value={adminId} />
    </div>
  );
}

Hope this helps!


问:
Kotlin - Check if one map contains all entries from another
I'm trying to create a function in kotlin that takes two maps and returns true if one is contained in another, that is, if all the entries in map A are in map B (but B can have other entries)

The code I have is

```<code>private fun matchesMap(map1: Map<String, Any>, reference: Map<String, Any>): Boolean {
    return reference.all { k, v ->  map1.get(k).equals(v) }
}
</code>```

But this gives a Type mismatch: inferred type is (Map.Entry<String, Any>, ???) -> Boolean but (Map.Entry<String, Any>) -> Boolean was expected and I'm not sure what's wrong. I've tried to replace it with map1[k] == v but I still get the same error. How can I fix the compilation error?

答:
According to specification all method - argument of lambda is Entry. You cannot get key and value directly, so change it to Entry.

Correct code:

```<code>reference.all { entry ->  map1.get(entry.key) == entry.value }
</code>```

You should use Map method equals. It does the same.

Body:
I'm trying to create a function in kotlin that takes two maps and returns true if one is contained in another, that is, if all the entries in map A are in map B (but B can have other entries)

The code I have is

private fun matchesMap(map1: Map<String, Any>, reference: Map<String, Any>): Boolean {
    return reference.all { k, v ->  map1.get(k).equals(v) }
}

But this gives a Type mismatch: inferred type is (Map.Entry<String, Any>, ???) -> Boolean but (Map.Entry<String, Any>) -> Boolean was expected and I'm not sure what's wrong. I've tried to replace it with map1[k] == v but I still get the same error. How can I fix the compilation error?

Body:
According to specification all method - argument of lambda is Entry. You cannot get key and value directly, so change it to Entry.

Correct code:

reference.all { entry ->  map1.get(entry.key) == entry.value }

You should use Map method equals. It does the same.


问:
How to convert String in to Object Array in javascript
I am getting response in a string array like this.

```<code> {"columnModelObj":[{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_1","width":150,"text":"FILM"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_2","width":150,"text":"GENRE"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_3","width":150,"text":"LEAD STUDIO"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_4","showOriginalData":true,"width":150,"text":"AUDIENCE  SCORE %"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_5","showOriginalData":true,"width":150,"text":"PROFITABILITY"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_6","showOriginalData":true,"width":150,"text":"ROTTEN TOMATOES %"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_7","showOriginalData":true,"width":150,"text":"WORLDWIDE GROSS"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_8","showOriginalData":true,"width":150,"text":"YEAR"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_9","width":150,"text":"DATE"}],"recordModelObj":[{"name":"Film","type":"string"},{"name":"Genre","type":"string"},{"name":"Lead Studio","type":"string"},{"name":"Audience  score %","allowNull":true,"type":"number"},{"name":"Profitability","allowNull":true,"type":"number"},{"name":"Rotten Tomatoes %","allowNull":true,"type":"number"},{"name":"Worldwide Gross","allowNull":true,"type":"number"},{"name":"Year","allowNull":true,"type":"number"},{"name":"Date","type":"string"}]}
</code>```

I have to make in to array object. Any possible idea how to make it.

Here is what I am doing but no luck.

```<code>var foo = col.split("\n").reduce(function(obj, str, index) {
  let strParts = str.split(":");
  if (strParts[0] && strParts[1]) {
    obj[strParts[0].replace(/\s+/g, '')] = strParts[1].trim();
  }
  return obj;
}, {});
</code>```

答:
well check this out

One simple code to fix your problems

```<code>data = ' {"columnModelObj":[{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_1","width":150,"text":"FILM"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_2","width":150,"text":"GENRE"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_3","width":150,"text":"LEAD STUDIO"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_4","showOriginalData":true,"width":150,"text":"AUDIENCE  SCORE %"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_5","showOriginalData":true,"width":150,"text":"PROFITABILITY"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_6","showOriginalData":true,"width":150,"text":"ROTTEN TOMATOES %"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_7","showOriginalData":true,"width":150,"text":"WORLDWIDE GROSS"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_8","showOriginalData":true,"width":150,"text":"YEAR"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_9","width":150,"text":"DATE"}],"recordModelObj":[{"name":"Film","type":"string"},{"name":"Genre","type":"string"},{"name":"Lead Studio","type":"string"},{"name":"Audience  score %","allowNull":true,"type":"number"},{"name":"Profitability","allowNull":true,"type":"number"},{"name":"Rotten Tomatoes %","allowNull":true,"type":"number"},{"name":"Worldwide Gross","allowNull":true,"type":"number"},{"name":"Year","allowNull":true,"type":"number"},{"name":"Date","type":"string"}]}'

data = data.split("formatGridNumberColumn").join('"formatGridNumberColumn"')

data_object = JSON.parse(data)
</code>```

and Data_object is the object you are looking for

you see the villain here is the formatGridNumberColumn which in not qouted " ". So the parsed result can never be a string.

Alone the formatGridNumberColumn is foreign to javascript.

for that reason I split the string by formatGridNumberColumn and joind it again by "formatGridNumberColumn". As it beacame a string now JSON can parse it.

Body:
I am getting response in a string array like this.

 {"columnModelObj":[{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_1","width":150,"text":"FILM"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_2","width":150,"text":"GENRE"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_3","width":150,"text":"LEAD STUDIO"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_4","showOriginalData":true,"width":150,"text":"AUDIENCE  SCORE %"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_5","showOriginalData":true,"width":150,"text":"PROFITABILITY"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_6","showOriginalData":true,"width":150,"text":"ROTTEN TOMATOES %"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_7","showOriginalData":true,"width":150,"text":"WORLDWIDE GROSS"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_8","showOriginalData":true,"width":150,"text":"YEAR"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_9","width":150,"text":"DATE"}],"recordModelObj":[{"name":"Film","type":"string"},{"name":"Genre","type":"string"},{"name":"Lead Studio","type":"string"},{"name":"Audience  score %","allowNull":true,"type":"number"},{"name":"Profitability","allowNull":true,"type":"number"},{"name":"Rotten Tomatoes %","allowNull":true,"type":"number"},{"name":"Worldwide Gross","allowNull":true,"type":"number"},{"name":"Year","allowNull":true,"type":"number"},{"name":"Date","type":"string"}]}

I have to make in to array object. Any possible idea how to make it.

Here is what I am doing but no luck.

var foo = col.split("\n").reduce(function(obj, str, index) {
  let strParts = str.split(":");
  if (strParts[0] && strParts[1]) {
    obj[strParts[0].replace(/\s+/g, '')] = strParts[1].trim();
  }
  return obj;
}, {});

Body:
well check this out

One simple code to fix your problems

data = ' {"columnModelObj":[{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_1","width":150,"text":"FILM"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_2","width":150,"text":"GENRE"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_3","width":150,"text":"LEAD STUDIO"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_4","showOriginalData":true,"width":150,"text":"AUDIENCE  SCORE %"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_5","showOriginalData":true,"width":150,"text":"PROFITABILITY"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_6","showOriginalData":true,"width":150,"text":"ROTTEN TOMATOES %"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_7","showOriginalData":true,"width":150,"text":"WORLDWIDE GROSS"},{"filter":{"type":"number"},"renderer":formatGridNumberColumn,"dataIndex":"_8","showOriginalData":true,"width":150,"text":"YEAR"},{"filter":{"type":"list"},"multiValueTextData":true,"dataIndex":"_9","width":150,"text":"DATE"}],"recordModelObj":[{"name":"Film","type":"string"},{"name":"Genre","type":"string"},{"name":"Lead Studio","type":"string"},{"name":"Audience  score %","allowNull":true,"type":"number"},{"name":"Profitability","allowNull":true,"type":"number"},{"name":"Rotten Tomatoes %","allowNull":true,"type":"number"},{"name":"Worldwide Gross","allowNull":true,"type":"number"},{"name":"Year","allowNull":true,"type":"number"},{"name":"Date","type":"string"}]}'

data = data.split("formatGridNumberColumn").join('"formatGridNumberColumn"')

data_object = JSON.parse(data)

and Data_object is the object you are looking for

you see the villain here is the formatGridNumberColumn which in not qouted " ". So the parsed result can never be a string.

Alone the formatGridNumberColumn is foreign to javascript.

for that reason I split the string by formatGridNumberColumn and joind it again by "formatGridNumberColumn". As it beacame a string now JSON can parse it.


问:
How To Access Course Material In Google Classroom API?
Using the Google Classroom API is there a way to get or create Material for Courses?

I'm able to get a listing of Assignments and Questions but not Material using courses.courseWork.

答:
Unfortunately so far it's not possible

However, a related
feature request has been filed on Google's Public Issue Tracker and quite a few users have indicated that they are interested in the feature.

Show that you are also interested by giving a "star" to this feature request, this will show the importance of the feature and you will be updated about its implementation.


问:
How to upload excel file to server with kendo ui
i am trying to upload an excel file to my server with kendo ui but nothing happens.The problem is in js  on var upload as the #kupload is null and i dont know why

```<code><div class="form-group">
<label for="kUpload">Select File for Upload </label>
   <input type="file" id="kUpload"/>
 </div>
</code>```

Upload

```<code>$(document).ready(function ()
{ $("#btn-kUpload").on("click", function (e) {
            e.preventDefault();

            var formData = new FormData();
            var upload = $("#kUpload").getKendoUpload();

            var files = upload.getFiles();
            formData.append('files', files[0].rawFile);

            // Send the request
            $.ajax({
                url: 'test.aspx/ImportExcel',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (response) {
                    console.log(response);
                }
            });
        });
</code>```

答:
You don't need to use ajax if you are using kendo components, kendo upload has built-in ajax request for sending files to the server.

NOTE: Generally every kendo component that communicates with server-side has own ajax function so you don't need to use $.ajax

You only need to define saveUrl:

```<code>    <input name="files" id="files" type="file" aria-label="files"/>

    $('#files').kendoUpload({
        async: {
            saveUrl: 'test.aspx/ImportExcel'
        },
        dropZone: '.drop-zone',
        multiple: true,
        clear: function () {

        },
        complete: function(){
         //This is called when all files are uploaded
        },
        success: function() {
         //This is called for every uploaded file
        },
        error: function () {

        },
        localization: {
            select: 'Upload file...'
        }
    });
</code>```

Offical example: Upload component

Check documentation: Kendo UI Upload

Body:
i am trying to upload an excel file to my server with kendo ui but nothing happens.The problem is in js  on var upload as the #kupload is null and i dont know why

Select File for Upload
   <input type="file" id="kUpload"/>

Upload

$(document).ready(function ()
{ $("#btn-kUpload").on("click", function (e) {
            e.preventDefault();

            var formData = new FormData();
            var upload = $("#kUpload").getKendoUpload();

            var files = upload.getFiles();
            formData.append('files', files[0].rawFile);

            // Send the request
            $.ajax({
                url: 'test.aspx/ImportExcel',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (response) {
                    console.log(response);
                }
            });
        });

Body:
You don't need to use ajax if you are using kendo components, kendo upload has built-in ajax request for sending files to the server.

NOTE: Generally every kendo component that communicates with server-side has own ajax function so you don't need to use $.ajax

You only need to define saveUrl:

    <input name="files" id="files" type="file" aria-label="files"/>

    $('#files').kendoUpload({
        async: {
            saveUrl: 'test.aspx/ImportExcel'
        },
        dropZone: '.drop-zone',
        multiple: true,
        clear: function () {

        },
        complete: function(){
         //This is called when all files are uploaded
        },
        success: function() {
         //This is called for every uploaded file
        },
        error: function () {

        },
        localization: {
            select: 'Upload file...'
        }
    });

Offical example: Upload component

Check documentation: Kendo UI Upload


问:
Custom metrics for image segmentation in Keras
I am trying to print and log the custom metrics (dice score) for all classes for validation set during training. I want the Keras to calculate custom  metrics on validation set after each epoch. My current program is working but I have to use some tricks that ultimately cause memory problems during training.

The issue is to print and log the dice scores of all classes, the calculations are done on tensors which I am unable to print. I cant use eager mode due to some compatibility issues with TensorFlow 2.0 and forced to initialize another session.

My custom metrics class is given below:

```<code>class Metrics(tf.keras.callbacks.Callback):

    def on_train_begin(self, logs={}):
        self.val_lv = []
        self.val_rk = []
        self.val_lk = []
        self.val_sp = []

    def on_epoch_end(self, batch, logs={}):

        layer_name = 'loss6'
        self.intermediate_layer_model = tf.keras.models.Model(inputs=self.model.input,
                                                              outputs=self.model.get_layer(layer_name).output)
        for batch_index in range(0, len(self.validation_data)):
            temp_targ = self.validation_data[batch_index][1][0]

            temp_targ=temp_targ.astype('float32')

            temp_predict = (np.asarray( self.intermediate_layer_model.predict(
                self.validation_data[batch_index][0]))).round()

            val_lvs = tf.reduce_mean((dice_coef(temp_targ[:,1, :, :], temp_predict[:,1, :, :])))
            val_rks = tf.reduce_mean(dice_coef(temp_targ[:, 2, :, :], temp_predict[:, 2, :, :]))
            val_lks = tf.reduce_mean(dice_coef(temp_targ[:, 3, :, :], temp_predict[:, 3, :, :]))
            val_sps = tf.reduce_mean(dice_coef(temp_targ[:, 4, :, :], temp_predict[:, 4, :, :]))

            self.val_lv.append(val_lvs)
            self.val_rk.append(val_rks)
            self.val_lk.append(val_lks)
            self.val_sp.append(val_sps)
        sess = tf.Session()
        print('liver-score:', sess.run(tf.reduce_mean(self.val_lv)))
        print('rk-score:', sess.run(tf.reduce_mean(self.val_rk)))
        print('lk-score:', sess.run(tf.reduce_mean(self.val_lk)))
        print('sp-score:', sess.run(tf.reduce_mean(self.val_sp)))

        logs['liver-score'] = sess.run(tf.reduce_mean(self.val_lv))
        logs['rk-score'] = sess.run(tf.reduce_mean(self.val_rk))
        logs['lk-score'] = sess.run(tf.reduce_mean(self.val_lk))
        logs['sp-score'] = sess.run(tf.reduce_mean(self.val_sp))
        sess.close()

        return
</code>```

Note that the variables lv, rk, lk and sp are abbreviations for my class names.

Any alternative way to print and log the metrics except for using session?

答:
As far as i understand, temp_predict and temp_predict  are numpy arrays. So the only way you can end up with tensors is because you are using tf.reduce_mean. You can replace it with np.mean. This will only  work if dice_coef has no tensorflow ops. If it does then you will have to replace them with numpy functions. Once you do that, then you wouldn't have to open new sessions.

And also instead of creating a new model at the end of every epoch (intermediate_layer_model), you can construct a keras function using tf.keras.backend.function more about it here.

Body:
I am trying to print and log the custom metrics (dice score) for all classes for validation set during training. I want the Keras to calculate custom  metrics on validation set after each epoch. My current program is working but I have to use some tricks that ultimately cause memory problems during training.

The issue is to print and log the dice scores of all classes, the calculations are done on tensors which I am unable to print. I cant use eager mode due to some compatibility issues with TensorFlow 2.0 and forced to initialize another session.

My custom metrics class is given below:

class Metrics(tf.keras.callbacks.Callback):

    def on_train_begin(self, logs={}):
        self.val_lv = []
        self.val_rk = []
        self.val_lk = []
        self.val_sp = []

    def on_epoch_end(self, batch, logs={}):

        layer_name = 'loss6'
        self.intermediate_layer_model = tf.keras.models.Model(inputs=self.model.input,
                                                              outputs=self.model.get_layer(layer_name).output)
        for batch_index in range(0, len(self.validation_data)):
            temp_targ = self.validation_data[batch_index][1][0]

            temp_targ=temp_targ.astype('float32')

            temp_predict = (np.asarray( self.intermediate_layer_model.predict(
                self.validation_data[batch_index][0]))).round()

            val_lvs = tf.reduce_mean((dice_coef(temp_targ[:,1, :, :], temp_predict[:,1, :, :])))
            val_rks = tf.reduce_mean(dice_coef(temp_targ[:, 2, :, :], temp_predict[:, 2, :, :]))
            val_lks = tf.reduce_mean(dice_coef(temp_targ[:, 3, :, :], temp_predict[:, 3, :, :]))
            val_sps = tf.reduce_mean(dice_coef(temp_targ[:, 4, :, :], temp_predict[:, 4, :, :]))

            self.val_lv.append(val_lvs)
            self.val_rk.append(val_rks)
            self.val_lk.append(val_lks)
            self.val_sp.append(val_sps)
        sess = tf.Session()
        print('liver-score:', sess.run(tf.reduce_mean(self.val_lv)))
        print('rk-score:', sess.run(tf.reduce_mean(self.val_rk)))
        print('lk-score:', sess.run(tf.reduce_mean(self.val_lk)))
        print('sp-score:', sess.run(tf.reduce_mean(self.val_sp)))

        logs['liver-score'] = sess.run(tf.reduce_mean(self.val_lv))
        logs['rk-score'] = sess.run(tf.reduce_mean(self.val_rk))
        logs['lk-score'] = sess.run(tf.reduce_mean(self.val_lk))
        logs['sp-score'] = sess.run(tf.reduce_mean(self.val_sp))
        sess.close()

        return

Note that the variables lv, rk, lk and sp are abbreviations for my class names.

Any alternative way to print and log the metrics except for using session?


问:
node/express anchor links not directing to the other HTML static page
I'm building my first node.js/express.js project. This is what my directory structure looks like.

In my index.html and favorites.html files, I've included anchor tags to navigate between the two pages:

```
</div>
</div>
</p>

<p>When I run the server through node (localhost:3000), the nav links on <code>index.html</code> don't appear to work, nothing happens. However, when I go to localhost:3000/favorites.html, the nav links works and redirect me back to <code>index.html</code> and <code>favorites.html</code> itself. </p>

<p>In the <code>server.js</code> file, I've added express.static middleware to serve all the static files in the <code>public</code> folder following the express documentation and after reading different answers on here.</p>

```const express = require('express');
const app = express();

app.use(express.static('public'));
```

Could anyone point me in the right direction of why the links on index.html may not be working? Thank you!

答:
Please use route as following:

const express = require('express');
const app = express();

app.use(express.static('public'));

app.get('/', function (request, response) {
    response.sendFile(__dirname + './public/index.html');
});

app.get("/favorites", function (request, response) {
    response.sendFile(__dirname + './public/favorites.html');
});
```

<pre class="lang-html prettyprint-override"><code><header class="menu">
  <i class="fas fa-home"></i>
  <i class="fas fa-heart"></i>
</header>
</code>```

Body:
I'm building my first node.js/express.js project. This is what my directory structure looks like.

In my index.html and favorites.html files, I've included anchor tags to navigate between the two pages:

When I run the server through node (localhost:3000), the nav links on index.html don't appear to work, nothing happens. However, when I go to localhost:3000/favorites.html, the nav links works and redirect me back to index.html and favorites.html itself.

In the server.js file, I've added express.static middleware to serve all the static files in the public folder following the express documentation and after reading different answers on here.

const express = require('express');
const app = express();

app.use(express.static('public'));

Could anyone point me in the right direction of why the links on index.html may not be working? Thank you!

Body:
Please use route as following:

const express = require('express');
const app = express();

app.use(express.static('public'));

app.get('/', function (request, response) {
    response.sendFile(__dirname + './public/index.html');
});

app.get("/favorites", function (request, response) {
    response.sendFile(__dirname + './public/favorites.html');
});

<header class="menu">
  <a href="/"><i class="fas fa-home"></i></a>
  <a href="/favorites" class="favorite"><i class="fas fa-heart"></i></a>
</header>