问:
JDeveloper 12c | IntegratedWebLogicServer | Error while building the default domain
I'm trying to run IntegratedWebLogicServer using JDeveloper Version 12.2.1.4.0, and I have the following message:

ERROR:  An error occurred while building the default domain.

And the log shows:

```<code>BuildDefaultDomain1.py      2020-02-10 11:53:05

cmd.exe /c ""C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin\wlst.cmd" "C:\Users\nauana.nonato\AppData\Roaming\JDeveloper\system12.2.1.4.42.190911.2248\o.j2ee.adrs\BuildDefaultDomain1.py""
Cannot run program "cmd.exe" (in directory "C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin"): Malformed argument has embedded quote: "C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin\wlst.cmd" "C:\Users\nauana.nonato\AppData\Roaming\JDeveloper\system12.2.1.4.42.190911.2248\o.j2ee.adrs\BuildDefaultDomain1.py"
java.io.IOException: Cannot run program "cmd.exe" (in directory "C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin"): Malformed argument has embedded quote: "C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin\wlst.cmd" "C:\Users\nauana.nonato\AppData\Roaming\JDeveloper\system12.2.1.4.42.190911.2248\o.j2ee.adrs\BuildDefaultDomain1.py"
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at oracle.jdevimpl.adrs.weblogic.wlst.ScriptRunnerImpl.runScript(ScriptRunnerImpl.java:106)
    at oracle.jdevimpl.adrs.weblogic.builder.DomainScriptRunnerImpl.runScript(DomainScriptRunnerImpl.java:146)
    at oracle.jdevimpl.adrs.weblogic.builder.DefaultDomainBuilder.createDomain(DefaultDomainBuilder.java:606)
    at oracle.jdevimpl.adrs.weblogic.builder.DefaultDomainBuilder.build(DefaultDomainBuilder.java:274)
    at oracle.jdevimpl.adrs.weblogic.builder.DefaultDomainBuilder$1.run(DefaultDomainBuilder.java:225)
    at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:1443)
    at org.netbeans.modules.openide.util.GlobalLookup.execute(GlobalLookup.java:68)
    at org.openide.util.lookup.Lookups.executeWith(Lookups.java:303)
    at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:2058)
Caused by: java.lang.IllegalArgumentException: Malformed argument has embedded quote: "C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin\wlst.cmd" "C:\Users\nauana.nonato\AppData\Roaming\JDeveloper\system12.2.1.4.42.190911.2248\o.j2ee.adrs\BuildDefaultDomain1.py"
    at java.lang.ProcessImpl.needsEscaping(ProcessImpl.java:279)
    at java.lang.ProcessImpl.createCommandLine(ProcessImpl.java:202)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:436)
    at java.lang.ProcessImpl.start(ProcessImpl.java:140)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 9 more
</code>```

What should I do?

答:
I am having the same problem as you. I am installing Oralce SOA Quick Start 12c version 12.1
Version JDK: javac 1.8.0_251
To solve this problem. You set parameters in enviroment:
-Djdk.lang.Process.allowAmbiguousCommands=true
set JAVA_TOOL_OPTIONS=-Djdk.lang.Process.allowAmbiguousCommands=true

good luck: ManhKM

Body:
I'm trying to run IntegratedWebLogicServer using JDeveloper Version 12.2.1.4.0, and I have the following message:

ERROR:  An error occurred while building the default domain.

And the log shows:

BuildDefaultDomain1.py      2020-02-10 11:53:05

cmd.exe /c ""C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin\wlst.cmd" "C:\Users\nauana.nonato\AppData\Roaming\JDeveloper\system12.2.1.4.42.190911.2248\o.j2ee.adrs\BuildDefaultDomain1.py""
Cannot run program "cmd.exe" (in directory "C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin"): Malformed argument has embedded quote: "C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin\wlst.cmd" "C:\Users\nauana.nonato\AppData\Roaming\JDeveloper\system12.2.1.4.42.190911.2248\o.j2ee.adrs\BuildDefaultDomain1.py"
java.io.IOException: Cannot run program "cmd.exe" (in directory "C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin"): Malformed argument has embedded quote: "C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin\wlst.cmd" "C:\Users\nauana.nonato\AppData\Roaming\JDeveloper\system12.2.1.4.42.190911.2248\o.j2ee.adrs\BuildDefaultDomain1.py"
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at oracle.jdevimpl.adrs.weblogic.wlst.ScriptRunnerImpl.runScript(ScriptRunnerImpl.java:106)
    at oracle.jdevimpl.adrs.weblogic.builder.DomainScriptRunnerImpl.runScript(DomainScriptRunnerImpl.java:146)
    at oracle.jdevimpl.adrs.weblogic.builder.DefaultDomainBuilder.createDomain(DefaultDomainBuilder.java:606)
    at oracle.jdevimpl.adrs.weblogic.builder.DefaultDomainBuilder.build(DefaultDomainBuilder.java:274)
    at oracle.jdevimpl.adrs.weblogic.builder.DefaultDomainBuilder$1.run(DefaultDomainBuilder.java:225)
    at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:1443)
    at org.netbeans.modules.openide.util.GlobalLookup.execute(GlobalLookup.java:68)
    at org.openide.util.lookup.Lookups.executeWith(Lookups.java:303)
    at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:2058)
Caused by: java.lang.IllegalArgumentException: Malformed argument has embedded quote: "C:\Oracle\Middleware\Oracle_Home\oracle_common\common\bin\wlst.cmd" "C:\Users\nauana.nonato\AppData\Roaming\JDeveloper\system12.2.1.4.42.190911.2248\o.j2ee.adrs\BuildDefaultDomain1.py"
    at java.lang.ProcessImpl.needsEscaping(ProcessImpl.java:279)
    at java.lang.ProcessImpl.createCommandLine(ProcessImpl.java:202)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:436)
    at java.lang.ProcessImpl.start(ProcessImpl.java:140)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 9 more

What should I do?


来源: stackexchange

问:
How to test a method which is in mapStateToProps in React using Jest - Enzyme
I'm not able to increase coverage for this line handleSave which I'm passing as a prop to my component. However, I'm importing mapStateToProps from my container file in the test case and used .toBeTruthy() for validating the test case.

Here's a gist of my code

```<code>export const mapStateToProps = (state, ownProps) => {
  return {
    handleSave: title => ownProps.history.push(setTitle(title)),
  };
};
</code>```

This is the test case that I wrote

```<code>it('mapStateToProps test case', () => {
  const result = mapStateToProps(state, ownProps);
  expect(result.handleSave).toBeTruthy();
});
</code>```

Could anyone please help? What should I do to get the handleSave covered?

答:
What you can do is mock the ownProps and test out the mock function like:

const mockFn = jest.fn();
const ownProps = {
 history: {
   push: mockFn
 }
}

const result = mapStateToProps(state, ownProps);

// Now call the handle save function
result.handleSave("My title");

// And then as follows:

// This will ensure that your function is calling ownProps history push method.
expect(mockFn).toBeCalled();

// To check the funciton has only been called once
expect(mockFn.mock.calls.length).toBe(1);

// This is to check if the correct argument has been passed. Be sure to pass in what your `setTitle` funciton returns
expect(mockFn.mock.calls[0][0]).toBe("My title");

```

ContentLicense: CC BY-SA 4.0

Body:
I'm not able to increase coverage for this line handleSave which I'm passing as a prop to my component. However, I'm importing mapStateToProps from my container file in the test case and used .toBeTruthy() for validating the test case.

Here's a gist of my code

export const mapStateToProps = (state, ownProps) => {
  return {
    handleSave: title => ownProps.history.push(setTitle(title)),
  };
};

This is the test case that I wrote

it('mapStateToProps test case', () => {
  const result = mapStateToProps(state, ownProps);
  expect(result.handleSave).toBeTruthy();
});

Could anyone please help? What should I do to get the handleSave covered?


问:
Sequentially select parts of a string similar to ngram
Here is the problem I am trying to solve.

For example there is this string

```<code>my_string = 'jan feb mar'
</code>```

And I want to have sequentially generated items like this in a list.
It is always true that the words in a string are splittable with ' '.

```<code>my_function(my_string)
output = ['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb','feb mar','mar']
</code>```

What I tried is below and it is not what I want.

```<code>my_string = "jan feb mar"
words_list = my_string.split(' ')
words = [' '.join(words_list[i:i+n]) for i in range(len(words_list) - n+1)]
words.extend(input_list)
</code>```

Please help me out here. Thanks.

答:
using permutations

```<code>from itertools import permutations as per
res = []
my_string = 'jan feb mar'
l = my_string.split()
for i in range(len(l)):
    res.extend(list(per(l, i+1)))

