问:
Using custom Tags for Tagged Documents in Gensim
I am building a Document Vector in Gensim.

I have a custom list of tags (called url) I want to use for the TaggedDocument:

```<code>documents = [[TaggedDocument(doc, str(ur)) for ur in url] for doc in space]
</code>```

Every custom url is a sequence of 10 numbers.

The result looks like this:

```<code>[TaggedDocument(words=['googl', 'ibm', 'quantenrechnpentium', 'fdiv', 'bug', 'vierteljahrhundert',
'intel', 'geld', 'technikquantencomput', 'computibm', 'googl', 'beweis',
'quantum', 'supremacyforsch', 'natursycamor', 'qubit', 'groessenordn', 'supercomput', 'bauartibm',
'algorithmus', 'rechn', 'quant', 'quantenrechn', 'werkzeug', 'rechenfehl', 'intel', 'erfahr',
'professor', 'drthomas', 'fdiv', 'bug', 'intel', 'pentium', 'intel', 'fehl', 'austauschprogramm',
'intel', 'sorgdesktop', 'pc', 'prozessor', 'ghz', 'cor', 'fertigungstechn', 'stromauflag', 'pc',
'bauvorschlaeg', 'amd', 'ryzdesktop', 'schwaech', 'intel', 'geldquartal', 'rekordumsatz',
'milliard', 'dollarmilliard', 'preis', 'geld', 'fertigungsanlag', 'servermarkt', 'ausblick', 'amd',
'umsatz', 'jahresvergleich', 'anleg', 'ryz', 'epycs', 'ausblick', 'amd', 'erfolgmicrosoft', 'ryz',
'kund', 'surfac', 'notebook', 'gruend', 'journalist', 'surfac', 'testgeraet', 'ryz', 'ryz',
'vergleich', 'intel', 'cor', 'processor', 'conferenc', 'intel', 'atomkern', 'tremont',
'mikroarchitektur', 'atom', 'prozessor', 'nanomet', 'fertigelkhart', 'lak', 'embedded', 'systemiot',
'devic', 'skyhawk', 'lak', 'chips', 'nasatom', 'celeron', 'pentium', 'silv', 'tremont', 'goldmont',
'plusceleron', 'tremont', 'cor', 'kern', 'lakefield', 'microsoft', 'surfac', 'neo', 'kombination',
'cor', 'tremont', 'intel', 'atom', 'kern', 'cach', 'serv', 'tremont', 'risc', 'spezialist', 'sifiv',
'kern', 'aussichtnanomet', 'chipsarm', 'cortex', 'raspberry', 'pi', 'rechenpowspannend', 'erweiter',
'sichsogenannt', 'world', 'ids', 'trennung', 'welt', 'risc', 'socsprozess', 'cpu', 'kerncach',
'zeil', 'ram', 'adressbereich', 'world', 'id', 'sicherheitslueck', 'spectr', 'art', 'schreck',
'prozessor', 'markt', 'microsoft', 'sich', 'business', 'notebook', 'sogenannt', 'secured', 'cor',
'pcs', 'massnahmstart', 'betriebssystem', 'notebook', 'bios', 'bios', 'windows', 'updat', 'uefi',
'capsul', 'updattechnik', 'linuxsecured', 'cor', 'pcs', 'microsoft', 'angab', 'mobilrechn',
'business', 'version', 'surfacuefi', 'bios', 'kern', 'microsoft', 'rahm', 'project', 'artikel'], tags='4577911')
</code>```

As you can see at end is the field tags with my custom number.

After training the model with:

```<code>model = Doc2Vec(docu, vector_size=5, window=2, min_count=2, dm =1)
</code>```

I am runnning a similarity query with unseen Test Documents:

```<code>rank = []
for line in test:
    tokens = line.split()

    new_vector = model.infer_vector(tokens)
    sims = model.docvecs.most_similar([new_vector])
    rank.append(sims)
</code>```

Which yields this for the first document:

```<code>[('8', 0.9214882850646973),('9', 0.919198751449585),
('0', 0.9049716591835022), ('1', 0.9047936797142029),
('6', 0.9028873443603516), ('2', 0.8913612365722656),
('3', 0.8857095837593079), ('7', 0.8747860789299011),
('5', 0.8512719869613647), ('4', 0.8370641469955444)]
</code>```

As you can see the tags at index 0 of every sublist are not custom tags but generic numbers.

What am I doing wrong here?

答:
The tags should be a list-of-tags, because Doc2Vec can learn more than one tag per TaggedDocument (though it's not necessarily a good idea).

By providing tags='4577911', because Python strings are also lists-of-characters, it's essentially the same as tags=['4', '5', '7', '7', '9', '1', '1'] – and the training is only ever showing the model 10 unique tags, one for each digit, repeated across all texts.

Supply tags=['4577911'] instead & it should work as expected.

Body:
I am building a Document Vector in Gensim.

I have a custom list of tags (called url) I want to use for the TaggedDocument:

documents = [[TaggedDocument(doc, str(ur)) for ur in url] for doc in space]

Every custom url is a sequence of 10 numbers.

The result looks like this:

[TaggedDocument(words=['googl', 'ibm', 'quantenrechnpentium', 'fdiv', 'bug', 'vierteljahrhundert',
'intel', 'geld', 'technikquantencomput', 'computibm', 'googl', 'beweis',
'quantum', 'supremacyforsch', 'natursycamor', 'qubit', 'groessenordn', 'supercomput', 'bauartibm',
'algorithmus', 'rechn', 'quant', 'quantenrechn', 'werkzeug', 'rechenfehl', 'intel', 'erfahr',
'professor', 'drthomas', 'fdiv', 'bug', 'intel', 'pentium', 'intel', 'fehl', 'austauschprogramm',
'intel', 'sorgdesktop', 'pc', 'prozessor', 'ghz', 'cor', 'fertigungstechn', 'stromauflag', 'pc',
'bauvorschlaeg', 'amd', 'ryzdesktop', 'schwaech', 'intel', 'geldquartal', 'rekordumsatz',
'milliard', 'dollarmilliard', 'preis', 'geld', 'fertigungsanlag', 'servermarkt', 'ausblick', 'amd',
'umsatz', 'jahresvergleich', 'anleg', 'ryz', 'epycs', 'ausblick', 'amd', 'erfolgmicrosoft', 'ryz',
'kund', 'surfac', 'notebook', 'gruend', 'journalist', 'surfac', 'testgeraet', 'ryz', 'ryz',
'vergleich', 'intel', 'cor', 'processor', 'conferenc', 'intel', 'atomkern', 'tremont',
'mikroarchitektur', 'atom', 'prozessor', 'nanomet', 'fertigelkhart', 'lak', 'embedded', 'systemiot',
'devic', 'skyhawk', 'lak', 'chips', 'nasatom', 'celeron', 'pentium', 'silv', 'tremont', 'goldmont',
'plusceleron', 'tremont', 'cor', 'kern', 'lakefield', 'microsoft', 'surfac', 'neo', 'kombination',
'cor', 'tremont', 'intel', 'atom', 'kern', 'cach', 'serv', 'tremont', 'risc', 'spezialist', 'sifiv',
'kern', 'aussichtnanomet', 'chipsarm', 'cortex', 'raspberry', 'pi', 'rechenpowspannend', 'erweiter',
'sichsogenannt', 'world', 'ids', 'trennung', 'welt', 'risc', 'socsprozess', 'cpu', 'kerncach',
'zeil', 'ram', 'adressbereich', 'world', 'id', 'sicherheitslueck', 'spectr', 'art', 'schreck',
'prozessor', 'markt', 'microsoft', 'sich', 'business', 'notebook', 'sogenannt', 'secured', 'cor',
'pcs', 'massnahmstart', 'betriebssystem', 'notebook', 'bios', 'bios', 'windows', 'updat', 'uefi',
'capsul', 'updattechnik', 'linuxsecured', 'cor', 'pcs', 'microsoft', 'angab', 'mobilrechn',
'business', 'version', 'surfacuefi', 'bios', 'kern', 'microsoft', 'rahm', 'project', 'artikel'], tags='4577911')

As you can see at end is the field tags with my custom number.

After training the model with:

model = Doc2Vec(docu, vector_size=5, window=2, min_count=2, dm =1)

I am runnning a similarity query with unseen Test Documents:

rank = []
for line in test:
    tokens = line.split()

    new_vector = model.infer_vector(tokens)
    sims = model.docvecs.most_similar([new_vector])
    rank.append(sims)

Which yields this for the first document:

[('8', 0.9214882850646973),('9', 0.919198751449585),
('0', 0.9049716591835022), ('1', 0.9047936797142029),
('6', 0.9028873443603516), ('2', 0.8913612365722656),
('3', 0.8857095837593079), ('7', 0.8747860789299011),
('5', 0.8512719869613647), ('4', 0.8370641469955444)]

As you can see the tags at index 0 of every sublist are not custom tags but generic numbers.

What am I doing wrong here?


来源: stackexchange

问:
How to set responsive images with CKEditor 5?
Using the Simple Upload Adapter, according to the CKEditor 5 documentation upon a successful image upload, the server should return either:

This for a single image:

```<code>{
    default: 'http://example.com/images/image–default-size.png'
}
</code>```

Or this for multiple (i.e. for the srcset attribute)

```<code>{
    default: 'http://example.com/images/image–default-size.png',
    '160': 'http://example.com/images/image–size-160.image.png',
    '500': 'http://example.com/images/image–size-500.image.png',
    '1000': 'http://example.com/images/image–size-1000.image.png',
    '1052': 'http://example.com/images/image–default-size.png'
}
</code>```

For starters the documentation is incorrect as per this SO post, so I'm not surprised this doesn't work. But does anyone know what response format CKEditor 5 is expecting for it to correctly insert/build the srcset attribute? It does take the default key but seems to ignore the others!

答:
Inside of the _initListeners function of the upload adapter you will find that the Promise only resolves with the following:

resolve( {
    default: response.url
} );
```

<p>The solution - change the Promise to resolve the following:</p>

<pre class="lang-js prettyprint-override"><code>resolve( response.urls );
</code>```

Note, in this example the response object may have either keys url or urls.

I ended up using the following as I ignore null keys in my server responses.

if ( response.hasOwnProperty( 'url' ) ) {
    resolve( {
        default: response.url
    } );
} else if ( response.hasOwnProperty( 'urls' ) ) {
    resolve( response.urls );
}
```

<hr>

<p>As a sidenote, if you've read through the other SO post I referred to, I would also recommend removing this (see commented section):</p>

<pre class="lang-js prettyprint-override"><code>if ( !response /** || !response.uploaded */ ) {
    return reject( response && response.error && response.error.message ? response.error.message : genericError );
}
</code>```

I'm not a fan of using arbitrary flags in response, if the upload failed then I would rather see a HTTP status code indicating it, I can't see any reason why we need to return 200 and { "uploaded" : false }

ContentLicense: CC BY-SA 4.0

Body:
Using the Simple Upload Adapter, according to the CKEditor 5 documentation upon a successful image upload, the server should return either:

This for a single image:

{
    default: 'http://example.com/images/image–default-size.png'
}

Or this for multiple (i.e. for the srcset attribute)

{
    default: 'http://example.com/images/image–default-size.png',
    '160': 'http://example.com/images/image–size-160.image.png',
    '500': 'http://example.com/images/image–size-500.image.png',
    '1000': 'http://example.com/images/image–size-1000.image.png',
    '1052': 'http://example.com/images/image–default-size.png'
}

For starters the documentation is incorrect as per this SO post, so I'm not surprised this doesn't work. But does anyone know what response format CKEditor 5 is expecting for it to correctly insert/build the srcset attribute? It does take the default key but seems to ignore the others!

Body:
Inside of the _initListeners function of the upload adapter you will find that the Promise only resolves with the following:

resolve( {
    default: response.url
} );

The solution - change the Promise to resolve the following:

resolve( response.urls );

Note, in this example the response object may have either keys url or urls.

I ended up using the following as I ignore null keys in my server responses.

if ( response.hasOwnProperty( 'url' ) ) {
    resolve( {
        default: response.url
    } );
} else if ( response.hasOwnProperty( 'urls' ) ) {
    resolve( response.urls );
}

As a sidenote, if you've read through the other SO post I referred to, I would also recommend removing this (see commented section):

if ( !response /** || !response.uploaded */ ) {
    return reject( response && response.error && response.error.message ? response.error.message : genericError );
}

I'm not a fan of using arbitrary flags in response, if the upload failed then I would rather see a HTTP status code indicating it, I can't see any reason why we need to return 200 and { "uploaded" : false }


问:
Is there a way to convert a string (format: "1,5,20,22") to an array of integers ( [1,5, 20, 22] ) during MongoDB aggregation?
I have been working with MongoDB (and Metabase). Metabase way of searching is based on Mongo aggregation pipelines.

For people that don't know, Metabase allows us to create charts, and you can define filters for those charts, and use those filters on your Mongo query.

Anyway, the only filter types I can have are: String, Number and Date.

But, I have a query, that I need to check if a field value is $in some array.

So, I am not able to send an array as a filter.
Single number wouldn't work.

My idea was to pass a String (format: "1,3,5,20"), then transform this string in an array of numbers.

Is there a simple way to do this in a single "shot" on Mongo Aggregation?
I am trying to not rely on multiple pipeline stages

I know I can use split to generate my array, but from there, I would need to transform all values on my new array of string in integer values.

Any idea?

答:
You should be able to use $map, perhaps:

```<code>{$project:{
   arrayField: {$map: {
      input: {$split: ["$stringField",","]},
      as: "elem",
      in: {$toInt: "$$elem"}
   }}
}}
</code>```

Playground

Body:
You should be able to use $map, perhaps:

{$project:{
   arrayField: {$map: {
      input: {$split: ["$stringField",","]},
      as: "elem",
      in: {$toInt: "$$elem"}
   }}
}}

Playground


问:
Azure Portal add a user who can create web apps, sql server and other resources
What is the correct way to add a user who can create web apps, sql servers, and other resources in an Azure Portal without making them subscription administrators?

Do you just invite them as a user in the AD section and give them roles? and which roles, it looks like Application Administrator and Cloud application administrator?

答:
Yes, the user has to be invited / part of the Azure AD that is linked to your subscription. Then, you can grant him access at a subscription or resource group level.

The right you are looking for is called contributor:

Can create and manage all types of Azure resources but can’t grant
  access to others.

Further reading:
What is role-based access control (RBAC) for Azure resources


问:
The type or namespace EventProcessorClient could not be found
I am starting off with Event Hubs with .Net Core and am facing a very peculiar issue when trying to write the same code as in the official MS documentation(https://learn.microsoft.com/en-us/azure/event-hubs/get-started-dotnet-standard-send-v2). The event receiver code throws an error although I'm using it's containing namespace i.e. Azure.Messaging.EventHubs. Where am I going wrong here?

答: Make sure you have imported the correct Nuget package as below.


问:
PYTHON installed on PC, (have PYTHON ICON) no LINUX: how do I compile my 1st program?
Just getting started using PYTHON.
I am not working AT THE COMMAND LINE  (not on UNIX,  not on LINUX).
I have a DESKTOP folder with   prog1.py
and from the PC --> START  -->  I get to the  PYTHON  ICON.
How do I use this "PC environment / non-unix command line" to compile and run ?
Thank you - - -  Cesar

Here is what is installed.
 PYTHON 3.8 (64-bit)
 -AND-  IDLE PYTHON 3.8
 -AND-  MANUALS

I typed my first program prog1.py and it is on the PC DESKTOP

Which ICON do I choose to compile and run prog1.py

```<code># Program to add two numbers,  `prog1.py`
num1 = 15
num2 = 12

# Adding two nos
sum = num1 + num2

# Printing values
print("Sum of {0} and {1} is {2}" .format(num1, num2, sum))
</code>```

答:
If python is in your PATH, you can go on your terminal, cd into your prog1.py folder and type: </p>

```<code>python prog1.py
</code>```

<p>If python is not on your PATH, you will have to type the full path to python: </p>

```<code>{path_to_python} prog1.py
</code>```

Body:
Just getting started using PYTHON.
I am not working AT THE COMMAND LINE  (not on UNIX,  not on LINUX).
I have a DESKTOP folder with   prog1.py
and from the PC --> START  -->  I get to the  PYTHON  ICON.
How do I use this "PC environment / non-unix command line" to compile and run ?
Thank you - - -  Cesar

Here is what is installed.
 PYTHON 3.8 (64-bit)
 -AND-  IDLE PYTHON 3.8
 -AND-  MANUALS

I typed my first program prog1.py and it is on the PC DESKTOP

Which ICON do I choose to compile and run prog1.py

# Program to add two numbers,  `prog1.py`
num1 = 15
num2 = 12

# Adding two nos
sum = num1 + num2

# Printing values
print("Sum of {0} and {1} is {2}" .format(num1, num2, sum))

Body:
If python is in your PATH, you can go on your terminal, cd into your prog1.py folder and type:

python prog1.py

If python is not on your PATH, you will have to type the full path to python:

{path_to_python} prog1.py


问:
Qml Locale has same format for ShortFormat and NarrowFormat
I'm trying to display the date (and time) using the toLocaleDateString / toLocateTimeString methods implemented on the Date type in Qml (doc here). It works, except for the ShortFormat which is the same as the NarrowFormat.

Here's an example:

```<code>import QtQuick 2.3

import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    property var locale: Qt.locale()

    Label {
        id: date
        text: {
            "DATE: \n" +
              "Locale.LongFormat:\t" + new Date().toLocaleDateString(locale, Locale.LongFormat) + "\n" +
              "Locale.ShortFormat:\t" + new Date().toLocaleDateString(locale, Locale.ShortFormat) + "\n" +
              "Locale.NarrowFormat:\t" + new Date().toLocaleDateString(locale, Locale.NarrowFormat) + "\n"
        }
        anchors.top : parent
    }

    Label {
        id: time
        text:
            "TIME: \n" +
              "Locale.LongFormat:\t" + new Date().toLocaleTimeString(locale, Locale.LongFormat) + "\n" +
              "Locale.ShortFormat:\t" + new Date().toLocaleTimeString(locale, Locale.ShortFormat) + "\n" +
              "Locale.NarrowFormat:\t" + new Date().toLocaleTimeString(locale, Locale.NarrowFormat) + "\n"

        anchors.top: date.bottom
    }

}
</code>```

What's displayed:

```<code>Locale.LongFormat:  Wednesday, September 27, 2017
Locale.ShortFormat: 9/27/17
Locale.NarrowFormat:    9/27/17

Locale.LongFormat:  11:46:10 AM CEST
Locale.ShortFormat: 11:46 AM
Locale.NarrowFormat:    11:46 AM
</code>```

I was expecting the ShotFormat to give me the date as Sept 27th 2017 or something similar, and the time as 11:46:42 AM.

I found in the doc (here), about the NarrowFormat, that

Also, for the system locale this format is the same as ShortFormat.

I'm not sure if this is related to my issue, since I'm explicitly giving the locale in the toLocaleDateMethod. Even then, the NarrowFormat should then be more verbose, instead of the ShortFormat being shorter...

Thanks for your help !

答:
In Qml Documentation:

Locale.ShortFormat is the default and recommended format, as Locale.NarrowFormat may not be fully supported by each locale (see Locale String Format Types) and Locale.LongFormat may not fit within the header cells.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to display the date (and time) using the toLocaleDateString / toLocateTimeString methods implemented on the Date type in Qml (doc here). It works, except for the ShortFormat which is the same as the NarrowFormat.

Here's an example:

import QtQuick 2.3

import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    property var locale: Qt.locale()

    Label {
        id: date
        text: {
            "DATE: \n" +
              "Locale.LongFormat:\t" + new Date().toLocaleDateString(locale, Locale.LongFormat) + "\n" +
              "Locale.ShortFormat:\t" + new Date().toLocaleDateString(locale, Locale.ShortFormat) + "\n" +
              "Locale.NarrowFormat:\t" + new Date().toLocaleDateString(locale, Locale.NarrowFormat) + "\n"
        }
        anchors.top : parent
    }

    Label {
        id: time
        text:
            "TIME: \n" +
              "Locale.LongFormat:\t" + new Date().toLocaleTimeString(locale, Locale.LongFormat) + "\n" +
              "Locale.ShortFormat:\t" + new Date().toLocaleTimeString(locale, Locale.ShortFormat) + "\n" +
              "Locale.NarrowFormat:\t" + new Date().toLocaleTimeString(locale, Locale.NarrowFormat) + "\n"

        anchors.top: date.bottom
    }

}

What's displayed:

Locale.LongFormat:  Wednesday, September 27, 2017
Locale.ShortFormat: 9/27/17
Locale.NarrowFormat:    9/27/17

Locale.LongFormat:  11:46:10 AM CEST
Locale.ShortFormat: 11:46 AM
Locale.NarrowFormat:    11:46 AM

I was expecting the ShotFormat to give me the date as Sept 27th 2017 or something similar, and the time as 11:46:42 AM.

I found in the doc (here), about the NarrowFormat, that

Also, for the system locale this format is the same as ShortFormat.

I'm not sure if this is related to my issue, since I'm explicitly giving the locale in the toLocaleDateMethod. Even then, the NarrowFormat should then be more verbose, instead of the ShortFormat being shorter...

Thanks for your help !


问:
How to load a STL vector with a constant
If I have a vector<double> that has already been resized to be 1200, what is the best way to load that vector with the same value in each slot? The value is not known at compile time.

Right now I just use a loop through all 1200 slots and set each slot equal to the value. I was wondering if this was the best way to do this.

答:
You could use loop unrolling:

```<code>std::vector<double> my_vector(1200);
for (int i = 0; i < 300; i += 4)
{
    my_vector[i + 0] = value;
    my_vector[i + 1] = value;
    my_vector[i + 2] = value;
    my_vector[i + 3] = value;
}
</code>```

I suggest playing around with the number of assignments in the loop.  The idea here is to reduce the overhead of incrementing and branching (do more data operations).

Body:
You could use loop unrolling:

std::vector<double> my_vector(1200);
for (int i = 0; i < 300; i += 4)
{
    my_vector[i + 0] = value;
    my_vector[i + 1] = value;
    my_vector[i + 2] = value;
    my_vector[i + 3] = value;
}

I suggest playing around with the number of assignments in the loop.  The idea here is to reduce the overhead of incrementing and branching (do more data operations).


问:
Effective way to write function in BigQuery
I have a function, which i want to optimize:

```<code>CREATE OR REPLACE FUNCTION <project>.<dataset>.<function_name>( tv1 STRING, tv2 STRING) <br>
RETURNS STRING <br>
AS ( <br>
CASE
when lower(tv1) = 'val1' then '11' <br>
when lower(tv1) = 'val2' then 'ABC1' <br>
when lower(tv1) = 'val3' then 'XYZ5' <br>
when lower(tv2) = 'val4' then 'MyVal' <br>
when lower(tv2) = 'val5' then 'HisVal' <br>
else 'nothing' <br>
end <br>
); <br>
</code>```

Here, how i can avoid using the lower() in every sentence and do it once INSIDE the function itself. I don't want to call the lower function with the lower() call to it from outside. How can i make it inside the function itself ?

答:
Below is for BigQuery Standard SQL      </p>

```<code>CREATE TEMP FUNCTION test( tv1 STRING, tv2 STRING)
RETURNS STRING AS ((
  SELECT CASE
    WHEN tv1 = 'val1' THEN '11'
    WHEN tv1 = 'val2' THEN 'ABC1'
    WHEN tv1 = 'val3' THEN 'XYZ5'
    WHEN tv2 = 'val4' THEN 'MyVal'
    WHEN tv2 = 'val5' THEN 'HisVal'
    ELSE 'nothing'
  END
  FROM UNNEST([LOWER(tv1)]) tv1, UNNEST([LOWER(tv2)]) tv2
));
</code>```

<p>As you can see, it eliminates need in using LOWER in each and every "sentence", but still require using LOWER once for both tv1 and tv2   </p>

Body:
I have a function, which i want to optimize:

CREATE OR REPLACE FUNCTION <project>.<dataset>.<function_name>( tv1 STRING, tv2 STRING)

RETURNS STRING

AS (

CASE
when lower(tv1) = 'val1' then '11'

when lower(tv1) = 'val2' then 'ABC1'

when lower(tv1) = 'val3' then 'XYZ5'

when lower(tv2) = 'val4' then 'MyVal'

when lower(tv2) = 'val5' then 'HisVal'

else 'nothing'

end

);

Here, how i can avoid using the lower() in every sentence and do it once INSIDE the function itself. I don't want to call the lower function with the lower() call to it from outside. How can i make it inside the function itself ?

Body:
Below is for BigQuery Standard SQL

CREATE TEMP FUNCTION test( tv1 STRING, tv2 STRING)
RETURNS STRING AS ((
  SELECT CASE
    WHEN tv1 = 'val1' THEN '11'
    WHEN tv1 = 'val2' THEN 'ABC1'
    WHEN tv1 = 'val3' THEN 'XYZ5'
    WHEN tv2 = 'val4' THEN 'MyVal'
    WHEN tv2 = 'val5' THEN 'HisVal'
    ELSE 'nothing'
  END
  FROM UNNEST([LOWER(tv1)]) tv1, UNNEST([LOWER(tv2)]) tv2
));

As you can see, it eliminates need in using LOWER in each and every "sentence", but still require using LOWER once for both tv1 and tv2


问:
how to create a relocatable rpm package , no compile
I am trying to create a "relocatable RPM" of bunch of script and .png files. No build/compile. I wrote

```<code>
    Name:       utp
    Version:    1.0
    Release:    1%{?dist}
    Summary:    some summary

    Group:      Applications/Engineering
    License:    Proprietary
    URL:        http://www.example.com
    Source0:    %{name}-%{version}.tgz
    BuildArch:  noarch
    Prefix:     /opt

    %description
    A very nice description

    %prep
    echo "=== prep ... done"

    %setup -n utp
    echo "=== setup ... done"

    # %files -f %{_tmppath}/files.list
    %files

</code>```

and I get

```<code>
    medi@medi:~/work> rpm -qi -p rpmbuild/RPMS/noarch/utp-1.0-1.el8.noarch.rpm
    Name        : utp
    Version     : 1.0
    Release     : 1.el8
    Architecture: noarch
    Install Date: (not installed)
    Group       : Applications/Engineering
    Size        : 0
    License     : Proprietary
    Signature   : (none)
    Source RPM  : utp-1.0-1.el8.src.rpm
    Build Date  : Mon 17 Feb 2020 03:44:00 PM PST
    Build Host  : medi.example.com
    Relocations : /opt
    URL         : http://www.example.com
    Summary     : some summary
    Description :
    A very nice description
</code>```

and

```<code>    medi@medi:~/work> rpm -ql -p rpmbuild/RPMS/noarch/utp-1.0-1.el8.noarch.rpm
    (contains no files)
    medi@medi:~/work>
</code>```

Most likely the problem is with '%files'. I tried to specify a list (commented out now), but I ran into the following

```<code>    Processing files: utp-1.0-1.el8.noarch
    error: Directory not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp
    error: File not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp/utg
    error: File not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp/utg/UserGuide.txt

</code>```

where my file.list looks like

```<code>
    /opt/utp/
    /opt/utp/utg
    /opt/utp/utg/UserGuide.txt
    /opt/utp/utg/install.txt

</code>```

Since I want to make this a relocatable one (see Prefix: /opt), I prepended '/opt'.

I think overall, I am confused. Yes I did read the doc, but I am missing it.

答: Your %build and %install stanzas should still exist; one unpacks your source of images and the other copies them to the final locations within the buildroot.

Body:
I am trying to create a "relocatable RPM" of bunch of script and .png files. No build/compile. I wrote

    Name:       utp
    Version:    1.0
    Release:    1%{?dist}
    Summary:    some summary

    Group:      Applications/Engineering
    License:    Proprietary
    URL:        http://www.example.com
    Source0:    %{name}-%{version}.tgz
    BuildArch:  noarch
    Prefix:     /opt

    %description
    A very nice description

    %prep
    echo "=== prep ... done"

    %setup -n utp
    echo "=== setup ... done"

    # %files -f %{_tmppath}/files.list
    %files

and I get

    medi@medi:~/work> rpm -qi -p rpmbuild/RPMS/noarch/utp-1.0-1.el8.noarch.rpm
    Name        : utp
    Version     : 1.0
    Release     : 1.el8
    Architecture: noarch
    Install Date: (not installed)
    Group       : Applications/Engineering
    Size        : 0
    License     : Proprietary
    Signature   : (none)
    Source RPM  : utp-1.0-1.el8.src.rpm
    Build Date  : Mon 17 Feb 2020 03:44:00 PM PST
    Build Host  : medi.example.com
    Relocations : /opt
    URL         : http://www.example.com
    Summary     : some summary
    Description :
    A very nice description

and

    medi@medi:~/work> rpm -ql -p rpmbuild/RPMS/noarch/utp-1.0-1.el8.noarch.rpm
    (contains no files)
    medi@medi:~/work>

Most likely the problem is with '%files'. I tried to specify a list (commented out now), but I ran into the following

    Processing files: utp-1.0-1.el8.noarch
    error: Directory not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp
    error: File not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp/utg
    error: File not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp/utg/UserGuide.txt

where my file.list looks like

    /opt/utp/
    /opt/utp/utg
    /opt/utp/utg/UserGuide.txt
    /opt/utp/utg/install.txt

Since I want to make this a relocatable one (see Prefix: /opt), I prepended '/opt'.

I think overall, I am confused. Yes I did read the doc, but I am missing it.


问:
Finding All Positions for Multiple Elements in a Vector
Suppose I have the following vector:

```<code>x <- c(8, 6, 9, 9, 7, 3, 2, 5, 5, 1, 6, 8, 5, 2, 9, 3, 5, 10, 8, 2)
</code>```

How can I find which elements are either 8 or 9?

答:
Here is a generalized solution to find the locations of all target values (only works for vectors and 1-dimensional arrays).

```<code>locate <- function(x, targets) {
    results <- lapply(targets, function(target) which(x == target))
    names(results) <- targets
    results
}
</code>```

This function returns a list because each target may have any number of matches, including zero. The list is sorted (and named) in the original order of the targets.

Here is an example in use:

```<code>sequence <- c(1:10, 1:10)

locate(sequence, c(2,9))
$`2`
[1]  2 12

$`9`
[1]  9 19
</code>```

Body:
Suppose I have the following vector:

x <- c(8, 6, 9, 9, 7, 3, 2, 5, 5, 1, 6, 8, 5, 2, 9, 3, 5, 10, 8, 2)

How can I find which elements are either 8 or 9?

Body:
Here is a generalized solution to find the locations of all target values (only works for vectors and 1-dimensional arrays).

locate <- function(x, targets) {
    results <- lapply(targets, function(target) which(x == target))
    names(results) <- targets
    results
}

This function returns a list because each target may have any number of matches, including zero. The list is sorted (and named) in the original order of the targets.

Here is an example in use:

sequence <- c(1:10, 1:10)

locate(sequence, c(2,9))
$`2`
[1]  2 12

$`9`
[1]  9 19


问:
Alternative for JVM Flags of Java 8 in Java 11
I have been using the following flags in my application using Java 8:-

1) PrintFLSStatistics=1

2) +PrintPromotionFailure