res = [' '.join(i) for i in res]
print(res)
</code>```

output

```<code>['jan', 'feb', 'mar', 'jan feb', 'jan mar', 'feb jan', 'feb mar', 'mar jan', 'mar feb', 'jan feb mar', 'jan mar feb', 'feb jan mar', 'feb mar jan', 'mar jan feb', 'mar feb jan']
</code>```

Body:
Here is the problem I am trying to solve.

For example there is this string

my_string = 'jan feb mar'

And I want to have sequentially generated items like this in a list.
It is always true that the words in a string are splittable with ' '.

my_function(my_string)
output = ['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb','feb mar','mar']

What I tried is below and it is not what I want.

my_string = "jan feb mar"
words_list = my_string.split(' ')
words = [' '.join(words_list[i:i+n]) for i in range(len(words_list) - n+1)]
words.extend(input_list)

Please help me out here. Thanks.

Body:
using permutations

from itertools import permutations as per
res = []
my_string = 'jan feb mar'
l = my_string.split()
for i in range(len(l)):
    res.extend(list(per(l, i+1)))

res = [' '.join(i) for i in res]
print(res)

output

['jan', 'feb', 'mar', 'jan feb', 'jan mar', 'feb jan', 'feb mar', 'mar jan', 'mar feb', 'jan feb mar', 'jan mar feb', 'feb jan mar', 'feb mar jan', 'mar jan feb', 'mar feb jan']


问:
Scrapy: How to extract data from a page that loads it via ajax?
I am trying to extract data from a search result that is partially build via ajax:

https://www.vitalsana.com/catalogsearch/result/?q=ibuprofen

The wanted data PZN: 16336937 is somehow injected after page onload:

xpath does return an empty result:

```<code>//[@id="maincontent"]/div[3]/div[1]/div[2]/div[4]/ol/li[1]/form/div/div[2]/p[2]/span[2]/span
</code>```

Sanme goes for the data verfügbar. It is loaded after pageload via this API I guess:
https://www.vitalsana.com/catalogsearch/searchTermsLog/save/?q=ibuprofen

I noticed that some info is within inline JS, but it is difficult to get just this JS. I tried last, but this seems to be ignored. It gets all JS including the desired info:

```<code>response.xpath('//script[last()]/text()').extract()
</code>```

I am using scrapy 2.1.0. Is there a way to retrieve this data?

答:
PZN: 16336937 is not present in the search results (Vitamin D3 != Ibuprofen).

To get the PZN number of a product (8 digits), you can extract it from the img element of each product. For example, for the first search result ([1]) :

```<code>response.xpath('substring(substring-before((//img[@class="product-image-photo img-fluid"])[1]/@src,"_"),string-length(substring-before((//img[@class="product-image-photo img-fluid"])[1]/@src,"_"))-7,8)').extract()
</code>```

Output : 07728561

You could also extract the value directly from the script element, but you'll have to figure out how to escape single quotes in scrapy. The XPath :

```<code>substring-after(substring-before(//script[contains(.,"Suche")],'",'),'"id": "')
</code>```

Output : 07728561

Note : using regex instead of substring functions might be cleaner.

What you could try also is to "rebuild" the json from the script element, load the json, then query on it. Something like this should work :

```<code>import json

products = response.xpath('substring(substring-after(//script[contains(.,"Suche")],"] ="),1,string-length(substring-after(//script[contains(.,"Suche")],"] ="))-1)').extract()

result = json.loads(products)
for i in result:
    print i['id']
</code>```

Last option : request directly the data from the API (with a well-formed payload, a valid token and the appropiate method).

Body:
I am trying to extract data from a search result that is partially build via ajax:

https://www.vitalsana.com/catalogsearch/result/?q=ibuprofen

The wanted data PZN: 16336937 is somehow injected after page onload:

xpath does return an empty result:

//[@id="maincontent"]/div[3]/div[1]/div[2]/div[4]/ol/li[1]/form/div/div[2]/p[2]/span[2]/span

Sanme goes for the data verfügbar. It is loaded after pageload via this API I guess:
https://www.vitalsana.com/catalogsearch/searchTermsLog/save/?q=ibuprofen

I noticed that some info is within inline JS, but it is difficult to get just this JS. I tried last, but this seems to be ignored. It gets all JS including the desired info:

response.xpath('//script[last()]/text()').extract()

I am using scrapy 2.1.0. Is there a way to retrieve this data?

Body:
PZN: 16336937 is not present in the search results (Vitamin D3 != Ibuprofen).

To get the PZN number of a product (8 digits), you can extract it from the img element of each product. For example, for the first search result ([1]) :

response.xpath('substring(substring-before((//img[@class="product-image-photo img-fluid"])[1]/@src,"_"),string-length(substring-before((//img[@class="product-image-photo img-fluid"])[1]/@src,"_"))-7,8)').extract()

Output : 07728561

You could also extract the value directly from the script element, but you'll have to figure out how to escape single quotes in scrapy. The XPath :

substring-after(substring-before(//script[contains(.,"Suche")],'",'),'"id": "')

Output : 07728561

Note : using regex instead of substring functions might be cleaner.

What you could try also is to "rebuild" the json from the script element, load the json, then query on it. Something like this should work :

import json

products = response.xpath('substring(substring-after(//script[contains(.,"Suche")],"] ="),1,string-length(substring-after(//script[contains(.,"Suche")],"] ="))-1)').extract()

result = json.loads(products)
for i in result:
    print i['id']

Last option : request directly the data from the API (with a well-formed payload, a valid token and the appropiate method).


问:
Artificially increasing the size of a dataset through duplication?
I'm working on a machine learning project where I'm using a neural network to solve a binary classification problem, however, my dataset(in .csv format) is relatively small. It only has around 60 yes/no cases and although it was able to train, the accuracy wasn't very good. My solution to that was just duplicating the dataset and on each duplication, making tiny changes to the numbers, i.e., adding +-1 or multiplying by 0.999 to each number. By doing this I grew the size of the dataset to around 1100 new cases and it achieved much higher levels of accuracy. I was wondering if this is an actual technique used by ML researchers and if it is, does it have an actual official/academic name?

Thank You!

答:
Yes, the process you are referring to is called data augmentation.

However, I would highly recommend you to not use neural networks on datasets with merely hundred to thousand rows. Ideally Neural networks are used to train models over large datasets.


问:
Autorun script for any activity on linux server
so i have around 500 servers for which i wanted to create a script that automatically login and do some trivial activity to create some logs (basically want to send logs through siem tool to check if log sending is working or not) and then automatically logoff from the server.
I am planning that the script can be auto-run on the server every 15 days.
trivial activity can be anything(just want to create logs).
Any help how to achieve that??

EDIT

i was thinking now that stopping and starting a service in server will accomplish my need. Any help on that script. i am actually new in working in linux server. so any help is greatly appriciated.

答:
This can be done by cronjobs, you can simply setup a cronjob to do the task,

```<code>0 0 15 1-12 * /path/to/your/script
</code>```

This Cronjob will run at 00:00 on day-of-month 15 in every month from January through December.

Body:
This can be done by cronjobs, you can simply setup a cronjob to do the task,

0 0 15 1-12 * /path/to/your/script

This Cronjob will run at 00:00 on day-of-month 15 in every month from January through December.


问:
Hibernate many-to-many mapping
I am one of hibernate user in Australia. Recently, I have been dealing with hibernate many-to-many mapping and not going well though.
I got in trouble with "join/associate table with extra columns mapping".

Let`s say there are three tables called Product Order and OrderProduct (includes extra column quantity). Product holds many-to-many relationship with Order.

My confusion is that do we have to consider both ends of associate table when we are writing mapping files? or just write either side?
Also, is it necessary to produce mapping file for the associate table as well?

Any suggestions will be appreciated!!

答: You should have an association mapping and entity because you need to create them just like an other entity.</p>

ContentLicense: CC BY-SA 2.5

Title: Hibernate many-to-many mapping

ContentLicense: CC BY-SA 3.0


问:
Boyer Moore Algorithm Understanding and Example?
I am facing issues in understanding Boyer Moore String Search algorithm.

I am following the following document. Link

I am not able to work out my way as to exactly what is the real meaning of delta1 and delta2 here, and how are they applying this to find string search algorithm.
Language looked little vague..

Kindly if anybody out there can help me out in understanding this, it would be really helpful.

Or, if you know of any other link or document available that is easy to understand, then please share.

Thanks in advance.

答:
The insight behind Boyer-Moore is that if you start searching for a pattern in a string starting with the last character in the pattern, you can jump your search forward multiple characters when you hit a mismatch.

Let's say our pattern p is the sequence of characters p1, p2, ..., pn and we are searching a string s, currently with p aligned so that pn is at index i in s.

E.g.:

```<code>s = WHICH FINALLY HALTS.  AT THAT POINT...
p = AT THAT
i =       ^
</code>```

The B-M paper makes the following observations:

(1) if we try matching a character that is not in p then we can jump forward n characters:

'F' is not in p, hence we advance n characters:

```<code>s = WHICH FINALLY HALTS.  AT THAT POINT...
p =        AT THAT
i =              ^
</code>```

(2) if we try matching a character whose last position is k from the end of p then we can jump forward k characters:

' 's last position in p is 4 from the end, hence we advance 4 characters:

```<code>s = WHICH FINALLY HALTS.  AT THAT POINT...
p =            AT THAT
i =                  ^
</code>```

Now we scan backwards from i until we either succeed or we hit a mismatch.
(3a) if the mismatch occurs k characters from the start of p and the mismatched character is not in p, then we can advance (at least) k characters.

'L' is not in p and the mismatch occurred against p6, hence we can advance (at least) 6 characters:

```<code>s = WHICH FINALLY HALTS.  AT THAT POINT...
p =                  AT THAT
i =                        ^
</code>```

However, we can actually do better than this.
(3b) since we know that at the old i we'd already matched some characters (1 in this case).  If the matched characters don't match the start of p, then we can actually jump forward a little more (this extra distance is called 'delta2' in the paper):

```<code>s = WHICH FINALLY HALTS.  AT THAT POINT...
p =                   AT THAT
i =                         ^
</code>```

At this point, observation (2) applies again, giving

```<code>s = WHICH FINALLY HALTS.  AT THAT POINT...
p =                       AT THAT
i =                             ^
</code>```

and bingo!  We're done.

Body:
The insight behind Boyer-Moore is that if you start searching for a pattern in a string starting with the last character in the pattern, you can jump your search forward multiple characters when you hit a mismatch.

Let's say our pattern p is the sequence of characters p1, p2, ..., pn and we are searching a string s, currently with p aligned so that pn is at index i in s.

E.g.:

s = WHICH FINALLY HALTS.  AT THAT POINT...
p = AT THAT
i =       ^

The B-M paper makes the following observations:

(1) if we try matching a character that is not in p then we can jump forward n characters:

'F' is not in p, hence we advance n characters:

s = WHICH FINALLY HALTS.  AT THAT POINT...
p =        AT THAT
i =              ^

(2) if we try matching a character whose last position is k from the end of p then we can jump forward k characters:

' 's last position in p is 4 from the end, hence we advance 4 characters:

s = WHICH FINALLY HALTS.  AT THAT POINT...
p =            AT THAT
i =                  ^

Now we scan backwards from i until we either succeed or we hit a mismatch.
(3a) if the mismatch occurs k characters from the start of p and the mismatched character is not in p, then we can advance (at least) k characters.

'L' is not in p and the mismatch occurred against p6, hence we can advance (at least) 6 characters:

s = WHICH FINALLY HALTS.  AT THAT POINT...
p =                  AT THAT
i =                        ^

However, we can actually do better than this.
(3b) since we know that at the old i we'd already matched some characters (1 in this case).  If the matched characters don't match the start of p, then we can actually jump forward a little more (this extra distance is called 'delta2' in the paper):

s = WHICH FINALLY HALTS.  AT THAT POINT...
p =                   AT THAT
i =                         ^

At this point, observation (2) applies again, giving

s = WHICH FINALLY HALTS.  AT THAT POINT...
p =                       AT THAT
i =                             ^

and bingo!  We're done.


问:
Change View Color with alpha animation
I am writing an code where need to modified view background from one color to other color along alpha animation.

I tried with

```<code>ObjectAnimator backgroundColorAnimator = ObjectAnimator.ofObject(stickyLayout,
                        "backgroundColor",
                        new ArgbEvaluator(),
                        0xFFFFFFFF,
                        0xff78c5f9);
</code>```

EDIT: Since most of us not clear, Assume we need to change this color with alpha on seekbar updated values above mentioned solution work somewhat but not as expected with alpha...any suggestion?

答:
Use Color.parseColor instead of directly 0x value. Code example in Kotlin though

```<code>val objectAnimator = ObjectAnimator.ofObject(my_2_text, "backgroundColor",  ArgbEvaluator(),
    Color.parseColor("#FFFFFFFF"), Color.parseColor("#FF78c5f9"))
</code>```

Title: Change View Color with alpha animation

Body:
I am writing an code where need to modified view background from one color to other color along alpha animation.

I tried with

ObjectAnimator backgroundColorAnimator = ObjectAnimator.ofObject(stickyLayout,
                        "backgroundColor",
                        new ArgbEvaluator(),
                        0xFFFFFFFF,
                        0xff78c5f9);

EDIT: Since most of us not clear, Assume we need to change this color with alpha on seekbar updated values above mentioned solution work somewhat but not as expected with alpha...any suggestion?

Body:
Use Color.parseColor instead of directly 0x value. Code example in Kotlin though

val objectAnimator = ObjectAnimator.ofObject(my_2_text, "backgroundColor",  ArgbEvaluator(),
    Color.parseColor("#FFFFFFFF"), Color.parseColor("#FF78c5f9"))


问:
Retrieve all documents of my collection with firestore PHP
Hello I have the following database in firestore, and this code where I get the documents of the "ride" collection.

```<code>$db = new FirestoreClient([
     'projectId' => 'taxi-17b9c',
   ]);

$citiesRef = $db->collection('ride');
$documents = $citiesRef->documents();
foreach ($documents as $document) {
    if ($document->exists()) {
        print json_encode($document->data(), JSON_PRETTY_PRINT);
    }
</code>```

Basically my question is: why when I do a return of $document-> data(), I have only the json of a single document, but when I do print_r ($document-> data()) or json_encode ($document-> data()), the information is complete.

What I want is to iterate over the "ride" collection and obtain in json format the data of the documents that I have.

What do I need to add?
Thank you!
Cheers!

答:
If this is your server php code and you have only replaced "print" with "return", your function will only return data() of one existing $document and in your case only the data() of the first existing $document.

If this is all of your code, you can try to replace "print" with "echo":

$db = new FirestoreClient([
     'projectId' => 'taxi-17b9c',
   ]);

$citiesRef = $db->collection('ride');
$documents = $citiesRef->documents();
foreach ($documents as $document) {
    if ($document->exists()) {
        echo json_encode($document->data(), JSON_PRETTY_PRINT);
    }
}

```

<p>You can also collect your existing <code>$document</code> in a new object or array in order to return it as one string, as shown in the following simple examples. </p>

<h2>Additional "simple" examples</h2>

<pre class="lang-php prettyprint-override"><code><?php
$testObjs = array(
    'object1' => array('info'=>'taxi-17b9c', "foo"=>"bar"),
    'object2' => array('info'=>'taxi-17b9c'),
    'object3' => array('info'=>'taxi-23', "foo"=>"bla")
   );

echo "echo as single object strings: \n";
foreach ($testObjs as $obj) {
    if(isset($obj["foo"])){
        echo json_encode($obj, JSON_PRETTY_PRINT);
    }
}

echo "\nexample return as one string array: \n";
echo showReturn($testObjs);

function showReturn($testObjs){
    $new_testObjs = array();
    foreach ($testObjs as $obj) {
        if(isset($obj["foo"])){
            array_push($new_testObjs, $obj);
        }
    }
    return json_encode($new_testObjs, JSON_PRETTY_PRINT);
}

</code>```

Body:
Hello I have the following database in firestore, and this code where I get the documents of the "ride" collection.

$db = new FirestoreClient([
     'projectId' => 'taxi-17b9c',
   ]);

$citiesRef = $db->collection('ride');
$documents = $citiesRef->documents();
foreach ($documents as $document) {
    if ($document->exists()) {
        print json_encode($document->data(), JSON_PRETTY_PRINT);
    }

Basically my question is: why when I do a return of $document-> data(), I have only the json of a single document, but when I do print_r ($document-> data()) or json_encode ($document-> data()), the information is complete.

What I want is to iterate over the "ride" collection and obtain in json format the data of the documents that I have.

What do I need to add?
Thank you!
Cheers!

Body:
If this is your server php code and you have only replaced "print" with "return", your function will only return data() of one existing $document and in your case only the data() of the first existing $document.

If this is all of your code, you can try to replace "print" with "echo":

$db = new FirestoreClient([
     'projectId' => 'taxi-17b9c',
   ]);

$citiesRef = $db->collection('ride');
$documents = $citiesRef->documents();
foreach ($documents as $document) {
    if ($document->exists()) {
        echo json_encode($document->data(), JSON_PRETTY_PRINT);
    }
}

You can also collect your existing $document in a new object or array in order to return it as one string, as shown in the following simple examples.

Additional "simple" examples

<?php
$testObjs = array(
    'object1' => array('info'=>'taxi-17b9c', "foo"=>"bar"),
    'object2' => array('info'=>'taxi-17b9c'),
    'object3' => array('info'=>'taxi-23', "foo"=>"bla")
   );

echo "echo as single object strings: \n";
foreach ($testObjs as $obj) {
    if(isset($obj["foo"])){
        echo json_encode($obj, JSON_PRETTY_PRINT);
    }
}

echo "\nexample return as one string array: \n";
echo showReturn($testObjs);

function showReturn($testObjs){
    $new_testObjs = array();
    foreach ($testObjs as $obj) {
        if(isset($obj["foo"])){
            array_push($new_testObjs, $obj);
        }
    }
    return json_encode($new_testObjs, JSON_PRETTY_PRINT);
}


问:
Visual Studio does not show errors in the code anymore
I've been using Visual Studio (2017) for quite a long time now, to program mostly in C#, for Unity games. Recently though, I noticed that it was not displaying any errors in the code anymore, or at least most of them. I initially started making some small tests, for example removing variables that were being used multiple times in the scripts. Visual Studio was not showing any errors, while when going back to Unity, it was showing all the correct errors in the console (as always). Instead, if I tried to remove a parenthese, it was, after a bit, showing errors all over the place. Again, it was really strange.

After one day, I was still testing, and I noticed that if I first opened Visual Studio, and then in "recent" I clicked on the the .sln file, that opened all the scripts for one Unity project, it was immediately showing all the right errors, like it had always done and how (I think) it should always do. I started looking for some differences between what I was seeing there, and what I was seeing when opening the .cs files (in the way that wasn't working):

At the top, I wasn't seeing "Debug" and "Any CPU" how I was when it was working:

Another thing was that, between the "Project" and the "Debug" buttons (at the top, that open the drop-down lists), I didn't have the "Compile" button.

Also, under the the "Debug" drop-down many options like "start debug" were not available / disabled.

At the top left, under the left-most script name, I have "External files" instead of "Assembly-CSharp"

At the right of where there should be "Debug" and "Any CPU", I have "Connect" instead of "Start" (Or something similar, my system's language is not english, these are translations)

Another (maybe less relevant) thing that has changed from before, when it was working:

I have installed Visual Studio 2019, and uninstalled after a few minutes (I've always preferred Visual Studio 2017!).

Programming without seeing the errors realtime takes much more time, so I'd really like to fix this problem, if it is possible to do so. Is there anything that I have to activate? Did I accidentally press a combination of keys?

Thanks in advance! :)

答:
I had this issue for a while and it had to do with my solution.
I went to my project, ran a code analysis on it, then I re-targeted it to an older version. </p>

<p>I have no idea why this worked, however it fixed the issue. </p>

Body:
I had this issue for a while and it had to do with my solution.
I went to my project, ran a code analysis on it, then I re-targeted it to an older version.

I have no idea why this worked, however it fixed the issue.


问:
Split sentences string into new line properly (JAVA)
I want to split sentence (thai language) in proper way in pdf report (by JAVA) Please see my code below as.

```<code>def document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(Constants.FILE));
document.open()
document.setMargins(1,1,1,1);
Font fontSarabunBold = new Font(BaseFont.createFont("fonts/THSarabun Bold.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
Paragraph para1 = new Paragraph(20, "ณ ป่าใหญ่แห่งหนึ่ง มีกระต่ายตัวหนึ่งมั่นใจในความเร็วของฝีเท้าตัวเองมาก และมักพูดโม้โอ้อวดว่าไม่มีใครเทียบเทียมได้ จนวันหนึ่งเจ้ากระต่ายได้พบกับเต่าที่กำลังเดินต้วมเตี้ยมผ่านมา เมื่อเห็นดังนั้น เจ้ากระต่ายก็หัวเราะเยาะและพูดล้อเลียนว่า นี่เจ้าเต่า มัวแต่เดินอืดอาดอย่างนี้ แล้วเมื่อไรจะถึงบ้านกันล่ะเนี่ย ต่อให้เจ้าเดินนำหน้าไปก่อนครึ่งวัน ข้ายังตามเจ้าทันเลย", fontSarabunBold)
document.add(para1);
document.close()
</code>```

This is result.

It seems that program split sentence by space.

But I want to get sentences which are spitted in proper way same as I typed sentences in Microsoft Word.

This is expected result.

答:
Bell,in Paragraph writing PdfWriter , if sentence is not fitting in one line, it automatically move to next line after space as  our formal language sentences are completed by dot "." , so there possible way to do this work .

1)  Assign complete sentence to   para1 = new Paragraph(20,"this is sentence.");
and then move to next line and assign new paragraph.

Body:
I want to split sentence (thai language) in proper way in pdf report (by JAVA) Please see my code below as.

def document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(Constants.FILE));
document.open()
document.setMargins(1,1,1,1);
Font fontSarabunBold = new Font(BaseFont.createFont("fonts/THSarabun Bold.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
Paragraph para1 = new Paragraph(20, "ณ ป่าใหญ่แห่งหนึ่ง มีกระต่ายตัวหนึ่งมั่นใจในความเร็วของฝีเท้าตัวเองมาก และมักพูดโม้โอ้อวดว่าไม่มีใครเทียบเทียมได้ จนวันหนึ่งเจ้ากระต่ายได้พบกับเต่าที่กำลังเดินต้วมเตี้ยมผ่านมา เมื่อเห็นดังนั้น เจ้ากระต่ายก็หัวเราะเยาะและพูดล้อเลียนว่า นี่เจ้าเต่า มัวแต่เดินอืดอาดอย่างนี้ แล้วเมื่อไรจะถึงบ้านกันล่ะเนี่ย ต่อให้เจ้าเดินนำหน้าไปก่อนครึ่งวัน ข้ายังตามเจ้าทันเลย", fontSarabunBold)
document.add(para1);
document.close()

This is result.

It seems that program split sentence by space.

But I want to get sentences which are spitted in proper way same as I typed sentences in Microsoft Word.

This is expected result.


问:
Android - Obtain a key from a certification authority like VeriSign
Hi

I have written a program, my boss ask me to sign the apk file without self-signed, how can I get the certificate from any authority like VeriSign?

Thanks

答:
You can not use a Verisign or other commercial code-signing certificate to sign Android APKs for distribution in Android Market. The Android Market requires that the certificate expiry date have a year greater than or equal to 2033, but no commercial certificate vendor will sell you a cert with an expiry date that far in the future (their business is forcing you to come back and pay every year: selling you a 3-decade cert kind of defeats that). See http://developer.android.com/guide/publishing/app-signing.html#releasemode for the date information.

So no, you can not use a commercial authority cert.


问:
Maximum mark in Subject with Staff name
Write a query to display list of staff name, subject name handled, maximum mark scored in that subject. Give an alias to the maximum mark as max_mark. Sort the result based on maximum mark in descending.

This is the schema diagram.

This is the code I have tried.

select distinct
       staff_name,
       subject_name,
       max(value) over (partition by sb.staff_id) as max_mark
from   subject sb
       inner join staff st
       on st.staff_id=sb.staff_id
       inner join mark m
       on m.subject_id=sb.subject_id
order by max_mark desc;
```

I was abled to pass one testcase but I could not abled to pass second testcase and I don't know what second testcase is and also I am not getting what I have done wrong in my above code.Is there any way of getting solution for this problem.

答:
I think that you want aggregation:</p>

```<code>select
    st.staff_name,
    su.subject_name,
    max(ma.value) as max_mark
from subject su
inner join staff st on st.staff_id   = sb.staff_id
inner join mark ma  on ma.subject_id = su.subject_id
group by st.staff_id, st.staff_name, su.subject_id, su.subject_name
order by max_mark desc;
</code>```

Title: Maximum mark in Subject with Staff name

Body:
Write a query to display list of staff name, subject name handled, maximum mark scored in that subject. Give an alias to the maximum mark as max_mark. Sort the result based on maximum mark in descending.

This is the schema diagram.

This is the code I have tried.

select distinct
       staff_name,
       subject_name,
       max(value) over (partition by sb.staff_id) as max_mark
from   subject sb
       inner join staff st
       on st.staff_id=sb.staff_id
       inner join mark m
       on m.subject_id=sb.subject_id
order by max_mark desc;

I was abled to pass one testcase but I could not abled to pass second testcase and I don't know what second testcase is and also I am not getting what I have done wrong in my above code.Is there any way of getting solution for this problem.

Body:
I think that you want aggregation:

select
    st.staff_name,
    su.subject_name,
    max(ma.value) as max_mark
from subject su
inner join staff st on st.staff_id   = sb.staff_id
inner join mark ma  on ma.subject_id = su.subject_id
group by st.staff_id, st.staff_name, su.subject_id, su.subject_name
order by max_mark desc;


问:
Get ids on windows
I have an error that I cannot solve, not even searching the internet.
My code:

```<code>public static void GetClasses(ref List<ListViewItem> items)
    {
        ManagementPath path = new ManagementPath(string.Format("\\\\{0}\\ROOT\\CIMV2", SystemInformation.ComputerName.ToUpperInvariant()));
        ConnectionOptions options = new ConnectionOptions
        {
            EnablePrivileges = true,
            Impersonation = ImpersonationLevel.Impersonate,
            Authentication = AuthenticationLevel.Default,
            Username = null,
            SecurePassword = null
        };
        ManagementScope managementScope = new ManagementScope(path, options);
        managementScope.Connect();
        ObjectGetOptions options2 = new ObjectGetOptions();
        new ManagementScope(new ManagementObject(managementScope, path, options2).Path, options);
        ObjectQuery query = new ObjectQuery("SELECT * FROM meta_class WHERE __Class LIKE \"%%%\" AND NOT __Class LIKE \"[_][_]%\" AND NOT __Class LIKE \"Win32_Perf%\" AND NOT __Class LIKE \"MSFT[_]%\"");
        EnumerationOptions options3 = new EnumerationOptions
        {
            EnumerateDeep = true,
            UseAmendedQualifiers = true
        };
        ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, query, options3);
        new List<WMIClass>();
        foreach (ManagementClass managementClass in from ManagementClass currentClass in managementObjectSearcher.Get()
                                                    orderby currentClass.ClassPath.ClassName
                                                    select currentClass)
        {
            bool flag = false;
            // using (ManagementObjectCollection.ManagementObjectEnumerator enumerator2 = disks.GetEnumerator())
            using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
            {
                while (enumerator2.MoveNext())
                {
                    if (enumerator2.Current.Type == CimType.String)
                    {
                        flag = true;
                    }
                }
            }
            if (flag)
            {
                WMIClass wmiclass = new WMIClass(managementClass);
                ListViewItem listViewItem = new ListViewItem
                {
                    Name = wmiclass.DisplayName,
                    Text = wmiclass.DisplayName,
                    ToolTipText = wmiclass.Description,
                    Tag = wmiclass
                };
                listViewItem.SubItems.Add(wmiclass.Description);
                items.Add(listViewItem);
            }
        }
    }
</code>```

Error line:

```<code>using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
// using (ManagementObjectCollection.ManagementObjectEnumerator enumerator2 = disks.GetEnumerator())
</code>```

I don't know what the mistake is. If you can help me please I don't understand the language very well.
I would greatly appreciate your help.

答:
Try changing

```<code>using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
{
    while (enumerator2.MoveNext())
    {
        if (enumerator2.Current.Type == CimType.String)
        {
            flag = true;
        }
    }
}
</code>```

to

```<code>PropertyDataCollection.PropertyDataEnumerator enumerator2 = managementClass.Properties.GetEnumerator();
while (enumerator2.MoveNext())
{
    if (enumerator2.Current.Type == CimType.String)
    {
        flag = true;
    }
}
</code>```

First, "using" must be removed because GetEnumerator() does not return a disposable object and second, use "managementClass.Properties.GetEnumerator()" instead of "ManagementClass.Properties.GetEnumerator()".

Title: Get ids on windows

Body:
I have an error that I cannot solve, not even searching the internet.
My code:

public static void GetClasses(ref List<ListViewItem> items)
    {
        ManagementPath path = new ManagementPath(string.Format("\\\\{0}\\ROOT\\CIMV2", SystemInformation.ComputerName.ToUpperInvariant()));
        ConnectionOptions options = new ConnectionOptions
        {
            EnablePrivileges = true,
            Impersonation = ImpersonationLevel.Impersonate,
            Authentication = AuthenticationLevel.Default,
            Username = null,
            SecurePassword = null
        };
        ManagementScope managementScope = new ManagementScope(path, options);
        managementScope.Connect();
        ObjectGetOptions options2 = new ObjectGetOptions();
        new ManagementScope(new ManagementObject(managementScope, path, options2).Path, options);
        ObjectQuery query = new ObjectQuery("SELECT * FROM meta_class WHERE __Class LIKE \"%%%\" AND NOT __Class LIKE \"[_][_]%\" AND NOT __Class LIKE \"Win32_Perf%\" AND NOT __Class LIKE \"MSFT[_]%\"");
        EnumerationOptions options3 = new EnumerationOptions
        {
            EnumerateDeep = true,
            UseAmendedQualifiers = true
        };
        ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, query, options3);
        new List<WMIClass>();
        foreach (ManagementClass managementClass in from ManagementClass currentClass in managementObjectSearcher.Get()
                                                    orderby currentClass.ClassPath.ClassName
                                                    select currentClass)
        {
            bool flag = false;
            // using (ManagementObjectCollection.ManagementObjectEnumerator enumerator2 = disks.GetEnumerator())
            using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
            {
                while (enumerator2.MoveNext())
                {
                    if (enumerator2.Current.Type == CimType.String)
                    {
                        flag = true;
                    }
                }
            }
            if (flag)
            {
                WMIClass wmiclass = new WMIClass(managementClass);
                ListViewItem listViewItem = new ListViewItem
                {
                    Name = wmiclass.DisplayName,
                    Text = wmiclass.DisplayName,
                    ToolTipText = wmiclass.Description,
                    Tag = wmiclass
                };
                listViewItem.SubItems.Add(wmiclass.Description);
                items.Add(listViewItem);
            }
        }
    }

Error line:

using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
// using (ManagementObjectCollection.ManagementObjectEnumerator enumerator2 = disks.GetEnumerator())

I don't know what the mistake is. If you can help me please I don't understand the language very well.
I would greatly appreciate your help.

Body:
Try changing

using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
{
    while (enumerator2.MoveNext())
    {
        if (enumerator2.Current.Type == CimType.String)
        {
            flag = true;
        }
    }
}

to

PropertyDataCollection.PropertyDataEnumerator enumerator2 = managementClass.Properties.GetEnumerator();
while (enumerator2.MoveNext())
{
    if (enumerator2.Current.Type == CimType.String)
    {
        flag = true;
    }
}

First, "using" must be removed because GetEnumerator() does not return a disposable object and second, use "managementClass.Properties.GetEnumerator()" instead of "ManagementClass.Properties.GetEnumerator()".


问:
default backend - 404 Apache with ssl
I am pretty much new to apache. I am trying to use the apache official container to redirect the incoming traffic to below 2 pods
Pod-1. To my own custom container(CC) (this is a http service).
Pod-22. To cutomised rabbitmq container.
    I am exposing both 80 and 443 of apache. I am able to access my application which is running on Pod-1. But if I try to access using 80 (which is redirected to https[443]) i get default backend error. I have enabled the "mod_socache_shmcb.so", "mod_ssl.so" moduels and included my config file. Below is my config file. </p>

```<code><VirtualHost *>

    ServerName apachessl
    Redirect / https://apachessl/

</VirtualHost>

<VirtualHost *:443>
ServerName apachessl

SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off

SSLEngine on
SSLProtocol -ALL +TLSv1
SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM
SSLCertificateFile /usr/local/apache2/conf/certificate.crt
SSLCertificateKeyFile /usr/local/apache2/conf/privateKey.key

ProxyPreserveHost On

KeepAlive On
MaxKeepAliveRequests 0
ProxyTimeout 600

SSLProxyEngine on

ProxyPass /ws wss://rmqssl-app-loc:15674/ws
ProxyPassReverse /ws wss://apachessl/ws

ProxyPass / http://my-apllication:6543/
ProxyPassReverse / https://apachessl/

    ErrorLog "logs/my_application_log"
    LogLevel error
</code>```

答:
If you are using it from kubernetes and receiving default backend 404 error ... it essentially means that the domain using which the request is landing to kubernetes ingress controller is not mapped to any of the ingress.

So what you need is to check when request on port 80 is redirected to 443, the url apachessl --> has one ingress mapped in ingress definition under specs .. something like -

```<code>spec:
  rules:
  - host: apachessl
    http:
      paths:
      - backend:
          serviceName: <<your-app-service-exposed-on-k8s>>
          servicePort: 80
        path: /
  tls:
    - hosts:
      - apachessl
      secretName: <<your-ssl-secret>>
</code>```

Can you share your ingress definition, just to be clear what needs to be fixed.

Title: default backend - 404 Apache with ssl

Body:
I am pretty much new to apache. I am trying to use the apache official container to redirect the incoming traffic to below 2 pods
Pod-1. To my own custom container(CC) (this is a http service).
Pod-22. To cutomised rabbitmq container.
    I am exposing both 80 and 443 of apache. I am able to access my application which is running on Pod-1. But if I try to access using 80 (which is redirected to https[443]) i get default backend error. I have enabled the "mod_socache_shmcb.so", "mod_ssl.so" moduels and included my config file. Below is my config file.

<VirtualHost *>

    ServerName apachessl
    Redirect / https://apachessl/

</VirtualHost>

<VirtualHost *:443>
ServerName apachessl

SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off

SSLEngine on
SSLProtocol -ALL +TLSv1
SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM
SSLCertificateFile /usr/local/apache2/conf/certificate.crt
SSLCertificateKeyFile /usr/local/apache2/conf/privateKey.key

ProxyPreserveHost On

KeepAlive On
MaxKeepAliveRequests 0
ProxyTimeout 600

SSLProxyEngine on

ProxyPass /ws wss://rmqssl-app-loc:15674/ws
ProxyPassReverse /ws wss://apachessl/ws

ProxyPass / http://my-apllication:6543/
ProxyPassReverse / https://apachessl/

    ErrorLog "logs/my_application_log"
    LogLevel error

Body:
If you are using it from kubernetes and receiving default backend 404 error ... it essentially means that the domain using which the request is landing to kubernetes ingress controller is not mapped to any of the ingress.

So what you need is to check when request on port 80 is redirected to 443, the url apachessl --> has one ingress mapped in ingress definition under specs .. something like -

spec:
  rules:
  - host: apachessl
    http:
      paths:
      - backend:
          serviceName: <<your-app-service-exposed-on-k8s>>
          servicePort: 80
        path: /
  tls:
    - hosts:
      - apachessl
      secretName: <<your-ssl-secret>>

Can you share your ingress definition, just to be clear what needs to be fixed.


问:
How to convert Python variables into equivalent cobol group variables?
I am working on the COBOL module for which I need to convert the Python variables to the equivalent COBOL variables.
I am receiving data from an web application and it needs to be given to cobol module.So I am reading that data in python and storing it in variables, now i need to convert each variable to COBOL variable.
So I can use those values with copybook which is already present in my system.

I have tried to search on github using pycobol but it is all COBOL to python (lists,csv)
What I need is exactly opposite.

For Example if in python i have h=6,b='ab'
it should be converted to

```<code>01   H     PIC 9(1) value 9
01   B     PIC X(2) value 'AB'
</code>```

答: Simon Sobisch's comment should be turn into an answer.  It's probably easy for python to output something into json text file; then in the COBOL side, you can JSON PARSE that into COBOL.</p>

Body:
I am working on the COBOL module for which I need to convert the Python variables to the equivalent COBOL variables.
I am receiving data from an web application and it needs to be given to cobol module.So I am reading that data in python and storing it in variables, now i need to convert each variable to COBOL variable.
So I can use those values with copybook which is already present in my system.

I have tried to search on github using pycobol but it is all COBOL to python (lists,csv)
What I need is exactly opposite.

For Example if in python i have h=6,b='ab'
it should be converted to

01   H     PIC 9(1) value 9
01   B     PIC X(2) value 'AB'


问:
How to crawl a webpage with selectors?
I'm crawling a webpage: ogimet.com
This is my code:

```<code>import time
from urllib.request import urlopen
from bs4 import BeautifulSoup
from selenium import webdriver

#this path may be different on your cpu, you need to install a browser driver
driver = webdriver.Chrome(executable_path=r'C:/Users/jcrav/Desktop/driver/chromedriver.exe')
url="http://www.ogimet.com/"
driver.get(url)
#driver = webdriver.Chrome(driver)
#driver.get(url)

the_link = driver.find_element_by_xpath('/html/body/table/tbody/tr[2]/td[1]/div[19]/a')
the_link.click()
time.sleep(2)

desplegable_pais = driver.find_element_by_css_selector('select[name="estado"] option[value="Peru"]')
desplegable_pais.click()
time.sleep(2)
</code>```

The issue is that some selectors does not have a variable named value.
When i select a country, the selector has a variable named value.

```<code><option value="Peru">Perú</option>
</code>```

But when i select year, does not have a variable named value

```<code><option>2004</option>
</code>```

How can i select a year with the .click command?

答:
use element.text for finding what you want

Below is example

```<code>want_year_num = 2004
elements = driver.find_elements_by_xpath('/html/body/table/tbody/tr[2]/td[2]/form/table[3]/tbody/tr[2]/td[2]/select/option')
for element in elements:
    if element.text == str(want_year_num):
        element.click()
        break

</code>```

Title: How to crawl a webpage with selectors?

Body:
I'm crawling a webpage: ogimet.com
This is my code:

import time
from urllib.request import urlopen
from bs4 import BeautifulSoup
from selenium import webdriver

#this path may be different on your cpu, you need to install a browser driver
driver = webdriver.Chrome(executable_path=r'C:/Users/jcrav/Desktop/driver/chromedriver.exe')
url="http://www.ogimet.com/"
driver.get(url)
#driver = webdriver.Chrome(driver)
#driver.get(url)

the_link = driver.find_element_by_xpath('/html/body/table/tbody/tr[2]/td[1]/div[19]/a')
the_link.click()
time.sleep(2)

desplegable_pais = driver.find_element_by_css_selector('select[name="estado"] option[value="Peru"]')
desplegable_pais.click()
time.sleep(2)

The issue is that some selectors does not have a variable named value.
When i select a country, the selector has a variable named value.

<option value="Peru">Perú</option>

But when i select year, does not have a variable named value

<option>2004</option>

How can i select a year with the .click command?

Body:
use element.text for finding what you want

Below is example

want_year_num = 2004
elements = driver.find_elements_by_xpath('/html/body/table/tbody/tr[2]/td[2]/form/table[3]/tbody/tr[2]/td[2]/select/option')
for element in elements:
    if element.text == str(want_year_num):
        element.click()
        break


问:
Using a limit on a left join in mysql
The following query selects all posts and each post's owner, all of the comments that belong to each post, and the owner of each comment.

I need to only retrieve 5 comments per post. I rewrote the query, but I get an error of "each derived table must have it's own alias".

```<code>SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname, comments.id AS commentId, comments.text, commenters.id, commenters.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN comments ON posts.id = comments.postid
    JOIN users AS commenters ON comments.userId = commenters.id
ORDER BY posts.createdAt
</code>```

New Query:

```<code>SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN (
    SELECT comments.id AS commentId, comments.text AS commentText, commenters.id AS commenterId, commenters.displayname AS commenterDisplayName
    FROM comments
    JOIN users AS commenters ON comments.userid = commenters.id
    LIMIT 0,5
        ) AS comments ON comments.postid = posts.id
ORDER BY posts.createdAt
</code>```

UPDATE The query now works, but it does not produce the desired output. I want to output 10 posts, with 5 comments for each post. This limit clause will only apply for the comments of the first post encountered.

答:
From the edits and comment feedback, here's the query I think you are looking for... The inner most will prequery gets the posts and who initiated the post, comments and who posted the comments.  This inner query is also pre-sorted with the MOST RECENT COMMENTS to the top per postID.  Using the result of that, I'm joining to the sql variables (@variables) to get the @varRow increased every time a new comment and reset back to 1 each time a post ID changes (hence the inner PreQuery orders by post ID FIRST).  Finally, using the HAVING clause to have the comment's @varRow count < 6 will get at MOST 5 of each post.

If you want to limit what posts you are trying to retrieve, I would apply a WHERE clause (such as date/time if available) at the INNER most that generates the "PreQuery".

```<code>select straight_join
      PreQuery.*,
      @varRow := if( @LastPost = PreQuery.PostID, @varRow +1, 1 ) CommentRow,
      @LastPost := PreQuery.PostID PostID2
   from
      ( select
              posts.id PostID,
              posts.body,
              posts.CreatedAt,
              u1.id UserID,
              u1.DisplayName NameOfPoster,
              c.id,
              c.userid CommentUserID,
              c.text CommentText,
              u2.DisplayName CommentUserName
           from
              posts
                 join users u1
                    on posts.ownerUserID = u1.id

                 LEFT JOIN comments c
                    on posts.id = c.PostID

                    join users u2
                       on c.userid = u2.id
            where
                  posts.id = TheOneParentIDYouWant
               OR posts.parentid = TheOneParentIDYouWant
            order by
               posts.ID,
               c.id desc ) PreQuery,

      (select @varRow := 0, @LastPost = 0 ) SQLVars

   having
      CommentRow < 6

   order by
      PreQuery.postid,
      CommentRow
</code>```

--- EDIT --- per comment
I THINK what you mean by which "Parent Post" the comments are associated with is because they have the post ID directly.  Since the inner-most query does a join of all elements / tables across the board, all are coming along for the ride...

```<code>Post -> User (to get posting user name )
Post -> Comment (on Common Post ID -- left joined)
        Comment -> User ( to get commenting user name)
</code>```

Once THAT is all done and sorted by common Post ID and most recent comment sorted to the top, I then apply the @vars against ALL returned rows.  The HAVING clause will strip out any comment where it's sequence is BEYOND the 5 you were looking for.

Title: Using a limit on a left join in mysql

Body:
The following query selects all posts and each post's owner, all of the comments that belong to each post, and the owner of each comment.

I need to only retrieve 5 comments per post. I rewrote the query, but I get an error of "each derived table must have it's own alias".

SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname, comments.id AS commentId, comments.text, commenters.id, commenters.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN comments ON posts.id = comments.postid
    JOIN users AS commenters ON comments.userId = commenters.id
ORDER BY posts.createdAt

New Query:

SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN (
    SELECT comments.id AS commentId, comments.text AS commentText, commenters.id AS commenterId, commenters.displayname AS commenterDisplayName
    FROM comments
    JOIN users AS commenters ON comments.userid = commenters.id
    LIMIT 0,5
        ) AS comments ON comments.postid = posts.id
ORDER BY posts.createdAt

UPDATE The query now works, but it does not produce the desired output. I want to output 10 posts, with 5 comments for each post. This limit clause will only apply for the comments of the first post encountered.

Body:
From the edits and comment feedback, here's the query I think you are looking for... The inner most will prequery gets the posts and who initiated the post, comments and who posted the comments.  This inner query is also pre-sorted with the MOST RECENT COMMENTS to the top per postID.  Using the result of that, I'm joining to the sql variables (@variables) to get the @varRow increased every time a new comment and reset back to 1 each time a post ID changes (hence the inner PreQuery orders by post ID FIRST).  Finally, using the HAVING clause to have the comment's @varRow count < 6 will get at MOST 5 of each post.

If you want to limit what posts you are trying to retrieve, I would apply a WHERE clause (such as date/time if available) at the INNER most that generates the "PreQuery".

select straight_join
      PreQuery.*,
      @varRow := if( @LastPost = PreQuery.PostID, @varRow +1, 1 ) CommentRow,
      @LastPost := PreQuery.PostID PostID2
   from
      ( select
              posts.id PostID,
              posts.body,
              posts.CreatedAt,
              u1.id UserID,
              u1.DisplayName NameOfPoster,
              c.id,
              c.userid CommentUserID,
              c.text CommentText,
              u2.DisplayName CommentUserName
           from
              posts
                 join users u1
                    on posts.ownerUserID = u1.id

                 LEFT JOIN comments c
                    on posts.id = c.PostID

                    join users u2
                       on c.userid = u2.id
            where
                  posts.id = TheOneParentIDYouWant
               OR posts.parentid = TheOneParentIDYouWant
            order by
               posts.ID,
               c.id desc ) PreQuery,

      (select @varRow := 0, @LastPost = 0 ) SQLVars

   having
      CommentRow < 6

   order by
      PreQuery.postid,
      CommentRow

--- EDIT --- per comment
I THINK what you mean by which "Parent Post" the comments are associated with is because they have the post ID directly.  Since the inner-most query does a join of all elements / tables across the board, all are coming along for the ride...

Post -> User (to get posting user name )
Post -> Comment (on Common Post ID -- left joined)
        Comment -> User ( to get commenting user name)

Once THAT is all done and sorted by common Post ID and most recent comment sorted to the top, I then apply the @vars against ALL returned rows.  The HAVING clause will strip out any comment where it's sequence is BEYOND the 5 you were looking for.


问:
How to use gapi for sending email in Angular 9
I created once service in angular9 and call google api for sending email but it doesn't work. may someone help what should I do? I tried many other ways but no one of them worked.

```<code>sendEmail() {
    const scopes = [
      'https://www.googleapis.com/auth/gmail.send',
    ].join(' ');

    const message =
      "From: sample@gmail.com\r\n" +
      "To: sample2@gmail.com\r\n" +
      "Subject: As basic as it gets\r\n\r\n" +
      "This is the plain text body of the message.  Note the blank line between the header information and the body of the message.";

    const encodedMessage = btoa(message)

    const reallyEncodedMessage = encodedMessage.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')

    gapi.load('client:auth2', () => {
      gapi.client.load('gmail', 'v1', () => {
        console.log('Loaded Gmail');
        gapi.client.init({
          apiKey: this.apiKey,
          discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest'],
          client_id: this.clientId,
          immediate: true,
          scope: scopes
        }).then(res => {
          console.log('pop')
          return gapi.client.gmail.users.messages.send({
            userId: 'me',
            requestBody: {
              raw: reallyEncodedMessage
            }
          }).then(res => {
            console.log("done!", res)
          });
        })
      });
    });
  }
</code>```

response from gapi:

```<code>kind: "discovery#restDescription"
id: "gmail:v1"
name: "gmail"
version: "v1"
rootUrl: "https://www.googleapis.com/"
servicePath: "gmail/v1/users/"
batchPath: "batch/gmail/v1"
</code>```

...

答:
finally I made it and below is my code:</p>

```<code>  checkForGmailLogin() {
    console.log('onLoadCallbackFunction');
    const scope = ['https://mail.google.com/',
      'https://www.googleapis.com/auth/gmail.modify',
      'https://www.googleapis.com/auth/gmail.compose',
      'https://www.googleapis.com/auth/gmail.send'].join(' ');
    gapi.auth.authorize(
      {
        'client_id': this.clientId,
        'scope': scope,
        'immediate': true,
        discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest'],
      }, authResult => {
        if (authResult && !authResult.error) {
          gapi.client.load('gmail', 'v1', () => this.sendEmail());
        } else {
          console.log('Error in Load gmail');
        }
      });
  }

  sendEmail() {
    const subject = 'Code';
    const code = '123'
    const mimeData = [
      "From: from@gmail.com",
      "To: to@gmail.com",
      "To: to@yahoo.com",
      "Subject: =?utf-8?B?" + window.btoa(unescape(encodeURIComponent(subject))) + "?=",
      "MIME-Version: 1.0",
      "Content-Type: text/plain; charset=UTF-8",
      "Content-Transfer-Encoding: 7bit",
      "",
      "Your code is " + code].join("\n").trim();
    const raw = window.btoa(unescape(encodeURIComponent(mimeData))).replace(/\+/g, '-').replace(/\//g, '_');
    gapi.client.gmail.users.messages.send({
      'userId': 'me',
      'resource': {
        'raw': raw
      }
    }).execute(res => {
      console.log('Email sent', res);
      this.snackBar.success('Email has send Successfully')});
  }
</code>```

Body:
I created once service in angular9 and call google api for sending email but it doesn't work. may someone help what should I do? I tried many other ways but no one of them worked.

sendEmail() {
    const scopes = [
      'https://www.googleapis.com/auth/gmail.send',
    ].join(' ');

    const message =
      "From: sample@gmail.com\r\n" +
      "To: sample2@gmail.com\r\n" +
      "Subject: As basic as it gets\r\n\r\n" +
      "This is the plain text body of the message.  Note the blank line between the header information and the body of the message.";

    const encodedMessage = btoa(message)

    const reallyEncodedMessage = encodedMessage.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')

    gapi.load('client:auth2', () => {
      gapi.client.load('gmail', 'v1', () => {
        console.log('Loaded Gmail');
        gapi.client.init({
          apiKey: this.apiKey,
          discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest'],
          client_id: this.clientId,
          immediate: true,
          scope: scopes
        }).then(res => {
          console.log('pop')
          return gapi.client.gmail.users.messages.send({
            userId: 'me',
            requestBody: {
              raw: reallyEncodedMessage
            }
          }).then(res => {
            console.log("done!", res)
          });
        })
      });
    });
  }

response from gapi:

kind: "discovery#restDescription"
id: "gmail:v1"
name: "gmail"
version: "v1"
rootUrl: "https://www.googleapis.com/"
servicePath: "gmail/v1/users/"
batchPath: "batch/gmail/v1"

...

Body:
finally I made it and below is my code:

  checkForGmailLogin() {
    console.log('onLoadCallbackFunction');
    const scope = ['https://mail.google.com/',
      'https://www.googleapis.com/auth/gmail.modify',
      'https://www.googleapis.com/auth/gmail.compose',
      'https://www.googleapis.com/auth/gmail.send'].join(' ');
    gapi.auth.authorize(
      {
        'client_id': this.clientId,
        'scope': scope,
        'immediate': true,
        discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest'],
      }, authResult => {
        if (authResult && !authResult.error) {
          gapi.client.load('gmail', 'v1', () => this.sendEmail());
        } else {
          console.log('Error in Load gmail');
        }
      });
  }

  sendEmail() {
    const subject = 'Code';
    const code = '123'
    const mimeData = [
      "From: from@gmail.com",
      "To: to@gmail.com",
      "To: to@yahoo.com",
      "Subject: =?utf-8?B?" + window.btoa(unescape(encodeURIComponent(subject))) + "?=",
      "MIME-Version: 1.0",
      "Content-Type: text/plain; charset=UTF-8",
      "Content-Transfer-Encoding: 7bit",
      "",
      "Your code is " + code].join("\n").trim();
    const raw = window.btoa(unescape(encodeURIComponent(mimeData))).replace(/\+/g, '-').replace(/\//g, '_');
    gapi.client.gmail.users.messages.send({
      'userId': 'me',
      'resource': {
        'raw': raw
      }
    }).execute(res => {
      console.log('Email sent', res);
      this.snackBar.success('Email has send Successfully')});
  }


问:
Index of the lower_bound of a value in sets and maps in c++
Suppose I want to get the index of the lower_bound of a value in a set and if i type

```<code>cout<<set.lower_bound(number)-set.begin()<<endl;
</code>```

It is showing an  error: no match for ‘operator-’

The same goes for maps as well,

However for arrays and vectors if i use

```<code>lower_bound(begin,end,val)-begin
</code>```

it is showing the index

Why is that?

答:
Yes, this because the operator - is not defined for the iterators of std::sets (bidirectional iterators) while it's defined for the arrays iterators (random access iterators).

Instead, you can use  std::distance(), as follows

```<code>int main()
{
    std::set<int> set {1, 2, 4, 5, 6};
    int number = 3;
    std::cout<<std::distance(set.begin(), set.lower_bound(number))<<std::endl;
}
</code>```

And note that your sets will be ordered. I don't know what u  expect.

And as john said there might be a design flaw. maybe you choose the wrong container for your purpose.

Body:
Suppose I want to get the index of the lower_bound of a value in a set and if i type

cout<<set.lower_bound(number)-set.begin()<<endl;

It is showing an  error: no match for ‘operator-’

The same goes for maps as well,

However for arrays and vectors if i use

lower_bound(begin,end,val)-begin

it is showing the index

Why is that?

Body:
Yes, this because the operator - is not defined for the iterators of std::sets (bidirectional iterators) while it's defined for the arrays iterators (random access iterators).

Instead, you can use  std::distance(), as follows

int main()
{
    std::set<int> set {1, 2, 4, 5, 6};
    int number = 3;
    std::cout<<std::distance(set.begin(), set.lower_bound(number))<<std::endl;
}

And note that your sets will be ordered. I don't know what u  expect.

And as john said there might be a design flaw. maybe you choose the wrong container for your purpose.


问:
Execute command in multiple sub-directories
Suppose I have folder structure like this

- Parent Folder/
       - code.sh
       - Child Folder 1/
             - Child Sub-Folder/
       - Child Folder 2/
       - Child Folder 3/
       - Child Folder 4/
```

<p>I need some kind of bash script which will be placed in code.sh and will  <strong>execute a command in Child Folder 1, Child Folder 2, Child Folder 3, Child Folder 4, etc.</strong> But not in <strong>Child Sub-Folder</strong></p>

<p>So far I have only found this solution</p>

```find ./* -mindepth 0 -maxdepth 0 -type d -exec git add -A {} \;
```

<p>Give me this error</p>

```fatal: not a git repository (or any of the parent directories): .git
```

<p>When I try this</p>

```find ./* -mindepth 0 -maxdepth 0 -type d -exec git add -A && git commit -m "My Message"{} \;
```

<p>Give me this error</p>

```find: missing argument to `-exec'
```

Any help will be really appreciated.

答:
A simple and robust approach, using bash parameter expansion:

```<code>#!/bin/bash

for dir in ./*/*/.git; do
    (
        cd "${dir%.git}"
        git add -A && git commit -m "My Message"
    )
done
</code>```

Ensure you are at the same level than 'Parent Folder' directory.

A bit of explanations:

the idea behind the snippet is to list all .git directory with a glob (wildcard) ./*/*/.git

${dir%.git} bash parameter expansion, remove .git substring

the subshell ( ) is there to not having to explore the FS with cd to next dir. Each iteration is run in a new (sub)shell

Body:
Suppose I have folder structure like this

- Parent Folder/
       - code.sh
       - Child Folder 1/
             - Child Sub-Folder/
       - Child Folder 2/
       - Child Folder 3/
       - Child Folder 4/

I need some kind of bash script which will be placed in code.sh and will  execute a command in Child Folder 1, Child Folder 2, Child Folder 3, Child Folder 4, etc. But not in Child Sub-Folder

So far I have only found this solution

find ./* -mindepth 0 -maxdepth 0 -type d -exec git add -A {} \;

Give me this error

fatal: not a git repository (or any of the parent directories): .git

When I try this

find ./* -mindepth 0 -maxdepth 0 -type d -exec git add -A && git commit -m "My Message"{} \;

Give me this error

find: missing argument to `-exec'

Any help will be really appreciated.

Body:
A simple and robust approach, using bash parameter expansion:

#!/bin/bash

for dir in ./*/*/.git; do
    (
        cd "${dir%.git}"
        git add -A && git commit -m "My Message"
    )
done

Ensure you are at the same level than 'Parent Folder' directory.

A bit of explanations:

the idea behind the snippet is to list all .git directory with a glob (wildcard) ./*/*/.git

${dir%.git} bash parameter expansion, remove .git substring

the subshell ( ) is there to not having to explore the FS with cd to next dir. Each iteration is run in a new (sub)shell


问:
Does using a prototype + definition instead of just a definition speed up the program?
Im very new to C programing, but have limited experience with Python, Java, and Perl. I was just wondering what the advantage is of having the prototype of a function above main() and the definition of that function below main() rather than just having the definition of said function above main(). From what I have read, the definition can act as a prototype as well.

Thanks in advance,

答:
When someone else wants to use your library, you can give them the header (containing the prototypes), without giving them your code.

Example? Windows SDK.

If two functions call each other, you will need to have a prototype for at least one of them.

There is no performance impact* on the compiled code.

*Note: Well, there could be, I guess. If the compiler decides to put the method somewhere else in the binary, then you could theoretically see locality issues affecting the performance of your application. It's not something to normally worry about, though.


问:
Return all nodes that are indirectly related to central node

Hey guys! Im working with python py2neo and Im having trouble with returning "COMPRAN..." and "COMPRAS STREETW...", which as you can see are indirectly related to "Oscar" by the two closest note to "Oscar." My idea is to return a list with all nodes related to Oscar in the same way "COMPRAN..." and "COMPRAS STREETW..." are related.

The code Im trying is the following:

```<code>lista = []
for record in db.run("MATCH (a:user)-[:watched]->(b:video), (b)-[:hasTag]->(c:tag), (b)-[:hasGenre]->(d:genre), (e:video)-[:hasGenre]->(d:genre), (e:video)-[:hasTag]->(c:tag) WHERE a.name = $name RETURN e.name UNION MATCH (a:user)-[:watched]->(b:video), (b)-[:hasGenre]->(d:genre), (e:video)-[:hasGenre]->(d:genre) RETURN e.name UNION MATCH (a:user)-[:watched]->(b:video), (b)-[:hasGenre]->(d:genre), (e:video)-[:hasTag]->(c:tag) RETURN e.name", name=name, video=video, tag=tag, genre=genre):
    lista.append(record["e.name"])
    return lista
</code>```

My problem is that it is only returning the node with the name "COMPRAS STREETW...", and my idea is that the query should return this node and "COMPRAN..." since they are related indirectly to "Oscar". Thanks for reading and hope you can help me get this to work.

答:
This Cypher code should find both desired nodes:

```<code>MATCH
  (u:user)-[:watched]->(v1),
  (v1)-[:hasTag]->(t)<-[:hasTag]-(v2),
  (v1)-[:hasGenre]->(g)<-[:hasGenre]-(v2)
WHERE u.name = $name
RETURN v2.name
</code>```

Body:
Hey guys! Im working with python py2neo and Im having trouble with returning "COMPRAN..." and "COMPRAS STREETW...", which as you can see are indirectly related to "Oscar" by the two closest note to "Oscar." My idea is to return a list with all nodes related to Oscar in the same way "COMPRAN..." and "COMPRAS STREETW..." are related.

The code Im trying is the following:

lista = []
for record in db.run("MATCH (a:user)-[:watched]->(b:video), (b)-[:hasTag]->(c:tag), (b)-[:hasGenre]->(d:genre), (e:video)-[:hasGenre]->(d:genre), (e:video)-[:hasTag]->(c:tag) WHERE a.name = $name RETURN e.name UNION MATCH (a:user)-[:watched]->(b:video), (b)-[:hasGenre]->(d:genre), (e:video)-[:hasGenre]->(d:genre) RETURN e.name UNION MATCH (a:user)-[:watched]->(b:video), (b)-[:hasGenre]->(d:genre), (e:video)-[:hasTag]->(c:tag) RETURN e.name", name=name, video=video, tag=tag, genre=genre):
    lista.append(record["e.name"])
    return lista

My problem is that it is only returning the node with the name "COMPRAS STREETW...", and my idea is that the query should return this node and "COMPRAN..." since they are related indirectly to "Oscar". Thanks for reading and hope you can help me get this to work.

Body:
This Cypher code should find both desired nodes:

MATCH
  (u:user)-[:watched]->(v1),
  (v1)-[:hasTag]->(t)<-[:hasTag]-(v2),
  (v1)-[:hasGenre]->(g)<-[:hasGenre]-(v2)
WHERE u.name = $name
RETURN v2.name


问:
Android MVVM 2 ViewModels Sharing 1 Repository with LiveData
I have a question regarding MVVM pattern with Repository.

I have an activity that hosts 2 fragments. Let's call them FragmentA and FragmentB.

These 2 fragments have their own viewModels like viewModelA and viewModelB.

I also have a repository class that serves only local data. No network request. Just a MutableList.

FragmentA and FragmentB observe their respective viewModel through LiveData.

```<code>//FragmentA Observes viewModelA
viewModelA.cartContent.observe(viewLifecycleOwner, Observer { content ->

})
</code>```

```<code>// ViewModelA exposes cartContent
val cartContent: LiveData<MutableList<Item>> = repository.getContent()
</code>```

```<code>// Repository
private val contentRepository = mutableListOf<Item>()
fun getContent() : LiveData<MutableList<Item>> {
  val data = MutableLiveData<MutableList<Item>>()
  data.value = contentRepository
  return data
}
.
.
.

</code>```

Now, both viewModels are making changes on the repository that keeps a MutableList. I would like to know if it is possible to observe the changes on the repository that is done by the other viewModel. If so, how?

To be more clear, I want viewModelA to know when viewModelB modifies the list in repository. Can viewModelA observe data in repository so that when viewModelB modifies it, it propagates to viewModelA as well?

I would rather not use a shared viewModel. I would also prefer to solve it with observing LiveData rather than using interfaces

Thank you

答:
```<code>// Repository
private val contentRepository = MutableLiveData<List<Item>>(Collections.emptyList())
fun getContent() : LiveData<List<Item>> = contentRepository

fun addContent(item: Item) {
    val list = ArrayList(contentRepository.value!!)
    list.add(item)
    contentRepository.value = Collections.unmodifiableList(list)
}

fun setContent(items: List<Item>) {
    contentRepository.value = Collections.unmodifiableList(ArrayList(items))
}
</code>```

And

```<code>val cartContent: LiveData<List<Item>> = repository.getContent()
</code>```

And

```<code>import androidx.lifecycle.observe

//FragmentA Observes viewModelA
viewModelA.cartContent.observe(viewLifecycleOwner) { content ->

}
</code>```

Body:
I have a question regarding MVVM pattern with Repository.

I have an activity that hosts 2 fragments. Let's call them FragmentA and FragmentB.

These 2 fragments have their own viewModels like viewModelA and viewModelB.

I also have a repository class that serves only local data. No network request. Just a MutableList.

FragmentA and FragmentB observe their respective viewModel through LiveData.

//FragmentA Observes viewModelA
viewModelA.cartContent.observe(viewLifecycleOwner, Observer { content ->

})

// ViewModelA exposes cartContent
val cartContent: LiveData<MutableList<Item>> = repository.getContent()

// Repository
private val contentRepository = mutableListOf<Item>()
fun getContent() : LiveData<MutableList<Item>> {
  val data = MutableLiveData<MutableList<Item>>()
  data.value = contentRepository
  return data
}
.
.
.

Now, both viewModels are making changes on the repository that keeps a MutableList. I would like to know if it is possible to observe the changes on the repository that is done by the other viewModel. If so, how?

To be more clear, I want viewModelA to know when viewModelB modifies the list in repository. Can viewModelA observe data in repository so that when viewModelB modifies it, it propagates to viewModelA as well?

I would rather not use a shared viewModel. I would also prefer to solve it with observing LiveData rather than using interfaces

Thank you

Body:
// Repository
private val contentRepository = MutableLiveData<List<Item>>(Collections.emptyList())
fun getContent() : LiveData<List<Item>> = contentRepository

fun addContent(item: Item) {
    val list = ArrayList(contentRepository.value!!)
    list.add(item)
    contentRepository.value = Collections.unmodifiableList(list)
}

fun setContent(items: List<Item>) {
    contentRepository.value = Collections.unmodifiableList(ArrayList(items))
}

And

val cartContent: LiveData<List<Item>> = repository.getContent()

And

import androidx.lifecycle.observe

//FragmentA Observes viewModelA
viewModelA.cartContent.observe(viewLifecycleOwner) { content ->

}


问:
How can I solve keyerror
I'm studying the object detection in colab.
I got the code from GitHub.
Here a link https://medium.com/@moshe.livne/training-tensorflow-for-free-pet-object-detection-api-sample-trained-on-google-collab-c2e65f4a9949

When I use create_pet_tf_record.py, there is an error.
It's KeyError.
I just have a class, and it is not same category.
Now, my class is Shin, but KeyError is 'drop'.
Actually, I used 'drop' category long time ago.

Can you solve these error

Code is running on the google colab.
my class is just one which is 'Shin'
I modified these code and I confirmed to run code for other images.

This is the code can create the tfrecord file.

```<code>%cd ~/datalab

!python ~/models/research/object_detection/dataset_tools/create_pet_tf_record.py --label_map_path=label_map.pbtxt --data_dir=. --output_dir=. --num_shards=1
</code>```

This  is my error

```<code>/root/datalab
WARNING: Logging before flag parsing goes to stderr.
W0615 10:23:11.859250 139781813761920 deprecation_wrapper.py:119] From /root/models/research/object_detection/dataset_tools/create_pet_tf_record.py:318: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.

W0615 10:23:11.859874 139781813761920 deprecation_wrapper.py:119] From /usr/local/lib/python2.7/dist-packages/object_detection-0.1-py2.7.egg/object_detection/utils/label_map_util.py:132: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.

I0615 10:23:11.861181 139781813761920 create_pet_tf_record.py:273] Reading from Pet dataset.
I0615 10:23:11.861639 139781813761920 create_pet_tf_record.py:288] 21 training and 9 validation examples.
W0615 10:23:11.861834 139781813761920 deprecation_wrapper.py:119] From /usr/local/lib/python2.7/dist-packages/object_detection-0.1-py2.7.egg/object_detection/dataset_tools/tf_record_creation_util.py:43: The name tf.python_io.TFRecordWriter is deprecated. Please use tf.io.TFRecordWriter instead.

I0615 10:23:11.862046 139781813761920 create_pet_tf_record.py:241] On image 0 of 21
/usr/local/lib/python2.7/dist-packages/object_detection-0.1-py2.7.egg/object_detection/utils/dataset_util.py:75: FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead.
  if not xml:
Traceback (most recent call last):
  File "/root/models/research/object_detection/dataset_tools/create_pet_tf_record.py", line 318, in <module>
    tf.app.run()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 40, in run
    _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)
  File "/usr/local/lib/python2.7/dist-packages/absl/app.py", line 300, in run
    _run_main(main, args)
  File "/usr/local/lib/python2.7/dist-packages/absl/app.py", line 251, in _run_main
    sys.exit(main(argv))
  File "/root/models/research/object_detection/dataset_tools/create_pet_tf_record.py", line 305, in main
    mask_type=FLAGS.mask_type)
  File "/root/models/research/object_detection/dataset_tools/create_pet_tf_record.py", line 260, in create_tf_record
    mask_type=mask_type)
  File "/root/models/research/object_detection/dataset_tools/create_pet_tf_record.py", line 167, in dict_to_tf_example
    classes.append(label_map_dict[class_name])
KeyError: 'drop'
</code>```

I have checked my label_map. I can see just one class 'Shin'

Can you know how I can solve it?

答:
That's an undefined class, you must to change from:

```<code>    classes.append(label_map_dict[class_name])
</code>```

of File "/root/models/research/object_detection/dataset_tools/create_pet_tf_record.py"
to:

```<code>    classes.append(label_map_dict[x])
</code>```

being x the number of the file.pbtxt's class (in this case: 'drop').
except you were using that code for more than 1 class it will solve the problem.
I expect that it work, good lake.

Title: How can I solve keyerror

Body:
I'm studying the object detection in colab.
I got the code from GitHub.
Here a link https://medium.com/@moshe.livne/training-tensorflow-for-free-pet-object-detection-api-sample-trained-on-google-collab-c2e65f4a9949

When I use create_pet_tf_record.py, there is an error.
It's KeyError.
I just have a class, and it is not same category.
Now, my class is Shin, but KeyError is 'drop'.
Actually, I used 'drop' category long time ago.

Can you solve these error

Code is running on the google colab.
my class is just one which is 'Shin'
I modified these code and I confirmed to run code for other images.

This is the code can create the tfrecord file.

%cd ~/datalab

!python ~/models/research/object_detection/dataset_tools/create_pet_tf_record.py --label_map_path=label_map.pbtxt --data_dir=. --output_dir=. --num_shards=1

This  is my error

/root/datalab
WARNING: Logging before flag parsing goes to stderr.
W0615 10:23:11.859250 139781813761920 deprecation_wrapper.py:119] From /root/models/research/object_detection/dataset_tools/create_pet_tf_record.py:318: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.

W0615 10:23:11.859874 139781813761920 deprecation_wrapper.py:119] From /usr/local/lib/python2.7/dist-packages/object_detection-0.1-py2.7.egg/object_detection/utils/label_map_util.py:132: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.

I0615 10:23:11.861181 139781813761920 create_pet_tf_record.py:273] Reading from Pet dataset.
I0615 10:23:11.861639 139781813761920 create_pet_tf_record.py:288] 21 training and 9 validation examples.
W0615 10:23:11.861834 139781813761920 deprecation_wrapper.py:119] From /usr/local/lib/python2.7/dist-packages/object_detection-0.1-py2.7.egg/object_detection/dataset_tools/tf_record_creation_util.py:43: The name tf.python_io.TFRecordWriter is deprecated. Please use tf.io.TFRecordWriter instead.