3) -XX:+PrintGCDateStamps

4) -XX:+PrintGCDetails

I have been moving the application to use Java 11 instead of Java 8. It seems these flags are either deprecated or not supported in Java 11. Please tell the alternatives of these flags in Java 11.

Thanks for your time,

答:
In Java 11, you have to use -Xlog instead. For example: java -Xlog:gc\*::time -jar my.jar will log something like

```<code>[2020-02-19T18:32:50.107-0300] Heap region size: 1M
[2020-02-19T18:32:50.119-0300] Using G1
[2020-02-19T18:32:50.119-0300] Heap address: 0x000000070a200000, size: 3934 MB, Compressed Oops mode: Zero based, Oop shift amount: 3
</code>```

-Xlog is the general logging configuration option for logging in the HotSpot JVM. It's a tag-based system where gc is one of the tags. To
  get more information about what a GC is doing, you can configure
  logging to print any message that has the gc tag and any other tag.
  The command line option for this is -Xlog:gc*.

See:

https://docs.oracle.com/javase/9/tools/java.htm#GUID-BE93ABDC-999C-4CB5-A88B-1994AAAC74D5

https://docs.oracle.com/en/java/javase/11/gctuning/garbage-collector-implementation.html#GUID-A24775AB-16A3-4B86-9963-76E5AC398A3E