I0615 10:23:11.862046 139781813761920 create_pet_tf_record.py:241] On image 0 of 21
/usr/local/lib/python2.7/dist-packages/object_detection-0.1-py2.7.egg/object_detection/utils/dataset_util.py:75: FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead.
  if not xml:
Traceback (most recent call last):
  File "/root/models/research/object_detection/dataset_tools/create_pet_tf_record.py", line 318, in <module>
    tf.app.run()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 40, in run
    _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)
  File "/usr/local/lib/python2.7/dist-packages/absl/app.py", line 300, in run
    _run_main(main, args)
  File "/usr/local/lib/python2.7/dist-packages/absl/app.py", line 251, in _run_main
    sys.exit(main(argv))
  File "/root/models/research/object_detection/dataset_tools/create_pet_tf_record.py", line 305, in main
    mask_type=FLAGS.mask_type)
  File "/root/models/research/object_detection/dataset_tools/create_pet_tf_record.py", line 260, in create_tf_record
    mask_type=mask_type)
  File "/root/models/research/object_detection/dataset_tools/create_pet_tf_record.py", line 167, in dict_to_tf_example
    classes.append(label_map_dict[class_name])
KeyError: 'drop'

I have checked my label_map. I can see just one class 'Shin'

Can you know how I can solve it?