Body:
In Java 11, you have to use -Xlog instead. For example: java -Xlog:gc\*::time -jar my.jar will log something like

[2020-02-19T18:32:50.107-0300] Heap region size: 1M
[2020-02-19T18:32:50.119-0300] Using G1
[2020-02-19T18:32:50.119-0300] Heap address: 0x000000070a200000, size: 3934 MB, Compressed Oops mode: Zero based, Oop shift amount: 3

-Xlog is the general logging configuration option for logging in the HotSpot JVM. It's a tag-based system where gc is one of the tags. To
  get more information about what a GC is doing, you can configure
  logging to print any message that has the gc tag and any other tag.
  The command line option for this is -Xlog:gc*.

See:

https://docs.oracle.com/javase/9/tools/java.htm#GUID-BE93ABDC-999C-4CB5-A88B-1994AAAC74D5

https://docs.oracle.com/en/java/javase/11/gctuning/garbage-collector-implementation.html#GUID-A24775AB-16A3-4B86-9963-76E5AC398A3E


问:
Method should wait until window.open close
Am developing application in JSF. I have created t:commandlink that calls JavaScript method in onclick event, I have an action in same t:commandlink. That will trigger once onclick event complete. Before I used IE browser So, I used window.openmodaldialog('sample.xhtml', '_blank'); to open popup in javascript like below,

```<code><t:commandlink onclick="openPopup()" action="#{samplebean.savedata()}"></t:commandlink>
</code>```

Javascript code:

```<code>function openPopup(){
  window.showmodaldialog('sample.xhtml', '_blank');
  return true;
}
</code>```

In above code 'openPopup' method wait until showmodaldialog to close. Now am migrating application to Chrome browser. So, I used window.open since window.showmodaldialog is deprecated in Chrome. What am facing issue here is openPopup method not waiting until popup to close. It's getting executed and t:commandlink action block get called. How to make openPopup method to wait until popup close.

答: try to switch to oncomplete, instead of onclick

Body:
Am developing application in JSF. I have created t:commandlink that calls JavaScript method in onclick event, I have an action in same t:commandlink. That will trigger once onclick event complete. Before I used IE browser So, I used window.openmodaldialog('sample.xhtml', '_blank'); to open popup in javascript like below,

<t:commandlink onclick="openPopup()" action="#{samplebean.savedata()}"></t:commandlink>

Javascript code:

function openPopup(){
  window.showmodaldialog('sample.xhtml', '_blank');
  return true;
}

In above code 'openPopup' method wait until showmodaldialog to close. Now am migrating application to Chrome browser. So, I used window.open since window.showmodaldialog is deprecated in Chrome. What am facing issue here is openPopup method not waiting until popup to close. It's getting executed and t:commandlink action block get called. How to make openPopup method to wait until popup close.


问:
Is it possible make predicate from List?
I use SWI-Prolog

I have lists like this

```<code>[sunny,hot,high,weak,no]
</code>```

and

```<code>[outlook,temperature,humidity,wind,play_tennis]
</code>```

I want to make a predicate like

```<code>run(no,  [outlook=sunny,    temp=hot,  humidity=high,   wind=weak  ]).
</code>```

Is it possible?

答:
Yes, but you're going to have to implement the appropriate machine learning algorithm (your example looks identical to the ones found in Mitchell's machine learning book, is this a homework assignment?).

Note that you can use the =.. operator to turn a list into a predicate, which might help you if I've misunderstood your original question. In other words, A=..[a,b,c] binds a(b,c) to A

Body:
I use SWI-Prolog

I have lists like this

[sunny,hot,high,weak,no]

and

[outlook,temperature,humidity,wind,play_tennis]

I want to make a predicate like

run(no,  [outlook=sunny,    temp=hot,  humidity=high,   wind=weak  ]).

Is it possible?


问:
Yandex Mapkit iOS : animate placemark
I want to animate YMKPlacemarkMapObject when tapped. I tried, but not working.

```<code>    func onMapObjectTap(with mapObject: YMKMapObject, point: YMKPoint) -> Bool {

        guard let placemark = mapObject as? YMKPlacemarkMapObject else { return false }

        let iconStyle: YMKIconStyle = YMKIconStyle()

        UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: .curveEaseInOut, animations: {
            iconStyle.scale = 2
            placemark.setIconStyleWith(iconStyle)
        }) { _ in
            iconStyle.scale = 1
            placemark.setIconStyleWith(iconStyle)
        }
    }
</code>```

When using Google Maps, I can easily access markers imageView and transform it. For Yandex Maps I could not find a way to access placemarks imageView. Is there a way to access imageView?

答:
YMKPlacemarkMapObject does not support UIView animation, but you can animate any property of YMKPlacemarkMapObject manually using CADisplayLink for example.

I would like also suggest you to ask questions here. In this case it will be answered (by mapkit developers) faster.

Title: Yandex Mapkit iOS : animate placemark

Body:
I want to animate YMKPlacemarkMapObject when tapped. I tried, but not working.

    func onMapObjectTap(with mapObject: YMKMapObject, point: YMKPoint) -> Bool {

        guard let placemark = mapObject as? YMKPlacemarkMapObject else { return false }

        let iconStyle: YMKIconStyle = YMKIconStyle()

        UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: .curveEaseInOut, animations: {
            iconStyle.scale = 2
            placemark.setIconStyleWith(iconStyle)
        }) { _ in
            iconStyle.scale = 1
            placemark.setIconStyleWith(iconStyle)
        }
    }

When using Google Maps, I can easily access markers imageView and transform it. For Yandex Maps I could not find a way to access placemarks imageView. Is there a way to access imageView?


问:
Excluding intervals from a real number line
A long time ago I asked the following question:

Python: delete substring by indices

Last week I was asked a very similar question, but with continuous real-number line.

Imagine you are given an interval (X, Y), and a bunch of sub-intervals blocks=[(x1, y1), (x2, y2), ...]. Your goal is to find a list of intervals remaining=[(a1, b1), (a2, b2), ..] that is (1) in (X, Y), but (2) not in any of the sub-intervals in blocks. The intervals in blocks can overlap.

In other words, the function signature looks something like:

```<code>def delete_blocks_from_interval(X, Y, blocks):
    ```
    X: start of the given interval
    Y: end of the given interval
    blocks: list of intervals (x, y) to be removed, can overlap

    returns remaining = [(a, b), ...] intervals remaining after removal of blocks
    ```
    pass
</code>```

I can construct a graph of connected intervals in blocks, and find both the minimum of the start and the maximum of end for each connected component in the graph. But this is quadratic in length of blocks. I wonder if there is a better-runtime algorithm.

Please also discuss what code routine you think is more efficient for the algorithm if you will.

Many many thanks.

As requested, please consider the following illustrative inputs:

X = -1

Y = 20

blocks = [(1, 10), (4, 5), (9, 11), (16, 17.5)]

the expected output is remaining = [(-1, 1), (11, 16), (17.5, 20)]

答:
This should be linear run-time in number of blocks</p>

```<code>import bisect

def delete_blocks_from_interval(range_start, range_end, blocks):
    blocks = sorted(blocks)

    # check if the interval overlaps with blocks,
    # if so, truncate the block lists, reset end points if required
    start_idx = bisect.bisect_left([b[0] for b in blocks],range_start)
    end_idx = bisect.bisect_left([b[0] for b in blocks],range_end)
    blocks = blocks[start_idx:end_idx]
    if blocks[0][0] < range_start:
        blocks[0][0] = range_start
    if blocks[-1][1] > range_end:
        blocks[-1][1] = range_end

    # emit the first gap, if any
    if range_start < blocks[0][0]:
        yield (range_start, blocks[0][0])

    # loop through till the end of the blocks
    end = blocks[0][1]
    for block in blocks[1:]:
        if end < block[0]:
            yield (end, block[0])
            end = block[1]
        elif end < block[1]:
            end = block[1]

    # emit the last gap, if any
    if range_end > blocks[-1][1]:
        yield (blocks[-1][1], range_end)

blocks = [(1, 10), (4, 5), (9, 11), (16, 17.5)]
list(delete_blocks_from_interval(-1, 20, blocks))
</code>```

Body:
A long time ago I asked the following question:

Python: delete substring by indices

Last week I was asked a very similar question, but with continuous real-number line.

Imagine you are given an interval (X, Y), and a bunch of sub-intervals blocks=[(x1, y1), (x2, y2), ...]. Your goal is to find a list of intervals remaining=[(a1, b1), (a2, b2), ..] that is (1) in (X, Y), but (2) not in any of the sub-intervals in blocks. The intervals in blocks can overlap.

In other words, the function signature looks something like:

def delete_blocks_from_interval(X, Y, blocks):
    ```
    X: start of the given interval
    Y: end of the given interval
    blocks: list of intervals (x, y) to be removed, can overlap

    returns remaining = [(a, b), ...] intervals remaining after removal of blocks
    ```
    pass

I can construct a graph of connected intervals in blocks, and find both the minimum of the start and the maximum of end for each connected component in the graph. But this is quadratic in length of blocks. I wonder if there is a better-runtime algorithm.

Please also discuss what code routine you think is more efficient for the algorithm if you will.

Many many thanks.

As requested, please consider the following illustrative inputs:

X = -1

Y = 20

blocks = [(1, 10), (4, 5), (9, 11), (16, 17.5)]

the expected output is remaining = [(-1, 1), (11, 16), (17.5, 20)]

Body:
This should be linear run-time in number of blocks

import bisect

def delete_blocks_from_interval(range_start, range_end, blocks):
    blocks = sorted(blocks)

    # check if the interval overlaps with blocks,
    # if so, truncate the block lists, reset end points if required
    start_idx = bisect.bisect_left([b[0] for b in blocks],range_start)
    end_idx = bisect.bisect_left([b[0] for b in blocks],range_end)
    blocks = blocks[start_idx:end_idx]
    if blocks[0][0] < range_start:
        blocks[0][0] = range_start
    if blocks[-1][1] > range_end:
        blocks[-1][1] = range_end

    # emit the first gap, if any
    if range_start < blocks[0][0]:
        yield (range_start, blocks[0][0])

    # loop through till the end of the blocks
    end = blocks[0][1]
    for block in blocks[1:]:
        if end < block[0]:
            yield (end, block[0])
            end = block[1]
        elif end < block[1]:
            end = block[1]

    # emit the last gap, if any
    if range_end > blocks[-1][1]:
        yield (blocks[-1][1], range_end)

blocks = [(1, 10), (4, 5), (9, 11), (16, 17.5)]
list(delete_blocks_from_interval(-1, 20, blocks))


问:
How to run Python's subprocess and leave it in background
I have seen A LOT of posts regarding my topic, but actually I didn't find a solution for my problem.
I'm trying to run a subprocess in a background, without wait for subprocess execution. The called subprocess is a shell script, which does a lot of different things.
This is a small piece of my code:

```<code>print "Execute command:", full_command
subprocess.Popen(full_command, stdin=None, stdout=None, stderr=None, close_fds=True).communicate()
print "After subprocess"
</code>```

And my problem is that Python waits until subprocess.Popen finishes it's job. I read, that stdin(-out, -err)=None should solve this problem, but it's not. Also close_fds=True, doesn't help here.

答:
Might be another way of doing it, with the optional capability to inspect the subprocess output for a while, from github.com/hologram-io/hologram-python pppd.py file: </p>

```<code>    self.proc = Popen(self._commands, stdout=PIPE, stderr=STDOUT)

    # set stdout to non-blocking
    fd = self.proc.stdout.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
</code>```

Body:
I have seen A LOT of posts regarding my topic, but actually I didn't find a solution for my problem.
I'm trying to run a subprocess in a background, without wait for subprocess execution. The called subprocess is a shell script, which does a lot of different things.
This is a small piece of my code:

print "Execute command:", full_command
subprocess.Popen(full_command, stdin=None, stdout=None, stderr=None, close_fds=True).communicate()
print "After subprocess"

And my problem is that Python waits until subprocess.Popen finishes it's job. I read, that stdin(-out, -err)=None should solve this problem, but it's not. Also close_fds=True, doesn't help here.

Body:
Might be another way of doing it, with the optional capability to inspect the subprocess output for a while, from github.com/hologram-io/hologram-python pppd.py file:

    self.proc = Popen(self._commands, stdout=PIPE, stderr=STDOUT)

    # set stdout to non-blocking
    fd = self.proc.stdout.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)


问:
Is fsbolero's runner, `bolero-live`, open source and if so, where is the source?
I've been having a problem getting a modified bolero app to perform HotReload. The problem appears to be in bolero-live as indicated by this top portion of the error log (line break inserted for convenience). However, the source code for bolero-live does not appear to be available despite the presence of its reference library code for the client and server projects, on github. I welcome any insight.

```<code>fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HLTL27BTITCT", Request id "0HLTL27BTITCT:00000001":
      An unhandled exception was thrown by the application.
System.IO.DirectoryNotFoundException:
      Could not find a part of the path '
          /mnt/drive1/testproj/test1/src/test1.Serve/bin/Debug
            /netstandard2.0/dist/_framework/_bin/test1.Client.dll
          '
   at Interop.ThrowExceptionForIoErrno(
          ErrorInfo errorInfo, String path, Boolean isDirectory
          ,Func`2 errorRewriter
          )
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(
          String path, OpenFlags flags, Int32 mode
          )
   at System.IO.FileStream..ctor(
          String path, FileMode mode, FileAccess access,
          FileShare share, Int32 bufferSize, FileOptions options
          )
   at System.IO.FileStream..ctor(
          String path, FileMode mode, FileAccess access
          ,FileShare share
          )
   at System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes)
   at System.IO.File.WriteAllBytes(String path, Byte[] bytes)
   at Elmish.HotReload.Bolero.Cli.ListenerController.Update() in
          /root/TeamCity/buildAgent/work/bbeb18eb622e1e0d/src
             /bolero-live/ListenerController.fs
          :line 39
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor
          .AwaitableResultExecutor.Execute(
            IActionResultTypeMapper mapper
            ,ObjectMethodExecutor executor
            ,Object controller, Object[] arguments
            )
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .Rethrow(ActionExecutedContext context)
</code>```

答:
bolero-live is different than the Bolero HotReload Templating implementation. bolero-live is supposed to reload the underlying dll as well, not just the front end. You can find the source code here

It unfortunately has not been heavily maintained or kept up to date with the latest Bolero versions (mostly as I've not had time to maintain it). The exception seems to indicate that the cli tool itself cannot find the newly made dll from FCSWatch.

Body:
I've been having a problem getting a modified bolero app to perform HotReload. The problem appears to be in bolero-live as indicated by this top portion of the error log (line break inserted for convenience). However, the source code for bolero-live does not appear to be available despite the presence of its reference library code for the client and server projects, on github. I welcome any insight.

fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HLTL27BTITCT", Request id "0HLTL27BTITCT:00000001":
      An unhandled exception was thrown by the application.
System.IO.DirectoryNotFoundException:
      Could not find a part of the path '
          /mnt/drive1/testproj/test1/src/test1.Serve/bin/Debug
            /netstandard2.0/dist/_framework/_bin/test1.Client.dll
          '
   at Interop.ThrowExceptionForIoErrno(
          ErrorInfo errorInfo, String path, Boolean isDirectory
          ,Func`2 errorRewriter
          )
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(
          String path, OpenFlags flags, Int32 mode
          )
   at System.IO.FileStream..ctor(
          String path, FileMode mode, FileAccess access,
          FileShare share, Int32 bufferSize, FileOptions options
          )
   at System.IO.FileStream..ctor(
          String path, FileMode mode, FileAccess access
          ,FileShare share
          )
   at System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes)
   at System.IO.File.WriteAllBytes(String path, Byte[] bytes)
   at Elmish.HotReload.Bolero.Cli.ListenerController.Update() in
          /root/TeamCity/buildAgent/work/bbeb18eb622e1e0d/src
             /bolero-live/ListenerController.fs
          :line 39
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor
          .AwaitableResultExecutor.Execute(
            IActionResultTypeMapper mapper
            ,ObjectMethodExecutor executor
            ,Object controller, Object[] arguments
            )
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
          .Rethrow(ActionExecutedContext context)


问:
Instruments reporting memory leak whenever AVSpeechSynthesizer is used to read text
Everytime I use AVSpeechSynthesizer to speak text Instruments reports a memory leak in the AXSpeechImplementation library. Here's the code I'm using to make the call:

```<code>AVSpeechUtterance *speak = [AVSpeechUtterance speechUtteranceWithString:text];
speak.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"];
speak.rate = AVSpeechUtteranceMaximumSpeechRate * .2;
[m_speechSynth speakUtterance:speak];
</code>```

Here's the link to the Instruments screenshot
http://imageshack.com/a/img690/7993/b9w5.png

答:
I solved this by declaring the AVSpeechSynthesizer as a global variable

static let synth = AVSpeechSynthesizer()
```

Body:
Everytime I use AVSpeechSynthesizer to speak text Instruments reports a memory leak in the AXSpeechImplementation library. Here's the code I'm using to make the call:

AVSpeechUtterance *speak = [AVSpeechUtterance speechUtteranceWithString:text];
speak.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"];
speak.rate = AVSpeechUtteranceMaximumSpeechRate * .2;
[m_speechSynth speakUtterance:speak];

Here's the link to the Instruments screenshot
http://imageshack.com/a/img690/7993/b9w5.png


问:
I want to convert multiple text file (delimited) to separate Excel using Python in a loop
I have a folder in which there are 128 .txt files and all of them have delimited data that is to be converted into separate Excel files.

I have the code to convert one text file to excel file but I want that all the files should be converted to excel file automatically and saved with the same name.

I am using the following code:

```<code>import xlwt
import xlrd
f = open('Events.txt', 'r+')
row_list = []
for row in f:
   row_list.append(row.split('|'))
column_list = zip(*row_list)
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet1')
i = 0
for column in column_list:
    for item in range(len(column)):
        worksheet.write(item, i, column[item])
    workbook.save('Excel.xls')
    i+=1
</code>```

All the files are stored in the same folder. I am unable to make a loop in which it will open the text file one by one and convert it to excel and save it with the same name as that of text file and then select second text file and so on for 128 files.

Please help!

Thank you in advance

答:
You can iterate in your folder like this:</p>

```<code>import os

dir = "your directory"

for filename in os.listdir(dir):
    if filename.endswith(".txt"):
        # print(os.path.join(dir, filename))
        continue # do your stuff
    else:
        continue
</code>```

Body:
I have a folder in which there are 128 .txt files and all of them have delimited data that is to be converted into separate Excel files.

I have the code to convert one text file to excel file but I want that all the files should be converted to excel file automatically and saved with the same name.

I am using the following code:

import xlwt
import xlrd
f = open('Events.txt', 'r+')
row_list = []
for row in f:
   row_list.append(row.split('|'))
column_list = zip(*row_list)
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet1')
i = 0
for column in column_list:
    for item in range(len(column)):
        worksheet.write(item, i, column[item])
    workbook.save('Excel.xls')
    i+=1

All the files are stored in the same folder. I am unable to make a loop in which it will open the text file one by one and convert it to excel and save it with the same name as that of text file and then select second text file and so on for 128 files.

Please help!

Thank you in advance

Body:
You can iterate in your folder like this:

import os

dir = "your directory"

for filename in os.listdir(dir):
    if filename.endswith(".txt"):
        # print(os.path.join(dir, filename))
        continue # do your stuff
    else:
        continue


问:
Reverse populate in mongoose
How can i reverse populate in mongo. I have 2 schema's

User:

```<code>var user_scheme = new mongoose.Schema({
  name:String,
  age:Number,
  roles:{
    type:mongoose.Schema.Types.ObjectId,
    ref:'Role'
  }
 });
</code>```

Role:

```<code>var role_scheme = new mongoose.Schema({
  name:String,
});
</code>```

Documents:

```<code>///user
{
"_id" : ObjectId("5bf9a19b01ce3e19b440aed8"),
"name" : "user1",
"age" : 22,
"roles" : ObjectId("5c0242621ab7b677e6b2e01e"),
"__v" : 0
}
 ///role
{
"_id" : ObjectId("5c0242621ab7b677e6b2e01e"),
"name" : "Admin"
}
</code>```

Code:

```<code>User.find().populate('roles').exec(function (err, data) {
 res.json(data);
})
</code>```

Here i can get roles under user, But how i get users under each role.

答:
The $lookup function by @Ashh was not working for me.

I used a more recent version :

$lookup: {
    from: 'users',
    localField: '_id',
    foreignField: 'organization',
    as: 'users'
}
```

Title: Reverse populate in mongoose

Body:
How can i reverse populate in mongo. I have 2 schema's

User:

var user_scheme = new mongoose.Schema({
  name:String,
  age:Number,
  roles:{
    type:mongoose.Schema.Types.ObjectId,
    ref:'Role'
  }
 });

Role:

var role_scheme = new mongoose.Schema({
  name:String,
});

Documents:

///user
{
"_id" : ObjectId("5bf9a19b01ce3e19b440aed8"),
"name" : "user1",
"age" : 22,
"roles" : ObjectId("5c0242621ab7b677e6b2e01e"),
"__v" : 0
}
 ///role
{
"_id" : ObjectId("5c0242621ab7b677e6b2e01e"),
"name" : "Admin"
}

Code:

User.find().populate('roles').exec(function (err, data) {
 res.json(data);
})

Here i can get roles under user, But how i get users under each role.


问:
Error displayed int Clion "multiple definition"
```<code>using namespace std;

class Student{

public:

    int rollNumber;

    int age;

    static int totalStudents;

};

int Student :: totalStudents = 0;

int main() {

    cout<<Student :: totalStudents << endl;

    return 0;
}
</code>```

Why do I get this error in Clion? The code seems to work fine on other online IDEs.

Here's the error message I'm getting :

CMakeFiles\OOPS2.dir/objects.a(Student.cpp.obj):Student.cpp:(.bss+0x0): multiple definition of `Student::totalStudents'

CMakeFiles\OOPS2.dir/objects.a(main.cpp.obj):main.cpp:(.data+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: * [CMakeFiles\OOPS2.dir\build.make:115: OOPS2.exe] Error 1
mingw32-make.exe[2]:  [CMakeFiles\Makefile2:75: CMakeFiles/OOPS2.dir/all] Error 2
mingw32-make.exe1:  [CMakeFiles\Makefile2:82: CMakeFiles/OOPS2.dir/rule] Error 2
mingw32-make.exe: * [Makefile:117: OOPS2] Error 2

答: Maybe there are two files listed in your Makefile, namely Student.cpp and main.cpp (as stated in error message)? If they are within the same Makefile or project or linked or include/reference each other then no wonder. </p>

Body:
using namespace std;

class Student{

public:

    int rollNumber;

    int age;

    static int totalStudents;

};

int Student :: totalStudents = 0;

int main() {

    cout<<Student :: totalStudents << endl;

    return 0;
}

Why do I get this error in Clion? The code seems to work fine on other online IDEs.

Here's the error message I'm getting :

CMakeFiles\OOPS2.dir/objects.a(Student.cpp.obj):Student.cpp:(.bss+0x0): multiple definition of `Student::totalStudents'

CMakeFiles\OOPS2.dir/objects.a(main.cpp.obj):main.cpp:(.data+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: * [CMakeFiles\OOPS2.dir\build.make:115: OOPS2.exe] Error 1
mingw32-make.exe[2]:  [CMakeFiles\Makefile2:75: CMakeFiles/OOPS2.dir/all] Error 2
mingw32-make.exe1:  [CMakeFiles\Makefile2:82: CMakeFiles/OOPS2.dir/rule] Error 2
mingw32-make.exe: * [Makefile:117: OOPS2] Error 2


问:
Panda pivot_table with only column total and no row total
I want to have grand total for columns ONLY and not for the rows.  It seems the margins flag will give me both row and column total:

pivot_operation=pd.pivot_table(df_operation,index=["Name"],values=["Hours"], columns=["Workdate"],aggfunc=[np.sum],margins=True,margins_name='Grand Total')

And I get

```<code>Hours
Workdate    02-03   02-04   02-05   02-06   02-07   Grand Total
Name
Joe              8.0    8.0     8.0     8.0     8.0     40.0
Mary             8.5    8.5     8.5     8.5     8.5     42.5
Grand Total     16.5    16.5    16.5    16.5    16.5    82.5
</code>```

Where I only want the Columns Grand Total without Row Grand total

```<code>Hours
Workdate    02-03   02-04   02-05   02-06   02-07   Grand Total
Name
Joe              8.0    8.0     8.0     8.0     8.0     40.0
Mary             8.5    8.5     8.5     8.5     8.5     42.5
</code>```

How can I achieve that?

答: For now, I could work around this by removing the last row using iloc function() after creating the pivot with margin. aggfunc=[np.sum],margins=True,margins_name='Grand Total').iloc[:-1,:]

Body:
I want to have grand total for columns ONLY and not for the rows.  It seems the margins flag will give me both row and column total:

pivot_operation=pd.pivot_table(df_operation,index=["Name"],values=["Hours"], columns=["Workdate"],aggfunc=[np.sum],margins=True,margins_name='Grand Total')

And I get

Hours
Workdate    02-03   02-04   02-05   02-06   02-07   Grand Total
Name
Joe              8.0    8.0     8.0     8.0     8.0     40.0
Mary             8.5    8.5     8.5     8.5     8.5     42.5
Grand Total     16.5    16.5    16.5    16.5    16.5    82.5

Where I only want the Columns Grand Total without Row Grand total

Hours
Workdate    02-03   02-04   02-05   02-06   02-07   Grand Total
Name
Joe              8.0    8.0     8.0     8.0     8.0     40.0
Mary             8.5    8.5     8.5     8.5     8.5     42.5

How can I achieve that?


问:
Not sure if this is possible, but I would like to position a bar at the bottom of the view port, which stays until the footer scrolls into view
Hoping i can explain this clearly. I searched for many permutations and can't find anything that pertains...

I have a bar, with some buttons, that "sticks" to the bottom of the view port using absolute, and fixed, positioning. This I understand (using bootstrap 4).

What I would like to then happen is when the user scrolls the page, and the footer then comes into view, the button bar would then move up with the footer so as not to obscure the footer. When the user then scrolls the page down and the footer moves out of view, the button bar would then stay at the bottom of the view port.

How might I approach this? I've tried a bunch of things but can't seem to get it latch onto the footer.

Thanks for all the suggestions.

答:
you would probably want to try the jQuery scroll function: https://api.jquery.com/scroll/

so you can detect the scroll distance where the button bar is, then change the css to make the viewport bar unfixed. May be a bit tricky though.


问:
Excel - counting names in an column that have non blank columns adjacent to them
I need to count the number of names in Column A that do not have blank cells adjacent to them in Column B .. I've tried several combinations of countif, countifs, counta .. and all i can get it to do is add the results together. </p>

<p>Thanks for any help. </p>

答:
One option might be something like the following, using wildcards:</p>

```<code>=COUNTIFS(A:A,"*",B:B,"*")
</code>```

Body:
I need to count the number of names in Column A that do not have blank cells adjacent to them in Column B .. I've tried several combinations of countif, countifs, counta .. and all i can get it to do is add the results together.

Thanks for any help.

Body:
One option might be something like the following, using wildcards:

=COUNTIFS(A:A,"*",B:B,"*")


问:
How to remove Header in functional component React Native
I'm setting up a navigation in react-native using only functional component. How do i remove the header on the Screen?

```<code>const AppScreen = ({ navigation }) => {

  //Desc => removing header
  AppScreen.navigationOptions = {
    header: null
  };

  return (
    <>
      <Text>LoGinScreen</Text>
    </>
  );
};
</code>```

No error message is shown but the app renders with a header.

答:
You can remove header from functional component

```<code> const AppScreen = ({ navigation }) => {
 return (
   <Text>LoginScreen</Text>
 );
};
</code>```

by using this out side of your functional component.

```<code>AppScreen.navigationOptions = {
header: null
};
</code>```

Body:
I'm setting up a navigation in react-native using only functional component. How do i remove the header on the Screen?

const AppScreen = ({ navigation }) => {

  //Desc => removing header
  AppScreen.navigationOptions = {
    header: null
  };

  return (
    <>
      <Text>LoGinScreen</Text>
    </>
  );
};

No error message is shown but the app renders with a header.

Body:
You can remove header from functional component

 const AppScreen = ({ navigation }) => {
 return (
   <Text>LoginScreen</Text>
 );
};

by using this out side of your functional component.

AppScreen.navigationOptions = {
header: null
};


问:
How to fetch the XPATH of an initialized IWebElement in c#
I am using WinappDriver/Appium to automate an windows application project.

I have initialized an Parent WindowsElement using Xpath.

Now once the Element is initialized i want to get the XPATH of the (Parent) Element which was used so that i can get the Child elements using the Parent XPATH.

```<code>session = UiaWindowDriver.CreateSession(new Uri(WindowsApplicationDriverUrl), uiaDriverOptions); //WindowsDriver<WindowsElement>
var Window = session.GetWindow("//Window[@Name=\"Sample Application\"]"); //Returns me an WindowsElement
</code>```

Now as i got the Window (i.e. Parent Control) i want to get the child elements of the Parent Control.

Any help is appreciated.

Many Thanks !!!

答:
Why create it as a Window? You can just create that as a WindowsElement like...

```<code>WindowsElement parentWindow = session.FindElementByXPath("//Window[@Name=\"Sample Application\"]");
</code>```

THEN this will allow you to look for additional elements isolated to this window like so..

```<code>WindowsElement someElement = parentWindow.FindElementByXPath("...");
</code>```

In some cases it may throw an error related to casting, you can resolve that like so...

```<code>WindowsElement someElement = (WindowsElement)parentWindow.FindElementByXPath("...");
</code>```

I am almost certain this will work in your case.

Body:
I am using WinappDriver/Appium to automate an windows application project.

I have initialized an Parent WindowsElement using Xpath.

Now once the Element is initialized i want to get the XPATH of the (Parent) Element which was used so that i can get the Child elements using the Parent XPATH.

session = UiaWindowDriver.CreateSession(new Uri(WindowsApplicationDriverUrl), uiaDriverOptions); //WindowsDriver<WindowsElement>
var Window = session.GetWindow("//Window[@Name=\"Sample Application\"]"); //Returns me an WindowsElement

Now as i got the Window (i.e. Parent Control) i want to get the child elements of the Parent Control.

Any help is appreciated.

Many Thanks !!!

Body:
Why create it as a Window? You can just create that as a WindowsElement like...

WindowsElement parentWindow = session.FindElementByXPath("//Window[@Name=\"Sample Application\"]");

THEN this will allow you to look for additional elements isolated to this window like so..

WindowsElement someElement = parentWindow.FindElementByXPath("...");

In some cases it may throw an error related to casting, you can resolve that like so...

WindowsElement someElement = (WindowsElement)parentWindow.FindElementByXPath("...");

I am almost certain this will work in your case.


问:
Formatting Mysql Queries in Table
Alright. I have several queries

```<code>    <?php
// Make a MySQL Connection
mysql_connect("mm.hostname.net", "user", "pass") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());

$query  = "SELECT card_id,item_bar FROM cards";
$result = mysql_query($query);

while($row = mysql_fetch_assoc($result))
{
    echo "Id :{$row['card_id']} <br>" .
         "Title :($row['title']}" .
         "Description :($row['description']}";
}

include 'closedb.php';
?>
</code>```

My question is how do I get the queries to align in a table like form like below?

```<code>Id  |  Title  |  Description
============================
1   |  card   |  cute and fluffy
1   |  card   |  cute and fluffy
1   |  card   |  cute and fluffy
1   |  card   |  cute and fluffy
1   |  card   |  cute and fluffy
</code>```