Body:
That's an undefined class, you must to change from:

    classes.append(label_map_dict[class_name])

of File "/root/models/research/object_detection/dataset_tools/create_pet_tf_record.py"
to:

    classes.append(label_map_dict[x])

being x the number of the file.pbtxt's class (in this case: 'drop').
except you were using that code for more than 1 class it will solve the problem.
I expect that it work, good lake.


问:
Disable dragging of image in entire project HTML pages
I want to disable dragging of all the images in my project which has a large amount of images. The results that I found on web was to disable a particular image. Putting draggable="false" inside every image tag would take a lot of time. So I want a solution to disable them together.

I was successful to disable dragging with this code but it's still draggable in Firefox .

```<code>img {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-user-drag: none;
  user-drag: none;
  -webkit-touch-callout: none;
}
</code>```

I've already gone through Disable dragging an image from an HTML page but found no answer to my question.

答:
For specific image you can do something like this, it will work on all browsers

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

<p>If you want all of your images non draggable in all browsers including <code>firefox</code> then few lines of javascript can do that for you!</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// register onLoad event with anonymous function
window.onload = function(e) {
  var evt = e || window.event, // define event (cross browser)
    imgs, // images collection
    i; // used in local loop
  // if preventDefault exists, then define onmousedown event handlers
  if (evt.preventDefault) {
    // collect all images on the page
    imgs = document.getElementsByTagName('img');
    // loop through fetched images
    for (i = 0; i < imgs.length; i++) {
      // and define onmousedown event handler
      imgs[i].onmousedown = disableDragging;
    }
  }
};