I am pretty new to queries using php (and really still trying to get the hang of them anyway)

答:
You can use tables:</p>

```<code><?php
// Make a MySQL Connection
mysql_connect("hostname", "user", "pass") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());

$query  = "SELECT card_id,item_bar FROM cards";
$result = mysql_query($query);

echo '<table>';
echo '<th><td>Id</td><td>Title</td><td>Description</td></th>';
while($row = mysql_fetch_assoc($result))
{
    echo "<tr><td>$row['card_id']</td>" .
         "<td>$row['title']</td>" .
         "<td>$row['description']</td></tr>";
}
echo '</table>';
?>
</code>```

Title: Formatting Mysql Queries in Table

Body:
Alright. I have several queries

    <?php
// Make a MySQL Connection
mysql_connect("mm.hostname.net", "user", "pass") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());

$query  = "SELECT card_id,item_bar FROM cards";
$result = mysql_query($query);

while($row = mysql_fetch_assoc($result))
{
    echo "Id :{$row['card_id']}
" .
         "Title :($row['title']}" .
         "Description :($row['description']}";
}

include 'closedb.php';
?>

My question is how do I get the queries to align in a table like form like below?

Id  |  Title  |  Description
============================
1   |  card   |  cute and fluffy
1   |  card   |  cute and fluffy
1   |  card   |  cute and fluffy
1   |  card   |  cute and fluffy
1   |  card   |  cute and fluffy

I am pretty new to queries using php (and really still trying to get the hang of them anyway)

Body:
You can use tables:

<?php
// Make a MySQL Connection
mysql_connect("hostname", "user", "pass") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());

$query  = "SELECT card_id,item_bar FROM cards";
$result = mysql_query($query);

echo '<table>';
echo '<th><td>Id</td><td>Title</td><td>Description</td></th>';
while($row = mysql_fetch_assoc($result))
{
    echo "<tr><td>$row['card_id']</td>" .
         "<td>$row['title']</td>" .
         "<td>$row['description']</td></tr>";
}
echo '</table>';
?>


问:
Is it possible to update a Doc2Vec Vector?
I am working with a steadily growing corpus. I train my Document Vector with Doc2Vec which is implemented in Python.

Is it possible to update a Document Vector?

I want to use the Document Vector for Document recommendations.

答:
Individual vectors can be updated, but the gensim Doc2Vec model class doesn't have much support for adding more doc-vectors to itself.

It can, however, return individual vectors for new texts that are compatible (comparable) with the existing vectors, via the .infer_vector(words) method. You can retain these vectors in your own data structures for lookup.