// disable image dragging
function disableDragging(e) {
  e.preventDefault();
}</code>```

```

Body:
I want to disable dragging of all the images in my project which has a large amount of images. The results that I found on web was to disable a particular image. Putting draggable="false" inside every image tag would take a lot of time. So I want a solution to disable them together.

I was successful to disable dragging with this code but it's still draggable in Firefox .

img {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-user-drag: none;
  user-drag: none;
  -webkit-touch-callout: none;
}

I've already gone through Disable dragging an image from an HTML page but found no answer to my question.

Body:
For specific image you can do something like this, it will work on all browsers

<!-- right image (dragging disabled) -->
<img src="https://contribute.geeksforgeeks.org/wp-content/uploads/gfg-39.png" onmousedown="if (event.preventDefault) event.preventDefault()">

If you want all of your images non draggable in all browsers including firefox then few lines of javascript can do that for you!

// register onLoad event with anonymous function
window.onload = function(e) {
  var evt = e || window.event, // define event (cross browser)
    imgs, // images collection
    i; // used in local loop
  // if preventDefault exists, then define onmousedown event handlers
  if (evt.preventDefault) {
    // collect all images on the page
    imgs = document.getElementsByTagName('img');
    // loop through fetched images
    for (i = 0; i < imgs.length; i++) {
      // and define onmousedown event handler
      imgs[i].onmousedown = disableDragging;
    }
  }
};