When enough new documents have arrived that you think your core model would be better, if trained on all documents, you can re-train the model with all available data, using it as the new base for .infer_vector(). (Note that vectors from the retrained model won't usually be compatible/comparable with those from the prior model: each training session bootstraps a different self-consistent coordinate space.)


问:
Luigi: Is there a way to use Extended Interpolation like in configparser?
I have a luigi config file:

```<code>[Common]
dir: /some/path

[MyTask]
task_parameter: ${Common:dir}/other/folders/
</code>```

But when I run luigi task with path to the config I see that task_parameter == "${Common:dir}/other/folders/", not "/some/path/other/folders/"

Am I doing something wrong? Is it possible to use LuigiConfigParser in that way?

I use python2.7 and luigi==2.7.1.

答:
No, you cannot do extended interpolation. Interpolation is Shell specific and configurations are parsed inside of Python land. Also, remember that all parameters must be serializable, so Luigi/Python would have to jump through some pretty weird hoops for this.

However, it is pretty easy to extend to what you need. What you could do is instead of specifying task_parameter, you could specify say task_parameter_query and use the string as the basis for a query when resolving the parameter's purpose. It looks like you're just trying to get an environment variable here, so you could just use task_parameter as a string template and then fill in the value by calling to os.getenv.

Body:
I have a luigi config file:

[Common]
dir: /some/path

[MyTask]
task_parameter: ${Common:dir}/other/folders/

But when I run luigi task with path to the config I see that task_parameter == "${Common:dir}/other/folders/", not "/some/path/other/folders/"

Am I doing something wrong? Is it possible to use LuigiConfigParser in that way?

I use python2.7 and luigi==2.7.1.


问:
Cocoa: How to properly hide other views below NSImageView?
I have a view with several subviews (NSButton, NSTextField, NSPopUpButton) and a NSImageView with a spinner icon which should be displayed on top of the other views while data is retrieved from the web.

To display the NSImageView on top  I have set

```<code>imageViewSpinner.wantsLayer = true
imageViewSpinner.layer?.backgroundColor = NSColor.windowBackgroundColor.cgColor
</code>```

The problem is, that the focus borders and PopUpButtons are still accessible/shining through the NSImageView (see attached video).

To solve this, I could iterate over all the other subviews and set them to "isHidden" or "disabled" but I wonder, if there is a cleaner solution to this problem, for example defining the NSImageView as topmost layer without things getting through?

答:
You could put all of the other views inside of one container view and hide that.

You can also use a tab-less tab view to programmatically switch between view sub-hierarchies. (That basically achieves the same thing. It's better when there are more than 2 views to manage.)

Body:
I have a view with several subviews (NSButton, NSTextField, NSPopUpButton) and a NSImageView with a spinner icon which should be displayed on top of the other views while data is retrieved from the web.

To display the NSImageView on top  I have set

imageViewSpinner.wantsLayer = true
imageViewSpinner.layer?.backgroundColor = NSColor.windowBackgroundColor.cgColor

The problem is, that the focus borders and PopUpButtons are still accessible/shining through the NSImageView (see attached video).

To solve this, I could iterate over all the other subviews and set them to "isHidden" or "disabled" but I wonder, if there is a cleaner solution to this problem, for example defining the NSImageView as topmost layer without things getting through?


问:
Opening an link and scrape the data in exisiting webpage using selineum webdriver python
I am learning web scraping using Selenium web driver using Python. For my learning purpose, I am scraping indeed.com. I am scraping job title, company name, location, salary and job summary. I can able to extract job title, company name, location, salary using beautiful soup. Job summary is loading into the next page where I am trying to using selenium to extract the data but not successful. I have checked all the posts here, but still couldn't able to do it. I can able to click the new page but I am not sure how to scrape the data from the new page.

my code

```<code>#Importing necessary library

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.firefox.options import Options
import pandas as pd
import time
import re
import requests
from itertools import zip_longest
from webdriver_manager.chrome import ChromeDriverManager

title = []
company = []
locations = []
summary = []

for pageno in range(0,26):
    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.get("https://nz.indeed.com/jobs?q=data+analyst&l=New+Zealand&start=" + str(10*pageno))
    time.sleep(1)

    summaryItems = driver.find_elements_by_xpath("//a[contains(@class, 'jobtitle turnstileLink')]")
    job_links = [summaryItem.get_attribute("href") for summaryItem in summaryItems]

    for job_link in job_links:
        driver.get(job_link)
        time.sleep(1)

        job_title = driver.find_element_by_xpath("//*[@class='icl-u-xs-mb--xs icl-u-xs-mt--none jobsearch-JobInfoHeader-title']").text
        title.append(job_title)

        company_name = driver.find_element_by_xpath("//div[@class='icl-u-lg-mr--sm icl-u-xs-mr--xs']").text
        company.append(company_name)

        location = driver.find_element_by_xpath("//*[@class='jobsearch-JobMetadataHeader-iconLabel']").text
        locations.append(location)

        job_description = driver.find_element_by_xpath("//*[@class='jobsearch-jobDescriptionText']").text
        summary.append(job_description)

driver.close()

# Converting all the details into dataframe and csv file
final = []
for item in zip_longest(title, company, locations, summary):
    final.append(item)

df4 = pd.DataFrame(
    final, columns=['Job_title', 'Company_name','Locations', 'Summary'])
#df.to_csv('booked.csv')

I tried to debug but not successful. One of the job page is not loading. I don't know the reason. Problem either 3 or 4 loop. Any suggestion?
</code>```

I can able to click the new page but I am not sure how to scrape the data from the new page. I need to do for other pages as well automatically. Any suggestions, please?

答:
Instead of clicking to open a job on a new page, you can get the link of that job and load it again through Selenium, as follows:

```<code>driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://nz.indeed.com/jobs?q=data+scientist&l=New+Zealand&start=" + str(10*1))
time.sleep(5)

summaryItems = driver.find_element_by_xpath("//a[contains(@class, 'jobtitle turnstileLink')]")
job_link = summaryItems.get_attribute("href")
driver.get(job_link)
</code>```

Now, you can easily get job information, as follows:

```<code>job_title = driver.find_element_by_xpath("//*[@class='icl-u-xs-mb--xs icl-u-xs-mt--none jobsearch-JobInfoHeader-title']")
company_name = driver.find_element_by_xpath("//*[@class='icl-u-lg-mr--sm icl-u-xs-mr--xs']")
location = driver.find_element_by_xpath("//*[@class='jobsearch-JobMetadataHeader-iconLabel']")
job_description = driver.find_element_by_xpath("//*[@class='jobsearch-jobDescriptionText']")
</code>```

EDIT:

If you want to get the information of all job listings, you can do so as follows:

```<code>summaryItems = driver.find_elements_by_xpath("//a[contains(@class, 'jobtitle turnstileLink')]")
job_links = [summaryItem.get_attribute("href") for summaryItem in summaryItems]

for job_link in job_links:
    driver.get(job_link)
    time.sleep(1)

    job_title = driver.find_element_by_xpath("//*[@class='icl-u-xs-mb--xs icl-u-xs-mt--none jobsearch-JobInfoHeader-title']").text
    company_name = driver.find_element_by_xpath("//*[@class='icl-u-lg-mr--sm icl-u-xs-mr--xs']").text
    location = driver.find_element_by_xpath("//*[@class='jobsearch-JobMetadataHeader-iconLabel']").text
    job_description = driver.find_element_by_xpath("//*[@class='jobsearch-jobDescriptionText']").text
</code>```

EDIT 2:

To avoid getting an error when there is no company name for a certain job, you can do the following:

```<code>try:
    company_name = driver.find_element_by_xpath("//div[@class='icl-u-lg-mr--sm icl-u-xs-mr--xs']").text
except:
    company_name = ""
</code>```

Hope it helps.

Body:
I am learning web scraping using Selenium web driver using Python. For my learning purpose, I am scraping indeed.com. I am scraping job title, company name, location, salary and job summary. I can able to extract job title, company name, location, salary using beautiful soup. Job summary is loading into the next page where I am trying to using selenium to extract the data but not successful. I have checked all the posts here, but still couldn't able to do it. I can able to click the new page but I am not sure how to scrape the data from the new page.

my code

#Importing necessary library

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.firefox.options import Options
import pandas as pd
import time
import re
import requests
from itertools import zip_longest
from webdriver_manager.chrome import ChromeDriverManager

title = []
company = []
locations = []
summary = []

for pageno in range(0,26):
    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.get("https://nz.indeed.com/jobs?q=data+analyst&l=New+Zealand&start=" + str(10*pageno))
    time.sleep(1)

    summaryItems = driver.find_elements_by_xpath("//a[contains(@class, 'jobtitle turnstileLink')]")
    job_links = [summaryItem.get_attribute("href") for summaryItem in summaryItems]

    for job_link in job_links:
        driver.get(job_link)
        time.sleep(1)

        job_title = driver.find_element_by_xpath("//*[@class='icl-u-xs-mb--xs icl-u-xs-mt--none jobsearch-JobInfoHeader-title']").text
        title.append(job_title)

        company_name = driver.find_element_by_xpath("//div[@class='icl-u-lg-mr--sm icl-u-xs-mr--xs']").text
        company.append(company_name)

        location = driver.find_element_by_xpath("//*[@class='jobsearch-JobMetadataHeader-iconLabel']").text
        locations.append(location)

        job_description = driver.find_element_by_xpath("//*[@class='jobsearch-jobDescriptionText']").text
        summary.append(job_description)

driver.close()

# Converting all the details into dataframe and csv file
final = []
for item in zip_longest(title, company, locations, summary):
    final.append(item)

df4 = pd.DataFrame(
    final, columns=['Job_title', 'Company_name','Locations', 'Summary'])
#df.to_csv('booked.csv')

I tried to debug but not successful. One of the job page is not loading. I don't know the reason. Problem either 3 or 4 loop. Any suggestion?

I can able to click the new page but I am not sure how to scrape the data from the new page. I need to do for other pages as well automatically. Any suggestions, please?

Body:
Instead of clicking to open a job on a new page, you can get the link of that job and load it again through Selenium, as follows:

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://nz.indeed.com/jobs?q=data+scientist&l=New+Zealand&start=" + str(10*1))
time.sleep(5)

summaryItems = driver.find_element_by_xpath("//a[contains(@class, 'jobtitle turnstileLink')]")
job_link = summaryItems.get_attribute("href")
driver.get(job_link)

Now, you can easily get job information, as follows:

job_title = driver.find_element_by_xpath("//*[@class='icl-u-xs-mb--xs icl-u-xs-mt--none jobsearch-JobInfoHeader-title']")
company_name = driver.find_element_by_xpath("//*[@class='icl-u-lg-mr--sm icl-u-xs-mr--xs']")
location = driver.find_element_by_xpath("//*[@class='jobsearch-JobMetadataHeader-iconLabel']")
job_description = driver.find_element_by_xpath("//*[@class='jobsearch-jobDescriptionText']")

EDIT:

If you want to get the information of all job listings, you can do so as follows:

summaryItems = driver.find_elements_by_xpath("//a[contains(@class, 'jobtitle turnstileLink')]")
job_links = [summaryItem.get_attribute("href") for summaryItem in summaryItems]

for job_link in job_links:
    driver.get(job_link)
    time.sleep(1)

    job_title = driver.find_element_by_xpath("//*[@class='icl-u-xs-mb--xs icl-u-xs-mt--none jobsearch-JobInfoHeader-title']").text
    company_name = driver.find_element_by_xpath("//*[@class='icl-u-lg-mr--sm icl-u-xs-mr--xs']").text
    location = driver.find_element_by_xpath("//*[@class='jobsearch-JobMetadataHeader-iconLabel']").text
    job_description = driver.find_element_by_xpath("//*[@class='jobsearch-jobDescriptionText']").text

EDIT 2:

To avoid getting an error when there is no company name for a certain job, you can do the following:

try:
    company_name = driver.find_element_by_xpath("//div[@class='icl-u-lg-mr--sm icl-u-xs-mr--xs']").text
except:
    company_name = ""

Hope it helps.


问:
Firebase App Distribution for Android from gradle with groups totalling more than 200 users
I just migrated my Android app from Fabric Beta to Firebase App Distribution. My Fabric group android had 395 people in it, and Firebase only allows a maximum of 200 people in a group, so I split my Firebase groups into android-1 and android-2.

Here is my gradle definition:

```<code>firebaseAppDistribution {
  releaseNotes="Alpha"
  groups="android-1, android-2, qa"
}
</code>```

However, when I try to run my gradle task, I get the following error:

```<code>Execution failed for task ':app:appDistributionUploadRelease'.
> App Distribution halted because it had a problem adding testers/groups: [400] Request contains an invalid argument.
</code>```

If I change groups to:

```<code>firebaseAppDistribution {
  releaseNotes="Alpha"
  groups="android-1, qa"
}
</code>```

or:

```<code>firebaseAppDistribution {
  releaseNotes="Alpha"
  groups="android-2, qa"
}
</code>```

everything works fine.

I suspect that firebase just doesn't want to send more than 200 emails at a time when there's a new update.
Does anyone have an idea how to work around this?

Also, I'm trying to find the github project for this, so I can file an issue, but nothing is coming up.

答:
A firebase developer relations engineer told me this is likely a Firebase Bug. I submitted a bug report there. I'll update this answer when I learn more.

Update

Someone from firebase-community showed me documentation proving that Firebase App Distribution is limited to 200 users:

Tester limits
  App Distribution offers free quotas that let you start distributing your app at no cost. The free quota amounts are listed below. If you need more quota, request a free limit increase.

||Operation||Quota||

|Add testers to a Firebase project|500 testers per Firebase project|

|Add testers to an App Distribution group|200 testers per group|

|Distribute to testers|200 testers per build distribution|

Body:
I just migrated my Android app from Fabric Beta to Firebase App Distribution. My Fabric group android had 395 people in it, and Firebase only allows a maximum of 200 people in a group, so I split my Firebase groups into android-1 and android-2.

Here is my gradle definition:

firebaseAppDistribution {
  releaseNotes="Alpha"
  groups="android-1, android-2, qa"
}

However, when I try to run my gradle task, I get the following error:

Execution failed for task ':app:appDistributionUploadRelease'.
> App Distribution halted because it had a problem adding testers/groups: [400] Request contains an invalid argument.

If I change groups to:

firebaseAppDistribution {
  releaseNotes="Alpha"
  groups="android-1, qa"
}

or:

firebaseAppDistribution {
  releaseNotes="Alpha"
  groups="android-2, qa"
}

everything works fine.

I suspect that firebase just doesn't want to send more than 200 emails at a time when there's a new update.
Does anyone have an idea how to work around this?

Also, I'm trying to find the github project for this, so I can file an issue, but nothing is coming up.


问:
Is there a way to intercept setters and getters in C#?
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

```<code>public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code>```

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.

答:
As far as I know, you have to use a backing field and put the call to the other method inside the setter thusly:</p>

```<code>public class Person {
    private string firstName;
    private string lastName;

    public string FirstName {
        set {
            DoSomeStuff();
            firstName = value;
        }
        get { return firstName; }
    }

    public string LastName {
        set {
            DoSomeStuff();
            lastName = value;
        }
        get { return lastName; }
    }
}
</code>```

Body:
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.

Body:
As far as I know, you have to use a backing field and put the call to the other method inside the setter thusly:

public class Person {
    private string firstName;
    private string lastName;

    public string FirstName {
        set {
            DoSomeStuff();
            firstName = value;
        }
        get { return firstName; }
    }

    public string LastName {
        set {
            DoSomeStuff();
            lastName = value;
        }
        get { return lastName; }
    }
}


问:
Javascript find index of word in string (not part of word)
I am currently using str.indexOf("word") to find a word in a string.
But the problem is that it is also returning parts of other words.

Example: "I went to the foobar and ordered foo."
I want the first index of the single word "foo", not not the foo within foobar.

I can not search for "foo " because sometimes it might be followed by a full-stop or comma (any non-alphanumeric character).

答:
I have tried both with ".search" and ".match", as suggested in the previous answers, but only this solution worked for me.

```<code>var str = 'Lorem Ipsum Docet';
var kw  = 'IPSUM';
var res = new RegExp('\\b('+kw+')\\b','i').test(str);

console.log(res); // true (...or false)
</code>```

With the 'i' for case insensitive search.

ComFreek wrote a detailed answer here

Body:
I have tried both with ".search" and ".match", as suggested in the previous answers, but only this solution worked for me.

var str = 'Lorem Ipsum Docet';
var kw  = 'IPSUM';
var res = new RegExp('\\b('+kw+')\\b','i').test(str);

console.log(res); // true (...or false)

With the 'i' for case insensitive search.

ComFreek wrote a detailed answer here


问:
protractor - how to select element from multiselect dropdown
I am using multiselect dropdown from angular https://www.npmjs.com/package/ng-multiselect-dropdown
and want to select element from the dropdown using protractor. DOM element looks like below.
I need to check the checkbox for which value is 'Navkit'.</p>

```<code><ng-multiselect-dropdown name="dropdown">
    <div class="multiselect-dropdown">
        <div class="dropdown-list">
            <ul class="item2">
                <li class="multiselect-item-checkbox">
                    <input _ngcontent-c3="" aria-label="multiselect-item" type="checkbox">
                    <div _ngcontent-c3="">Navkit</div>
</code>```

答:
I use Protractor filters to select items form Drop down menu :</p>

```<code> this.DDmenueItems = element.all(by.css(".multiselect-item-checkbox"));

//Before selecting value from dropdown make sure to click on Drop down and populate drop down list.

 this.FilterDDSelectField("Navkit");

    exports.FilterDDSelectField = function (fieldname) {
    this.DDmenueItems.filter(function (elem, index) {
        return elem.getText().then(function (text) {
          return text.toUpperCase() === fieldname.toUpperCase();
        });
      }).then(function (filteredElements) {
        filteredElements[0].click();
      });
    }
</code>```

Body:
I am using multiselect dropdown from angular https://www.npmjs.com/package/ng-multiselect-dropdown
and want to select element from the dropdown using protractor. DOM element looks like below.
I need to check the checkbox for which value is 'Navkit'.

<ng-multiselect-dropdown name="dropdown">

                    <input _ngcontent-c3="" aria-label="multiselect-item" type="checkbox">

Navkit

Body:
I use Protractor filters to select items form Drop down menu :

 this.DDmenueItems = element.all(by.css(".multiselect-item-checkbox"));

//Before selecting value from dropdown make sure to click on Drop down and populate drop down list.

 this.FilterDDSelectField("Navkit");

    exports.FilterDDSelectField = function (fieldname) {
    this.DDmenueItems.filter(function (elem, index) {
        return elem.getText().then(function (text) {
          return text.toUpperCase() === fieldname.toUpperCase();
        });
      }).then(function (filteredElements) {
        filteredElements[0].click();
      });
    }