// disable image dragging
function disableDragging(e) {
  e.preventDefault();
}

<img src="https://contribute.geeksforgeeks.org/wp-content/uploads/gfg-39.png">

<img src="https://contribute.geeksforgeeks.org/wp-content/uploads/gfg-39.png">

<img src="https://contribute.geeksforgeeks.org/wp-content/uploads/gfg-39.png">


问:
How to use Master page in Electron Js Project
I am creating a ElectronJs Project.

Here i want to create a master page where i can store header navigation and footer.

I have created a base.html file. Now i want all code of base.html in every page.

In PHP we can do with

include 'base.php';

I want to do just like that in ElectronJs.

答:
Use one of the following JS web Frameworks and it will solve your problem
it provide the dynamic components

EJS EJS provide same as php include function

Angular Use angular selector to include headers,footers etc like below

<app-header></app-header>

React JS

VUE JS

let me know if its not clear , comment in commenbox i will explain.


问:
jQuery get relative click coords on an image in its actual dimensions
I have an image in my DOM and I want to get the mouse click coords relative to the image in its natural width and height not the one that fits the container. For example, when the mouse clicks on the image it gives back coords (50, 50) which are the actual click coords on the image in its actual dimensions.

Any idea how to attain this?

答:
After some scribbling here's how I solved it.

```<code>    $("#img-container img").click((e) => {
    // image reference
    const img = $("#img-container img");

    // consider scrolled page amount for later calcualtions
    const scrollTop = $("body").scrollTop();
    const scrollLeft = $("body").scrollLeft();

    // calculate click x, y coords
    let x = e.pageX + scrollLeft - e.target.offsetLeft;
    let y = e.pageY + scrollTop - e.target.offsetTop;

    // get original image dimensions
    const originalWidth = e.target.naturalWidth;
    const originalHeight = e.target.naturalHeight;

    // calcualte the difference in dimensions with current image
    const deltaWidth = originalWidth / img.width();
    const deltaHeight = originalHeight / img.height();

    // multiply the difference with x,y coords
    x = Math.round(x * deltaWidth);
    y = Math.round(y * deltaHeight);

    console.log(x, y);

  });
</code>```

thanks for everyone's help

Body:
After some scribbling here's how I solved it.

    $("#img-container img").click((e) => {
    // image reference
    const img = $("#img-container img");

    // consider scrolled page amount for later calcualtions
    const scrollTop = $("body").scrollTop();
    const scrollLeft = $("body").scrollLeft();

    // calculate click x, y coords
    let x = e.pageX + scrollLeft - e.target.offsetLeft;
    let y = e.pageY + scrollTop - e.target.offsetTop;

    // get original image dimensions
    const originalWidth = e.target.naturalWidth;
    const originalHeight = e.target.naturalHeight;

    // calcualte the difference in dimensions with current image
    const deltaWidth = originalWidth / img.width();
    const deltaHeight = originalHeight / img.height();

    // multiply the difference with x,y coords
    x = Math.round(x * deltaWidth);
    y = Math.round(y * deltaHeight);

    console.log(x, y);

  });

thanks for everyone's help


问:
Logout of Facebook (using PHP SDK) and CodeIgniter
Before I started implementing Facebook authentication, my logout controller looked like this:

```<code># Kill the session
$this->session->sess_destroy();

# Redirect back to main page.
redirect('', 'location');
</code>```

I tried modifying it to log the user out of Facebook as well, but no luck.

```<code># Kill the session
$this->session->sess_destroy();

require 'application/sdk/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '625256',
  'secret' => '25256256',
  'cookie' => true,
));

$session = $facebook->getSession();

if ($session) {
    $location = (string) html_entity_decode($facebook->getLogoutUrl(array('next' => 'http://localhost:8888/taketocollege/')));
    header("Location: $location");
    exit();
}

# Redirect back to main page.
redirect('', 'location');
</code>```

What am I doing wrong? I'm not looking to use the Javascript SDK for this since I want it all to be done in the controller.

Thanks!!

EDIT: To be a bit more clear, the problem is that the session isn't being destroyed. My logout controller sends users to the home page, but the home page redirects Facebook users with a session to the login page. So the Facebook users end up on the login page. Normally the login page would automatically log them in, but, by then, their session is destroyed.

答:
My code initially redirected users to the home page.

```<code>$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

if($session && !$this->session->userdata('logged_in'))
    redirect('login');
</code>```

That code was redirecting users to the login page since the session had been changed, not completely erased.

By changing the last two lines, I was able to fix this problem:

```<code>if($me && !$this->session->userdata('logged_in'))
    redirect('login');
</code>```

Hope it helps someone!

Body:
Before I started implementing Facebook authentication, my logout controller looked like this:

# Kill the session
$this->session->sess_destroy();

# Redirect back to main page.
redirect('', 'location');

I tried modifying it to log the user out of Facebook as well, but no luck.

# Kill the session
$this->session->sess_destroy();

require 'application/sdk/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '625256',
  'secret' => '25256256',
  'cookie' => true,
));

$session = $facebook->getSession();

if ($session) {
    $location = (string) html_entity_decode($facebook->getLogoutUrl(array('next' => 'http://localhost:8888/taketocollege/')));
    header("Location: $location");
    exit();
}

# Redirect back to main page.
redirect('', 'location');

What am I doing wrong? I'm not looking to use the Javascript SDK for this since I want it all to be done in the controller.

Thanks!!

EDIT: To be a bit more clear, the problem is that the session isn't being destroyed. My logout controller sends users to the home page, but the home page redirects Facebook users with a session to the login page. So the Facebook users end up on the login page. Normally the login page would automatically log them in, but, by then, their session is destroyed.

Body:
My code initially redirected users to the home page.

$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

if($session && !$this->session->userdata('logged_in'))
    redirect('login');

That code was redirecting users to the login page since the session had been changed, not completely erased.

By changing the last two lines, I was able to fix this problem:

if($me && !$this->session->userdata('logged_in'))
    redirect('login');

Hope it helps someone!