问:
pyautogui to locate certain text in a dropdown menu
Just discovered the pyautogui function, and its an amazing function

everything works great when i use the x and y coordinates , so i am using x and y coordinates to click on the drop down menu and this menu contains round about 40 options like this :

Alex Lategun 205 north ave
sergy shimer 22 xyz ave
Joe Astpher  11 fifth block
:
:
:
:
:::::::

now if i wanted to select only the field with Joe Astpher  how do i do that so that it selects the required option with lightning fast speed ?

the reason i cant use the x and y coordinates in selecting the options is because the dropdown menu contains the scroll bar and most of the option are hidden
so what are the possible options for me to achieve this ?

答:
If only one option begins with 'j', you can do this for pyautogui to travel to that specific button:

```<code>pyautogui.typewrite('j')
</code>```

If more than one option begins with 'j', you can count how many times you would need to press 'j' on the keyboard to get there and add that amount of pyautogui.typewrite('j') to your script.

Then, make it press it:

```<code>pyautogui.typewrite('enter')
</code>```

Body:
If only one option begins with 'j', you can do this for pyautogui to travel to that specific button:

pyautogui.typewrite('j')

If more than one option begins with 'j', you can count how many times you would need to press 'j' on the keyboard to get there and add that amount of pyautogui.typewrite('j') to your script.

Then, make it press it:

pyautogui.typewrite('enter')


来源: stackexchange

问:
Running an operation periodically when the length of operation is not known
I need to execute an operation that needs to be executed relatively fast (let's say 10 times per second.  It should be fast enough, but I can sacrifice speed if there are issues.) This is an ajax request, so potentially I do not know how much time it takes - it could even take seconds if network is bad.

The usual:

```<code>setInterval(() => operation(), 100);
</code>```

Will not work here, because if the network is bad and my operation takes more than 100 ms, It might be scheduled one after another, occupying JS engine time (please correct me if I'm wrong)

The other possible solution is to recursively run it:

```<code>function execute() {
   operation();
   setTimeout(execute, 100);
}
</code>```

This means that there will be 100 ms between the calls to operation(), which is OK for me. The problem with this is that I'm afraid that it will fail at some point because of stack overflow. Consider this code:

```<code>i = 0;
function test() { if (i % 1000 == 0) console.log(i); i++; test(); }
</code>```

If I run it my console, this fails in around 12000 calls. if I add setTimeout in the end, this would mean 12000 / 10 / 60 = 20 minutes, potentially ruining the user experience.

Are there any simple ways how to do this and be sure it can run for days?

答:
The two alternatives you showed here actually share the flaw you're concerned about, which is that the callbacks might bunch up and run together. Using setTimeout like this is (for your purposes) identical to calling setInterval (except for some small subtleties that don't apply with a light call like making an AJAX request.)

It sounds like you might want to guarantee that the callbacks run in order, or potentially that if multiple callbacks come in at once, that only the most recent one is run.

To build a service that runs the most recent callback, consider a setup like this:

let lastCallbackOriginTime = 0;

setInterval(()=>{
    const now = new Date().getTime();
    fetch(url).then(x=>x.json()).then(res=>{
        if ( now > lastCallbackOriginTime ) {
            // do interesting stuff
            lastCallbackOriginTime = now;
        }
        else console.log('Already ran a more recent callback');
    });
}, 100);
```

<p>Or let's make it run the callbacks in order. To do this, just make each callback depend on a promise returned by the previous one.</p>

<pre class="lang-js prettyprint-override"><code>let promises = [Promise.resolve(true)];
setInterval(()=>{
    const promise = new Promise((resolve, reject)=> {
fetch(url).then(x=>x.json()).then(serviceResponse=>{
        const lastPromise = promises[promises.length - 1];
        lastPromise.then(()=>resolve(serviceResponse));
    }).then((serviceResponse)=>{
        // Your actual callback code
    });
    promises.push(promise)

   });
}, 100);

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to execute an operation that needs to be executed relatively fast (let's say 10 times per second.  It should be fast enough, but I can sacrifice speed if there are issues.) This is an ajax request, so potentially I do not know how much time it takes - it could even take seconds if network is bad.

The usual:

setInterval(() => operation(), 100);

Will not work here, because if the network is bad and my operation takes more than 100 ms, It might be scheduled one after another, occupying JS engine time (please correct me if I'm wrong)

The other possible solution is to recursively run it:

function execute() {
   operation();
   setTimeout(execute, 100);
}

This means that there will be 100 ms between the calls to operation(), which is OK for me. The problem with this is that I'm afraid that it will fail at some point because of stack overflow. Consider this code:

i = 0;
function test() { if (i % 1000 == 0) console.log(i); i++; test(); }

If I run it my console, this fails in around 12000 calls. if I add setTimeout in the end, this would mean 12000 / 10 / 60 = 20 minutes, potentially ruining the user experience.

Are there any simple ways how to do this and be sure it can run for days?

Body:
The two alternatives you showed here actually share the flaw you're concerned about, which is that the callbacks might bunch up and run together. Using setTimeout like this is (for your purposes) identical to calling setInterval (except for some small subtleties that don't apply with a light call like making an AJAX request.)

It sounds like you might want to guarantee that the callbacks run in order, or potentially that if multiple callbacks come in at once, that only the most recent one is run.

To build a service that runs the most recent callback, consider a setup like this:

let lastCallbackOriginTime = 0;

setInterval(()=>{
    const now = new Date().getTime();
    fetch(url).then(x=>x.json()).then(res=>{
        if ( now > lastCallbackOriginTime ) {
            // do interesting stuff
            lastCallbackOriginTime = now;
        }
        else console.log('Already ran a more recent callback');
    });
}, 100);

Or let's make it run the callbacks in order. To do this, just make each callback depend on a promise returned by the previous one.

let promises = [Promise.resolve(true)];
setInterval(()=>{
    const promise = new Promise((resolve, reject)=> {
fetch(url).then(x=>x.json()).then(serviceResponse=>{
        const lastPromise = promises[promises.length - 1];
        lastPromise.then(()=>resolve(serviceResponse));
    }).then((serviceResponse)=>{
        // Your actual callback code
    });
    promises.push(promise)

   });
}, 100);


问:
How to create single jar in scala with sbt assembly on AWS EMR? Running into deduplicate: different file contents found in the following: errors
I'm on an AWS EMR cluster I just stood up, have a scala file compiles and one which I would like to build into an assembly.  However, when I issue sbt assembly I run into deduplicate errors.

Per https://medium.com/@tedherman/compile-scala-on-emr-cb77610559f0 I originally had a symbolic link for my lib to usr lib spark jars;

```<code>ln -s /usr/lib/spark/jars lib
</code>```

although I've noticed my code passes an sbt compile with or without this.  I am confused why/how to resolve sbt assembly dupe errors however.  I'll also note that I install sbt in bootstrap actions as per the article.

With the symbolic link in

Some dedupes appear to be clear exact dupes; example:

```<code>[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/org.apache.parquet/parquet-jackson/jars/parquet-jackson-1.10.1.jar:shaded/parquet/org/codehaus/jackson/util/CharTypes.class
[error] /usr/lib/spark/jars/parquet-jackson-1.10.1-spark-amzn-1.jar:shaded/parquet/org/codehaus/jackson/util/CharTypes.class
</code>```

Others seem to be competing versions;

```<code>[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/org.apache.spark/spark-core_2.11/jars/spark-core_2.11-2.4.3.jar:org/spark_project/jetty/util/MultiPartOutputStream.class
[error] /usr/lib/spark/jars/spark-core_2.11-2.4.5-amzn-0.jar:org/spark_project/jetty/util/MultiPartOutputStream.class
</code>```

I don't understand why there are competing versions; or if they are by default like this or I did something to introduce them.

Without the symbolic link

I thought if I removed this, I would have less problems; although I still have dupes (just less);

```<code>[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/org.apache.hadoop/hadoop-yarn-api/jars/hadoop-yarn-api-2.6.5.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] /home/hadoop/.ivy2/cache/org.apache.hadoop/hadoop-yarn-common/jars/hadoop-yarn-common-2.6.5.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
</code>```

I don't understand why the above is a dupe considering one is hadoop-yarn-api-2.6.5.jar and the other is hadoop-yarn-common-2.6.5.jar.  Different names so why the dupe?

Others appear to be versions;

```<code>[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/javax.inject/javax.inject/jars/javax.inject-1.jar:javax/inject/Named.class
[error] /home/hadoop/.ivy2/cache/org.glassfish.hk2.external/javax.inject/jars/javax.inject-2.4.0-b34.jar:javax/inject/Named.class
</code>```

Some have a same filename but are different paths/jars...

```<code>[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/org.apache.arrow/arrow-format/jars/arrow-format-0.10.0.jar:git.properties
[error] /home/hadoop/.ivy2/cache/org.apache.arrow/arrow-memory/jars/arrow-memory-0.10.0.jar:git.properties
[error] /home/hadoop/.ivy2/cache/org.apache.arrow/arrow-vector/jars/arrow-vector-0.10.0.jar:git.properties
</code>```

Same with these...

```<code>[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/org.apache.spark/spark-catalyst_2.11/jars/spark-catalyst_2.11-2.4.3.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /home/hadoop/.ivy2/cache/org.apache.spark/spark-core_2.11/jars/spark-core_2.11-2.4.3.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /home/hadoop/.ivy2/cache/org.apache.spark/spark-graphx_2.11/jars/spark-graphx_2.11-2.4.3.jar:org/apache/spark/unused/UnusedStubClass.class
</code>```

For reference, some other info

imports into my scala object

```<code>import org.apache.spark.sql.SparkSession
import java.time.LocalDateTime
import com.amazonaws.regions.Regions
import com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder
import com.amazonaws.services.secretsmanager.model.GetSecretValueRequest
import org.json4s.{DefaultFormats, MappingException}
import org.json4s.jackson.JsonMethods._
import com.datarobot.prediction.spark.Predictors.{getPredictorFromServer, getPredictor}
</code>```

My build.sbt

```<code>libraryDependencies ++= Seq(
  "net.snowflake" % "snowflake-jdbc" % "3.12.5",
  "net.snowflake" % "spark-snowflake_2.11" % "2.7.1-spark_2.4",
  "com.datarobot" % "scoring-code-spark-api_2.4.3" % "0.0.19",
  "com.datarobot" % "datarobot-prediction" % "2.1.4",
  "com.amazonaws" % "aws-java-sdk-secretsmanager" % "1.11.789",
  "software.amazon.awssdk" % "regions" % "2.13.23"
)
</code>```

Thoughts?  Please advise.

答:
You will need a mergeStrategy setup (docs).

"Random example:"

assemblyMergeStrategy in assembly := {
  case PathList("META-INF", _)       => MergeStrategy.discard
  case PathList("git.properties", _) => MergeStrategy.discard
  case "application.conf"            => MergeStrategy.concat
  case "reference.conf"              => MergeStrategy.concat
  case _                             => MergeStrategy.first
}
```

Body:
I'm on an AWS EMR cluster I just stood up, have a scala file compiles and one which I would like to build into an assembly.  However, when I issue sbt assembly I run into deduplicate errors.

Per https://medium.com/@tedherman/compile-scala-on-emr-cb77610559f0 I originally had a symbolic link for my lib to usr lib spark jars;

ln -s /usr/lib/spark/jars lib

although I've noticed my code passes an sbt compile with or without this.  I am confused why/how to resolve sbt assembly dupe errors however.  I'll also note that I install sbt in bootstrap actions as per the article.

With the symbolic link in

Some dedupes appear to be clear exact dupes; example:

[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/org.apache.parquet/parquet-jackson/jars/parquet-jackson-1.10.1.jar:shaded/parquet/org/codehaus/jackson/util/CharTypes.class
[error] /usr/lib/spark/jars/parquet-jackson-1.10.1-spark-amzn-1.jar:shaded/parquet/org/codehaus/jackson/util/CharTypes.class

Others seem to be competing versions;

[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/org.apache.spark/spark-core_2.11/jars/spark-core_2.11-2.4.3.jar:org/spark_project/jetty/util/MultiPartOutputStream.class
[error] /usr/lib/spark/jars/spark-core_2.11-2.4.5-amzn-0.jar:org/spark_project/jetty/util/MultiPartOutputStream.class

I don't understand why there are competing versions; or if they are by default like this or I did something to introduce them.

Without the symbolic link

I thought if I removed this, I would have less problems; although I still have dupes (just less);

[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/org.apache.hadoop/hadoop-yarn-api/jars/hadoop-yarn-api-2.6.5.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] /home/hadoop/.ivy2/cache/org.apache.hadoop/hadoop-yarn-common/jars/hadoop-yarn-common-2.6.5.jar:org/apache/hadoop/yarn/factory/providers/package-info.class

I don't understand why the above is a dupe considering one is hadoop-yarn-api-2.6.5.jar and the other is hadoop-yarn-common-2.6.5.jar.  Different names so why the dupe?

Others appear to be versions;

[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/javax.inject/javax.inject/jars/javax.inject-1.jar:javax/inject/Named.class
[error] /home/hadoop/.ivy2/cache/org.glassfish.hk2.external/javax.inject/jars/javax.inject-2.4.0-b34.jar:javax/inject/Named.class

Some have a same filename but are different paths/jars...

[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/org.apache.arrow/arrow-format/jars/arrow-format-0.10.0.jar:git.properties
[error] /home/hadoop/.ivy2/cache/org.apache.arrow/arrow-memory/jars/arrow-memory-0.10.0.jar:git.properties
[error] /home/hadoop/.ivy2/cache/org.apache.arrow/arrow-vector/jars/arrow-vector-0.10.0.jar:git.properties

Same with these...

[error] deduplicate: different file contents found in the following:
[error] /home/hadoop/.ivy2/cache/org.apache.spark/spark-catalyst_2.11/jars/spark-catalyst_2.11-2.4.3.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /home/hadoop/.ivy2/cache/org.apache.spark/spark-core_2.11/jars/spark-core_2.11-2.4.3.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /home/hadoop/.ivy2/cache/org.apache.spark/spark-graphx_2.11/jars/spark-graphx_2.11-2.4.3.jar:org/apache/spark/unused/UnusedStubClass.class

For reference, some other info

imports into my scala object

import org.apache.spark.sql.SparkSession
import java.time.LocalDateTime
import com.amazonaws.regions.Regions
import com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder
import com.amazonaws.services.secretsmanager.model.GetSecretValueRequest
import org.json4s.{DefaultFormats, MappingException}
import org.json4s.jackson.JsonMethods._
import com.datarobot.prediction.spark.Predictors.{getPredictorFromServer, getPredictor}

My build.sbt

libraryDependencies ++= Seq(
  "net.snowflake" % "snowflake-jdbc" % "3.12.5",
  "net.snowflake" % "spark-snowflake_2.11" % "2.7.1-spark_2.4",
  "com.datarobot" % "scoring-code-spark-api_2.4.3" % "0.0.19",
  "com.datarobot" % "datarobot-prediction" % "2.1.4",
  "com.amazonaws" % "aws-java-sdk-secretsmanager" % "1.11.789",
  "software.amazon.awssdk" % "regions" % "2.13.23"
)

Thoughts?  Please advise.


问:
How to install gdal using conda in Windows 10 with python 3.7? After I installed geoviews I´ve never managed to use gdal again
I had to install the geoviews package, which install geopandas and downgraded my gdal version in a way I lost the driver for jp2 files (ECWJPEG2000). I tryed to re-install and I´ve never managed to use again. I use conda for installing and nothing happens. I get a message on the shell saying that the instalation was done, but nothing happens. I can´t import gdal at all. If I use pip for installing, I have a huge error message in red saying that there´s something with the visual studio cl.exe. But the file is there, and visual studio is already whithin my enviromnetal variables. I already reinstall OSGEO4W but it didn´t work. </p>

答: First, you can try to install gdal from the wheels file here. Here is another website that walks you through installing all of the other dependencies for geopandas. You will see that for gdal, you will also have to modify your windows path variable to be able to use it from the command line. This could be a reason that your gdal installation is not complete.</p>


问:
iOS XML parsing on main or background thread
When parsing XML in Objective-C on an iOS app, when can the main thread be used and when should the parsing happen on a background thread? Can the main thread handle SAX parsing on small documents, or should all XML parsing happen in the background?

答: I normally do all of my data processing on a background thread. This ensures that the UI thread isn't blocked at any point in time by whatever I'm doing. </p>

ContentLicense: CC BY-SA 3.0


问:
Embedding multiple very large video files
For an web app, basically an art project, I want do a thing.

A fixed set of 8 24-hours-long videos are to be viewed simultaneously. 7 of them in thumbnail size, and one as almost-fullscreen. The user is able to switch out the fullscreen video for another.
After 24 hours, they loop around.

Each video is in sync with the time of the day and cannot be skipped, so that if you're visiting the website on 10:09:08, all the videos should start as well on 10:09:08. So no pausing or seeking.

Due to the massive size the video files would have, I am not sure which way would be a good one to approach this project. Just puting them in a <video> tag will not be a good user experience due to loading times, I assume.

Fast reactivity of the switching action is key; switching without delay or as little as possible loading time. The quality of the 7 small videos can be reduced, but the big one should be primarely as good as possible.
Additionally, it should be mobile and desktop friendly.

What kind of services do i need - is google cloud storage smart for these video files?

Adaptive Streaming by DASH.js seems to be a good solution for all Desktops, but its not made for mobile browsers. Is there a ready-made solution around? Should I just use a service for that (throwing a bit money around is an option)? Or can the youtube API, or even plain youtube iframes handle something like this? This would feel like a terrible hack.

Thank you very very much for any input!

答: HLS format is what you should use - the browser will just load the actual files on demand that you need. Specifically, it lets you specify timestamps in the m3u8 files as timestamps, so seeking should be easier. HLS also breaks up the actual video segments into smaller chunks, and you can store in S3 / cloud storage. hls.js is an option for external library that works desktop + mobile, though being able to combine video on page instead of going auto-fullscreen may dependent on mobile device. What I think you should do for thumbnails is create 1 video that has those streams tiled, then use  elements to arrange those streams on the screen. You can then load the different large video streams on demand (also HLS - could even be different levels in the same m3u8 if you want to be fancy).</p>


问:
Puppeteer iterate div and then from result, iterate child element
I want to return an object from the HTML as below:

HTML

```<code><div id="collection">
  <div class="div">
    <h1 class="title">Title 1</h1>
    <ul class="list">
      <li>list item 1</li>
      <li>list item 2</li>
      <li>list item 3</li>
    </ul>
  </div>
  <div class="div">
    <h1 class="title">Title 2</h1>
    <ul class="list">
      <li>list item 1a</li>
      <li>list item 2a</li>
      <li>list item 3a</li>
      <li>list item 4a</li>
    </ul>
  </div>
  <div class="div">
    <h1 class="title">Title 3</h1>
  </div>
</div>
</code>```

Required result:

```<code>{
  title: "Title 1",
  list:{
    item: "list item 1",
    item: "list item 2",
    item: "list item 3"
  }
},
{
  title: "Title 2",
  list:{
    item: "list item 1a",
    item: "list item 2a",
    item: "list item 3a",
    item: "list item 4a"
  }
},
{
  title: "Title 3",
  list:{}
}

</code>```

So far I have:

```<code>const result = await page.$$eval('div.div, (divs) => divs.map((div) => {
   return {
      title: div.querySelector('.title').innerText,
   }
}));
console.log(result)
</code>```

I am unsure on how I can use page.$$eval to then iterate another element; in this case the ul.
Any help would be appreciated.

Thanks

答:
try to do the following on your puppeteer script, i think it might work:

const values = await page.evaluate(() => {
    const titles = Array.from(document.querySelectorAll('.title')).map(el => el.innerText); // this will get you an array with the titles
    const list = Array.from(document.querySelectorAll('.list')).map(el => Array.from(el.children).map(elm => elm.innerText));

    const endArray = titles.map((el, index) => {
      return {
        title: el,
        list: list[index],
      }
    })

    return endArray;
});
```

You cannot have an object with repeated attributes as you're trying to do. It's a better practice to define your list as an array, since you know your list has a repeated type of data.

Body:
I want to return an object from the HTML as below:

HTML

Title 1

list item 1

list item 2

list item 3

Title 2

list item 1a

list item 2a

list item 3a

list item 4a

Title 3

Required result:

{
  title: "Title 1",
  list:{
    item: "list item 1",
    item: "list item 2",
    item: "list item 3"
  }
},
{
  title: "Title 2",
  list:{
    item: "list item 1a",
    item: "list item 2a",
    item: "list item 3a",
    item: "list item 4a"
  }
},
{
  title: "Title 3",
  list:{}
}

So far I have:

const result = await page.$$eval('div.div, (divs) => divs.map((div) => {
   return {
      title: div.querySelector('.title').innerText,
   }
}));
console.log(result)

I am unsure on how I can use page.$$eval to then iterate another element; in this case the ul.
Any help would be appreciated.

Thanks

Body:
try to do the following on your puppeteer script, i think it might work:

const values = await page.evaluate(() => {
    const titles = Array.from(document.querySelectorAll('.title')).map(el => el.innerText); // this will get you an array with the titles
    const list = Array.from(document.querySelectorAll('.list')).map(el => Array.from(el.children).map(elm => elm.innerText));

    const endArray = titles.map((el, index) => {
      return {
        title: el,
        list: list[index],
      }
    })

    return endArray;
});

You cannot have an object with repeated attributes as you're trying to do. It's a better practice to define your list as an array, since you know your list has a repeated type of data.


问:
Another way to change the name of a table in Laravel using App\Models\XXX name
Simple question...
I can change the name of a table in a query like this:

```<code>$users = DB::table('users AS u')->select('name');
</code>```

Can i do it in some way like this?

```<code>$users = App\Models\Users::select('name')->get();
</code>```

答:
You can do it (source),

```<code>App\Models\Users::from( 'users as u' )
    ->select( 'name' )
    ->get();
</code>```

To get the name directly from the table (source),

```<code>$users = new Users;
$table = $users->getTable();
print_r($table);
</code>```

Body:
Simple question...
I can change the name of a table in a query like this:

$users = DB::table('users AS u')->select('name');

Can i do it in some way like this?

$users = App\Models\Users::select('name')->get();

Body:
You can do it (source),

App\Models\Users::from( 'users as u' )
    ->select( 'name' )
    ->get();

To get the name directly from the table (source),

$users = new Users;
$table = $users->getTable();
print_r($table);


问:
Reset switch case value so they can enter menu input again Java
I am using a switch statement which worked fine. But if something like an exception occurs inside the switch I want the program to return to ask for the users selection again.

I'll share some example code:

```<code>while (valid != true)
{
    System.out.println("Enter a Choice \n1. Choice 1. \n2. Choice 2. \n3. Choice 3.");
    int choice = getChoice();      //Get choice just returns an integer from user input.

    switch (choice)
    {
        case 1:
            //Do something
            valid = true;
            break;

        case 2:
            //Do something
            valid = true;
            break;

        case 3:
            //Do something
            valid = true;
            break;

        default:
            System.out.println("Invalid Choice.");
    }
</code>```

So if something went wrong and validChoice wasn't set to true. I want the user to be able to re-enter the choice but since the choice is already set. It will go to case 3 straight away.

Some things ive tried include:

All of these would be done if something goes wrong.

Setting choice to null for if it goes wrong. (Was hopeful that this would work) but java doesn't allow

Setting choice to 0 would just make it go to the default case.

答:
Try this : </p>

```<code>            do {
                 System.out.println("Enter a Choice \n1. Choice 1. \n2. Choice 2. \n3. Choice 3.");
    int choice = getChoice();      //Get choice just returns an integer from user input.

    switch (choice)
    {
        case 1:
            //Do something
            valid = true;
            break;

        case 2:
            //Do something
            valid = true;
            break;

        case 3:
            //Do something
            valid = true;
            break;

        default:
            System.out.println("Invalid Choice.");
            break;
    }

            } while (valid != true);
}
}
</code>```

Body:
I am using a switch statement which worked fine. But if something like an exception occurs inside the switch I want the program to return to ask for the users selection again.

I'll share some example code:

while (valid != true)
{
    System.out.println("Enter a Choice \n1. Choice 1. \n2. Choice 2. \n3. Choice 3.");
    int choice = getChoice();      //Get choice just returns an integer from user input.

    switch (choice)
    {
        case 1:
            //Do something
            valid = true;
            break;

        case 2:
            //Do something
            valid = true;
            break;

        case 3:
            //Do something
            valid = true;
            break;

        default:
            System.out.println("Invalid Choice.");
    }

So if something went wrong and validChoice wasn't set to true. I want the user to be able to re-enter the choice but since the choice is already set. It will go to case 3 straight away.

Some things ive tried include:

All of these would be done if something goes wrong.

Setting choice to null for if it goes wrong. (Was hopeful that this would work) but java doesn't allow

Setting choice to 0 would just make it go to the default case.

Body:
Try this :

            do {
                 System.out.println("Enter a Choice \n1. Choice 1. \n2. Choice 2. \n3. Choice 3.");
    int choice = getChoice();      //Get choice just returns an integer from user input.

    switch (choice)
    {
        case 1:
            //Do something
            valid = true;
            break;

        case 2:
            //Do something
            valid = true;
            break;

        case 3:
            //Do something
            valid = true;
            break;

        default:
            System.out.println("Invalid Choice.");
            break;
    }

            } while (valid != true);
}
}


问:
How to calculate the average of an element in the array (salary) in C#
what else do I need to add or change to display my employees between the ages of 25 and 35
years with a higher salary than average salary. This program only displays employees between the ages of 25 and 35.</p>

```<code>        for (int i = 0; i < employeename; i++)
         {
            while (br.PeekChar() != -1)
            {
                function[i].Name= br.ReadString();
                function[i].Function= br.ReadString();
                function[i].Age= br.ReadInt32();
                function[i].salary= br.ReadInt32();
                function[i].Studies= br.ReadString();

                if ((function[i].Age>25) && (function[i].Age<35))
                {
                    string str = String.Format("|{0,-21}|{1,-9}|{2,-7}|{3,-16}|{4,-12}|", function[i].Name, function[i].Function,
                        function[i].Age.ToString(), function[i].Salary.ToString(), function[i].Studies);
                    Console.WriteLine(str);
                }

            }

        }
        Console.ReadKey();
        br.Close();
</code>```

答:
best way this :
first read all and add to a list then do other operation on list

here it is a sample!

```<code>sing System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            List<Employee> employees = new List<Employee>();

            for (int i = 0; i < 10; i++)
            {
                employees.Add(new Employee
                {
                    Name ="name "+i,
                    Function = "fun "+i,
                    Age =i+24,
                    Salary =100+i,
                    Studies ="stu"+i
                });
            }

            //here can do any opr on list
            double avg =employees.Average(s => s.Salary);
            var result = employees.Where(x => x.Age > 25 && x.Age < 35 && x.Salary> avg).ToList();

            foreach (var item in result)
            {
                Console.WriteLine("item name:" + item.Name);

            }

            Console.WriteLine("avg :" + avg);
            Console.ReadKey();
        }

        public class Employee
        {
            public string Name { set; get; }
            public string Function { set; get; }
            public int Salary { set; get; }
            public int Age { set; get; }
            public string Studies { set; get; }

        }
    }
}
</code>```

Body:
what else do I need to add or change to display my employees between the ages of 25 and 35
years with a higher salary than average salary. This program only displays employees between the ages of 25 and 35.

        for (int i = 0; i < employeename; i++)
         {
            while (br.PeekChar() != -1)
            {
                function[i].Name= br.ReadString();
                function[i].Function= br.ReadString();
                function[i].Age= br.ReadInt32();
                function[i].salary= br.ReadInt32();
                function[i].Studies= br.ReadString();

                if ((function[i].Age>25) && (function[i].Age<35))
                {
                    string str = String.Format("|{0,-21}|{1,-9}|{2,-7}|{3,-16}|{4,-12}|", function[i].Name, function[i].Function,
                        function[i].Age.ToString(), function[i].Salary.ToString(), function[i].Studies);
                    Console.WriteLine(str);
                }

            }

        }
        Console.ReadKey();
        br.Close();

Body:
best way this :
first read all and add to a list then do other operation on list

here it is a sample!

sing System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            List<Employee> employees = new List<Employee>();

            for (int i = 0; i < 10; i++)
            {
                employees.Add(new Employee
                {
                    Name ="name "+i,
                    Function = "fun "+i,
                    Age =i+24,
                    Salary =100+i,
                    Studies ="stu"+i
                });
            }

            //here can do any opr on list
            double avg =employees.Average(s => s.Salary);
            var result = employees.Where(x => x.Age > 25 && x.Age < 35 && x.Salary> avg).ToList();

            foreach (var item in result)
            {
                Console.WriteLine("item name:" + item.Name);

            }

            Console.WriteLine("avg :" + avg);
            Console.ReadKey();
        }

        public class Employee
        {
            public string Name { set; get; }
            public string Function { set; get; }
            public int Salary { set; get; }
            public int Age { set; get; }
            public string Studies { set; get; }

        }
    }
}


问:
Dokan Add new product not saving custom field in backend
My task is to add customer field to Add new product Vendor option. I successfully added this field to frontend tmpl-add-product-popup.php with code:

```<code><!-- Novo polje: Kolicina jednog pakovanja*/ -->
                        <div class="dokan-form-group">
                            <div> Količina jednog pakovanja (neobavezno)</div>
                            <div style = "color:gray;font-size:10px;"> L - litar, ml - Mililitar, Kg - Kilogram, g - Gram</div>
                            <div class="dokan-input-group">
                                <input class="dokan-form-control" name="_new_field" id="_new_field" type="text" placeholder="Primjer: 1L ili 500g" value="<?php echo dokan_posted_input( '_new_field' ); ?>">
                            </div>
                        </div>

</code>```

and modified functions.php:

```<code>add_action( ‘woocommerce_product_options_general_product_data’, ‘x_add_fields’ );
function x_add_fields() {

global $woocommerce, $post;

echo ‘<div class=”options_group”>’;

// Number Field
woocommerce_wp_text_input(
array(
‘id’ => ‘_new_field’,
‘label’ => __( ‘New Field’, ‘woocommerce’ ),
‘placeholder’ => ”,
‘description’ => __( ‘Primjer= 1L, 500ml, 1Kg’, ‘woocommerce’ ),
‘type’ => ‘number’,
‘custom_attributes’ => array(
‘step’ => ‘any’,
‘min’ => ‘0’
)
)
);

echo ‘</div>’;

}

// Save Fields
add_action( ‘woocommerce_process_product_meta’, ‘x_add_fields_save’ );
add_action( ‘dokan_process_product_meta’, ‘x_add_fields_save’ );
add_action( ‘dokan_new_product_added’, ‘x_add_fields_save’ );

function x_add_fields_save( $post_id ){

// Number Field
$woocommerce_new_field = $_POST[‘_new_field’];
if( !empty( $woocommerce_new_field) )
update_post_meta( $post_id, ‘_new_field’, esc_attr( $woocommerce_new_field ) );

}
</code>```

When I try to post new product this new field is not saved for Product. What am I missing here?

Thanks,
Dejan

答: And for some reason this happens only in tmpl-add-product-popup.php. If I use same logic for new-product.php it works fine.</p>

Body:
My task is to add customer field to Add new product Vendor option. I successfully added this field to frontend tmpl-add-product-popup.php with code:

 Količina jednog pakovanja (neobavezno)

 L - litar, ml - Mililitar, Kg - Kilogram, g - Gram

                                <input class="dokan-form-control" name="_new_field" id="_new_field" type="text" placeholder="Primjer: 1L ili 500g" value="<?php echo dokan_posted_input( '_new_field' ); ?>">

and modified functions.php:

add_action( ‘woocommerce_product_options_general_product_data’, ‘x_add_fields’ );
function x_add_fields() {

global $woocommerce, $post;

echo ‘
’;

// Number Field
woocommerce_wp_text_input(
array(
‘id’ => ‘_new_field’,
‘label’ => __( ‘New Field’, ‘woocommerce’ ),
‘placeholder’ => ”,
‘description’ => __( ‘Primjer= 1L, 500ml, 1Kg’, ‘woocommerce’ ),
‘type’ => ‘number’,
‘custom_attributes’ => array(
‘step’ => ‘any’,
‘min’ => ‘0’
)
)
);

echo ‘
’;

}

// Save Fields
add_action( ‘woocommerce_process_product_meta’, ‘x_add_fields_save’ );
add_action( ‘dokan_process_product_meta’, ‘x_add_fields_save’ );
add_action( ‘dokan_new_product_added’, ‘x_add_fields_save’ );

function x_add_fields_save( $post_id ){

// Number Field
$woocommerce_new_field = $_POST[‘_new_field’];
if( !empty( $woocommerce_new_field) )
update_post_meta( $post_id, ‘_new_field’, esc_attr( $woocommerce_new_field ) );

}

When I try to post new product this new field is not saved for Product. What am I missing here?

Thanks,
Dejan


问:
jQuery not showing correctly in aspx page
I'm trying to get this function to work in an aspx page but I'm having a rotten time.  Basically it works fine in a regular HTML page but in the aspx page, when click on the button all you can see is a sliver of the top part and on occasion (every 5th+ single button click & every double click) the message shows and fades like it should.  What am I missing?  Could it be getting tied up in the postback?

FIDDLE HERE

Code using in aspx page

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="checkTest.aspx.cs" Inherits="WebApplication2.checkTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#Button1").click(function () {
                    $(".message").stop(true,true).slideToggle().fadeOut(6000);
                });
            });
        </script>
    <style type="text/css">
    .message{height:70px;display:none;}
        .noChangesMessage{width:84px;padding:8px 8px;  background:#535353; -webkit-border-radius:5px; -moz-border-radius:5px; border-radius:5px; color:white;text-align:center;}
        .tipEnd{width:0;height:0;border-left:10px solid transparent;border-right:10px solid transparent;border-top:10px solid #535353;margin:0 auto;}

    </style>
</head>
<body>
    <form id="form1" runat="server">

    <br /><br /><br />
    <div>
    <div style="width:100px">
    <div style="height:70px">
                <div style="margin-bottom:5px;" class="message">
                    <div class="noChangesMessage">No changes were made!</div>
                    <div class="tipEnd"></div>
                </div></div>
            <div style="">
                <asp:Button ID="Button1" runat="server" Text="Save Changes"  />
            </div>
            </div>

    </div>

    </form>
</body>
</html>
</code>```

my code via view source for amit_g

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#Button1").click(function () {
                    $(".message").stop(true,true).slideToggle().fadeOut(6000);
                });
            });
        </script>
    <style type="text/css">.
    .message{height:70px;display:none;}
        .noChangesMessage{width:84px;padding:8px 8px;  background:#535353; -webkit-border-radius:5px; -moz-border-radius:5px; border-radius:5px; color:white;text-align:center;}
        .tipEnd{width:0;height:0;border-left:10px solid transparent;border-right:10px solid transparent;border-top:10px solid #535353;margin:0 auto;}
    </style>
</head>
<body>
    <form method="post" action="checkTest.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMjA0OTM4MTAwNGRkU+SP3bu4QJNH9S9XtdwPbEE8YODY/YlkotOt6l692s8=" />
</div>
<div class="aspNetHidden">
    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgKroLr3AwKM54rGBtLTfCTwYmYnb6l8tnp5jtojhvORYMJ6bPzAI+qbaDlU" />
</div>
    <br /><br /><br />
    <div>
    <div style="width:100px">
    <div style="height:70px">
                <div style="margin-bottom:5px;" class="message">
                    <div class="noChangesMessage">No changes were made!</div>
                    <div class="tipEnd"></div>
                </div></div>
            <div style="">
                <input type="submit" name="Button1" value="Save Changes" id="Button1" class="Button1" /></div>
            </div>
    </div>
    </form>
</body>
</html>
</code>```

答:
Try this:</p>

```<code>$("#<%= Button1.ClientID %>").click(function () {
   $(".message").stop(true,true).slideToggle().fadeOut(6000);}
);
</code>```

Body:
I'm trying to get this function to work in an aspx page but I'm having a rotten time.  Basically it works fine in a regular HTML page but in the aspx page, when click on the button all you can see is a sliver of the top part and on occasion (every 5th+ single button click & every double click) the message shows and fades like it should.  What am I missing?  Could it be getting tied up in the postback?

FIDDLE HERE

Code using in aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="checkTest.aspx.cs" Inherits="WebApplication2.checkTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

No changes were made!

                <asp:Button ID="Button1" runat="server" Text="Save Changes"  />

    </form>

my code via view source for amit_g

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>
</title>

    <form method="post" action="checkTest.aspx" id="form1">

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMjA0OTM4MTAwNGRkU+SP3bu4QJNH9S9XtdwPbEE8YODY/YlkotOt6l692s8=" />

    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgKroLr3AwKM54rGBtLTfCTwYmYnb6l8tnp5jtojhvORYMJ6bPzAI+qbaDlU" />

No changes were made!

                <input type="submit" name="Button1" value="Save Changes" id="Button1" class="Button1" />

    </form>

Body:
Try this:

$("#<%= Button1.ClientID %>").click(function () {
   $(".message").stop(true,true).slideToggle().fadeOut(6000);}
);


问:
Deriving time complexity from runtime analysis
As a non computer scientist I find it a bit hard to understand time complexity and the way it is calculated, So my question is if it is possible for the time complexity of a certain algorithm / program be derived from running it on increasingly large input data, and then look at how runtime changes relative to the  increase in the input size n.

I'm asking this because I wrote an algorithm in C++ which basically does pixel shading on 2D images using  a single cpu core and a single thread (3GHZ processor). I measured the runtime on input sizes from 2^4 up to 2^30 which is a matrix of size  32,768 ** 2. Now I have this plot of how my runtime behaves as a function of my input size n:

So for the input size of n = 2^4 to 2^30 the exact runtimes were(by row):

```<code> [1]  0.000  0.000  0.000  0.000  0.000  0.000  0.000
 [8]  0.000  0.000  0.000  0.000  0.001  0.000  0.000
[15]  0.002  0.004  0.013  0.018  0.053  0.079  0.231
[22]  0.358  0.963  1.772  4.626  9.713 25.582
</code>```

Now this is a bit strange, because when The power of 2 changes from an Odd to an even, the runtime is increased by just 1.5, but when it changes from even to an Odd, the runtime triples.  So, when I double my input, my runtime increases by an average multiple of (3 + 1.5) / 2 = 2.25. In fact, it seems as though when n becomes arbitrarily large, both changes in the power argument from Odd to even and even to Odd cause runtime to be multiplied by a constant of 2.25, in other words: as n becomes larger, the runtime multiplier converges to 2.25.

If my algorithm is quite complex, is there a way to say something about its time complexity from this analysis?

答:
Having C(4 * n) = (1.5 * 3) * C(n) suggest that you have a complexity in O(n^1.08) --
where 1.08 ~ log(4.5)/log(4).

Of course it's just a hint and we can prove nothing asymptotically.

Body:
As a non computer scientist I find it a bit hard to understand time complexity and the way it is calculated, So my question is if it is possible for the time complexity of a certain algorithm / program be derived from running it on increasingly large input data, and then look at how runtime changes relative to the  increase in the input size n.

I'm asking this because I wrote an algorithm in C++ which basically does pixel shading on 2D images using  a single cpu core and a single thread (3GHZ processor). I measured the runtime on input sizes from 2^4 up to 2^30 which is a matrix of size  32,768 ** 2. Now I have this plot of how my runtime behaves as a function of my input size n:

So for the input size of n = 2^4 to 2^30 the exact runtimes were(by row):

 [1]  0.000  0.000  0.000  0.000  0.000  0.000  0.000
 [8]  0.000  0.000  0.000  0.000  0.001  0.000  0.000
[15]  0.002  0.004  0.013  0.018  0.053  0.079  0.231
[22]  0.358  0.963  1.772  4.626  9.713 25.582

Now this is a bit strange, because when The power of 2 changes from an Odd to an even, the runtime is increased by just 1.5, but when it changes from even to an Odd, the runtime triples.  So, when I double my input, my runtime increases by an average multiple of (3 + 1.5) / 2 = 2.25. In fact, it seems as though when n becomes arbitrarily large, both changes in the power argument from Odd to even and even to Odd cause runtime to be multiplied by a constant of 2.25, in other words: as n becomes larger, the runtime multiplier converges to 2.25.

If my algorithm is quite complex, is there a way to say something about its time complexity from this analysis?


问:
Does this code use the Proxy or Singleton pattern, or both of them?
```<code>public interface SomeObject {
    void process();
}

public class SomeObjectImpl implements SomeObject {

    public SomeObjectImpl() {
        ...
    }

    @Override
    public void process() {
        ...
    }
}

public class AnotherObject implements SomeObject {
    private SomeObject object;

    @Override
    public void process() {
        if (object == null) {
            object = new SomeObjectImpl();
        }
        object.process();
    }
}

</code>```

I think it's the Singleton pattern because it states that a class must ensure that only a single instance should be created and a single object can be used by all other classes. In the example, when SomeObject is null an instance is created as required.

However, it also looks like the Proxy pattern is used, because SomeObject is the proxy.

Is this code really using both patterns? Or is the Proxy pattern used only?

答:
The Singleton Pattern's purpose is to ensure that only one instance of the singleton class ever exists.

Does the given code ensure that? No, because nothing prevents you from creating as many instances as you like from the two classes SomeObjectImpl and AnotherObject (by just invoking their default constructor).

Hint: See the Wikipedia page on Singleton Pattern for implementation examples in different languages... and once you've seen how to create singletons – then forget about using them in real code, ever – as it's the best way for creating untestable software ⚡ and having global variable(s) ⚡ gluing everything together.

The Proxy Pattern's purpose is to control the access to an object or to provide some additional functionality upon accessing an object.

Does the given code look something like that? Yes.

The two classes SomeObjectImpl and AnotherObject implement the interface SomeObject. That interface (in terms of the Proxy Pattern) represents the Subject providing some action, i.e. the process method. The SomeObjectImpl class is then the acutal implementation; the RealSubject (as named by the Proxy Pattern). While AnotherObject class simply delegates to the actual implemenation SomeObjectImpl, i.e. it's a Proxy.

Given that code, the Proxy's purpose (or additional functionality) is to cache an instance of SomeObjectImpl for subsequent process calls. This makes sense when the object creation is a costly operation. For example, when the process method implementation requires the setup of some external resources or requires "big" upfront memory allocations,  ...

Body:
public interface SomeObject {
    void process();
}

public class SomeObjectImpl implements SomeObject {

    public SomeObjectImpl() {
        ...
    }

    @Override
    public void process() {
        ...
    }
}

public class AnotherObject implements SomeObject {
    private SomeObject object;

    @Override
    public void process() {
        if (object == null) {
            object = new SomeObjectImpl();
        }
        object.process();
    }
}

I think it's the Singleton pattern because it states that a class must ensure that only a single instance should be created and a single object can be used by all other classes. In the example, when SomeObject is null an instance is created as required.

However, it also looks like the Proxy pattern is used, because SomeObject is the proxy.

Is this code really using both patterns? Or is the Proxy pattern used only?


问:
Is there a way to iterate through node.run_state data in a Chef recipe?
Is there a way to iterate through node.run_state data?
This is in a RHEL environment with Active Directory users.
I have a ruby block that populates node.run_state.  I have to have this run at converge time, because the overall cookbook will be used for build automation.  On the very first run, the cookbook installs Centrify, then later needs to run adquery to gather user info for populating home directories with SSH keys.

On a chef-client run, I see this:

```<code>       Compiling Cookbooks...
       {}
</code>```

Obviously, that's the puts running in compile time against an empty hash.
At converge time, nothing happens in the loop with the 2 directory and 1 template resource.

Here is the relevant piece of the recipe:

```<code>ruby_block 'set uid, gid, and homedir for users' do
  block do
    base_attr['ssh_keys'].each do |user, pubkeys|
  # next unless Dir.exist?(homedir)
      node.run_state[user] = {}
      puts "Checking user #{user}..."
      if local_users.key?(user)
        node.run_state[user]['homedir'] = local_users[user]['homedir']
        node.run_state[user]['uid'] = local_users[user]['uid'].to_i
        node.run_state[user]['gid'] = local_users[user]['gid'].to_i
      elsif centrify_users.key?(user)
        node.run_state[user]['homedir'] = centrify_users[user]['homedir']
        node.run_state[user]['uid'] = centrify_users[user]['uid'].to_i
        node.run_state[user]['gid'] = centrify_users[user]['gid'].to_i
      else
        puts "user #{user} not found."
        # Place holder values.
        node.run_state[user]['homedir'] = "/tmp/#{user}"
        node.run_state[user]['uid'] = 0
        node.run_state[user]['gid'] = 0
      end
    end
  end
end
  # Dir.exist? guard should bypass compile-time error.
  # "name is a required property"
  # next unless Dir.exist?(homedir)
puts node.run_state
node.run_state.each do |user|
  directory node.run_state[user]['homedir'] do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0700'
  end

  directory "#{node.run_state[user]['homedir']}/.ssh" do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0700'
  end

  template "#{node.run_state[user]['homedir']}/.ssh/authorized_keys" do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0600'
    source 'authorized_keys.erb'
    variables(
      sshkeys: base_attr['ssh_keys'][user]
    )
  end
end
</code>```

Any ideas how to make this work?

答: My subconscious mind told me this morning to pull the path inside the directory resource, and THEN use lazy on it.  So I have the working solution.  node.run_state in the ruby_block, and lazy blocks around the requisite attributes in the subsequent resources that use node.run_state.  Thanks for the feedback on this issue.</p>

Body:
Is there a way to iterate through node.run_state data?
This is in a RHEL environment with Active Directory users.
I have a ruby block that populates node.run_state.  I have to have this run at converge time, because the overall cookbook will be used for build automation.  On the very first run, the cookbook installs Centrify, then later needs to run adquery to gather user info for populating home directories with SSH keys.

On a chef-client run, I see this:

       Compiling Cookbooks...
       {}

Obviously, that's the puts running in compile time against an empty hash.
At converge time, nothing happens in the loop with the 2 directory and 1 template resource.

Here is the relevant piece of the recipe:

ruby_block 'set uid, gid, and homedir for users' do
  block do
    base_attr['ssh_keys'].each do |user, pubkeys|
  # next unless Dir.exist?(homedir)
      node.run_state[user] = {}
      puts "Checking user #{user}..."
      if local_users.key?(user)
        node.run_state[user]['homedir'] = local_users[user]['homedir']
        node.run_state[user]['uid'] = local_users[user]['uid'].to_i
        node.run_state[user]['gid'] = local_users[user]['gid'].to_i
      elsif centrify_users.key?(user)
        node.run_state[user]['homedir'] = centrify_users[user]['homedir']
        node.run_state[user]['uid'] = centrify_users[user]['uid'].to_i
        node.run_state[user]['gid'] = centrify_users[user]['gid'].to_i
      else
        puts "user #{user} not found."
        # Place holder values.
        node.run_state[user]['homedir'] = "/tmp/#{user}"
        node.run_state[user]['uid'] = 0
        node.run_state[user]['gid'] = 0
      end
    end
  end
end
  # Dir.exist? guard should bypass compile-time error.
  # "name is a required property"
  # next unless Dir.exist?(homedir)
puts node.run_state
node.run_state.each do |user|
  directory node.run_state[user]['homedir'] do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0700'
  end

  directory "#{node.run_state[user]['homedir']}/.ssh" do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0700'
  end

  template "#{node.run_state[user]['homedir']}/.ssh/authorized_keys" do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0600'
    source 'authorized_keys.erb'
    variables(
      sshkeys: base_attr['ssh_keys'][user]
    )
  end
end

Any ideas how to make this work?


问:
how can I Crawl prepared url lists
I'm going to crawl the web with python
Save urls information as csv or txt
I want to crawl page by page while loading it in code
How can i do this</p>

```<code>import urllib.request
from bs4 import BeautifulSoup
import pandas as pd

with open('crawlingweb.csv') as f:
    content=f.readlines()
    content=[x.strip() for x in content]

url='#I want to bring url from csv or txt file'
html=urllib.request.urlopen(url).read()
soup=BeautifulSoup(html,'lxml')
text=soup.get_text()
print(text)
</code>```

答:
```<code>import urllib.request
from bs4 import BeautifulSoup
import pandas as pd

with open('crawlingweb.csv') as f:
    content=f.readlines()
    content=[x.strip() for x in content]

for i in range(10):
    url=content[i]
    html=urllib.request.urlopen(url).read()
    soup=BeautifulSoup(html,'lxml')
    text=soup.get_text()
    print(text)
</code>```

Title: how can I Crawl prepared url lists

Body:
I'm going to crawl the web with python
Save urls information as csv or txt
I want to crawl page by page while loading it in code
How can i do this

import urllib.request
from bs4 import BeautifulSoup
import pandas as pd

with open('crawlingweb.csv') as f:
    content=f.readlines()
    content=[x.strip() for x in content]

url='#I want to bring url from csv or txt file'
html=urllib.request.urlopen(url).read()
soup=BeautifulSoup(html,'lxml')
text=soup.get_text()
print(text)


问:
why document.getElementsByName().length always return 0?
I'm new to JavaScript. In the following code getElementsByName("li").length always returns 0 although there are many
-tags in my HTML, why?

```<code>document.addEventListener('DOMContentLoaded', function() {
    var len = document.getElementsByName('li').length;
    alert(len);
})

art of my HTML:

<body>
    <ul>
        <li>aaaaaa</li>
        <li>bbbbbb</li>
        <li>cccccc</li>
    </ul>
</body>
</code>```

答:
You can do something like this because getElementsByTagName() returns NodeList so you can iterate over it like an array or get the length.

document.addEventListener('DOMContentLoaded', function() {
    var listElements = document.getElementById('list').getElementsByTagName("li");
    alert(listElements.length);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <ul id="list">
        <li >aaaaaa</li>
        <li>bbbbbb</li>
        <li>cccccc</li>
    </ul>
</body></code>```

getElementsByName() although also returns NodeList but it returns list of all same name elements in the whole document so to make this work you need to give same name to all list items.

document.addEventListener('DOMContentLoaded', function() {
    var len = document.getElementsByName('name').length;
    alert(len);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <ul>
        <li name="name">aaaaaa</li>
        <li name="name">bbbbbb</li>
        <li name="name">cccccc</li>
    </ul>
</body></code>```

Body:
I'm new to JavaScript. In the following code getElementsByName("li").length always returns 0 although there are many
-tags in my HTML, why?

document.addEventListener('DOMContentLoaded', function() {
    var len = document.getElementsByName('li').length;
    alert(len);
})

art of my HTML:

aaaaaa

bbbbbb

cccccc

Body:
You can do something like this because getElementsByTagName() returns NodeList so you can iterate over it like an array or get the length.

document.addEventListener('DOMContentLoaded', function() {
    var listElements = document.getElementById('list').getElementsByTagName("li");
    alert(listElements.length);
})

<body>
    <ul id="list">
        <li >aaaaaa</li>
        <li>bbbbbb</li>
        <li>cccccc</li>
    </ul>
</body>

getElementsByName() although also returns NodeList but it returns list of all same name elements in the whole document so to make this work you need to give same name to all list items.

document.addEventListener('DOMContentLoaded', function() {
    var len = document.getElementsByName('name').length;
    alert(len);
});

<body>
    <ul>
        <li name="name">aaaaaa</li>
        <li name="name">bbbbbb</li>
        <li name="name">cccccc</li>
    </ul>
</body>


问:
Should I delete a branch after merging it?
After merging a branch, do you delete it from the repository?

Is it a good practice or not?

I usually create a lot of branches, since I don't want to break my current release, and I'd wish to delete them to keep things in order.

However, if you work with Assembla or GitHub, your merge requests from old branches will be saved on the site, so if you delete them you'll get an error since it won't be able to fetch them...

Usually how do manage that?

答:
Just to clarify, branch, from git point of view, is just link onto some commit.
By deleting branch, you will not delete commits from git repo. Of course, detached commits will be cleaned after some time via git garbage collector.

FYI: We're usually merging branches into master via bitbucket interface. There you can set delete feature branch after merge flag.

If you need to deal with too old branches, you could have a look for some utilities. For example, this one might be helpful.


问:
ORA-01036: ILLEGAL VARIABLE NAME/NUMBER while filling the data table
I have a view in oracle DB and i am trying to call it from a method to to bind the data coming from the view to a data table but it raises the exception.

Please help.

Exception is raised in this line ( dataAdapter.Fill(dataTable);)

```<code> private static void ViewSelectedJobHistory(Document imDocument, Job selectedJob)
            {
                DataTable dataTable = new DataTable();
                try
                {
                    if (imDocument != null && selectedJob != null)
                    {
                        //string query =JobResource.QueryJobHistory;
                        //int id=selectedJob.ID;
                        //using (Command imCommand = new Command(query, imDocument.Connection))
                        string query = string.Format("select FID,F_CLASS_NAME,JOB_OPERATION_TYPE,OPERATION_DATE from JOB_EXPLORER_FETCH where JOB_ID={0}",selectedJob.ID);
                            //"select FID,F_CLASS_NAME,JOB_OPERATION_TYPE,OPERATION_DATE from JOB_EXPLORER_FETCH where JOB_ID=34680";
                        string abc = query;
                        using (Command imCommand = new Command(query, imDocument.Connection))
                        {
                            imCommand.Parameters.Add(new DataParameter("1", DbDataType.String, selectedJob.ID.ToString(), ParameterDirection.Input));

                            using (DataAdapter dataAdapter = new DataAdapter(imCommand))
                            {
                                dataAdapter.Fill(dataTable);
                                if (dataTable != null && dataTable.Rows.Count > 0 )
                                {
                                    if (instanceJob == false)
                                    {
                                        ViewSelectedJobHistory viewSelectedJobHistory = new ViewSelectedJobHistory(imDocument, dataTable, selectedJob);
                                        viewSelectedJobHistory.Show();
                                        instanceJob = true;
                                    }
                                }
</code>```

答:
You are attempting to bind the parameters twice, and also are not using the Oracle libraries (guessing because I don't see your connection open code).

The SQL command should look like this:

```<code>string query = "select FID,F_CLASS_NAME,JOB_OPERATION_TYPE,OPERATION_DATE from JOB_EXPLORER_FETCH where JOB_ID=:0";
</code>```

Then when youre adding the parameter, it should replace the :0 with your value.  This is also essential to avoid SQL Injection attacks.  Additionally you should be using an OracleParameter class:

```<code>imCommand.Parameters.Add(new OracleParameter("1", OracleDbType.NVarchar2, 100, selectedJob.ID.ToString(), ParameterDirection.Input));
</code>```

Body:
I have a view in oracle DB and i am trying to call it from a method to to bind the data coming from the view to a data table but it raises the exception.

Please help.

Exception is raised in this line ( dataAdapter.Fill(dataTable);)

 private static void ViewSelectedJobHistory(Document imDocument, Job selectedJob)
            {
                DataTable dataTable = new DataTable();
                try
                {
                    if (imDocument != null && selectedJob != null)
                    {
                        //string query =JobResource.QueryJobHistory;
                        //int id=selectedJob.ID;
                        //using (Command imCommand = new Command(query, imDocument.Connection))
                        string query = string.Format("select FID,F_CLASS_NAME,JOB_OPERATION_TYPE,OPERATION_DATE from JOB_EXPLORER_FETCH where JOB_ID={0}",selectedJob.ID);
                            //"select FID,F_CLASS_NAME,JOB_OPERATION_TYPE,OPERATION_DATE from JOB_EXPLORER_FETCH where JOB_ID=34680";
                        string abc = query;
                        using (Command imCommand = new Command(query, imDocument.Connection))
                        {
                            imCommand.Parameters.Add(new DataParameter("1", DbDataType.String, selectedJob.ID.ToString(), ParameterDirection.Input));

                            using (DataAdapter dataAdapter = new DataAdapter(imCommand))
                            {
                                dataAdapter.Fill(dataTable);
                                if (dataTable != null && dataTable.Rows.Count > 0 )
                                {
                                    if (instanceJob == false)
                                    {
                                        ViewSelectedJobHistory viewSelectedJobHistory = new ViewSelectedJobHistory(imDocument, dataTable, selectedJob);
                                        viewSelectedJobHistory.Show();
                                        instanceJob = true;
                                    }
                                }

Body:
You are attempting to bind the parameters twice, and also are not using the Oracle libraries (guessing because I don't see your connection open code).

The SQL command should look like this:

string query = "select FID,F_CLASS_NAME,JOB_OPERATION_TYPE,OPERATION_DATE from JOB_EXPLORER_FETCH where JOB_ID=:0";

Then when youre adding the parameter, it should replace the :0 with your value.  This is also essential to avoid SQL Injection attacks.  Additionally you should be using an OracleParameter class:

imCommand.Parameters.Add(new OracleParameter("1", OracleDbType.NVarchar2, 100, selectedJob.ID.ToString(), ParameterDirection.Input));


问:
How to dynamically generate file for download in Razor Pages
I want to add a button that will download a dynamically generated CSV file.

I think I need to use FileStreamResult (or possibly FileContentResult) but I have been unable to find an example that shows how to do this.

I've seen examples that create a physical file, and then download that. But my ideal solution would write directly to the response stream, which would be far more efficient than creating a file or first building the string in memory.

Has anyone seen an example of dynamically generating a file for download in Razor Pages (not MVC)?

答:
So here's what I came up with.

Markup:

```<code><a class="btn btn-success" asp-page-handler="DownloadCsv">
    Download CSV
</a>
</code>```

Handler:

```<code>public IActionResult OnGetDownloadCsv()
{
    using MemoryStream memoryStream = new MemoryStream();
    using CsvWriter writer = new CsvWriter(memoryStream);

    // Write to memoryStream using SoftCircuits.CsvParser

    writer.Flush(); // This is important!

    FileContentResult result = new FileContentResult(memoryStream.GetBuffer(), "text/csv")
    {
        FileDownloadName = "Filename.csv""
    };
    return result;
}
</code>```

This code works but I wish it used memory more efficiently. As is, it writes the entire file contents to memory, and then copies that memory to the result. So a large file would exist twice in memory before anything is written to the response stream. I was curious about FileStreamResult but wasn't able to get that working.

If someone can improve on this, I'd gladly mark your answer as the accepted one.

UPDATE:

So I realized I can adapt the code above to use FileStreamResult by replacing the last block with this:

```<code>memoryStream.Seek(0, SeekOrigin.Begin);
FileStreamResult result = new FileStreamResult(memoryStream, "text/csv")
{
    FileDownloadName = "Filename.csv"
};
return result;
</code>```

This works almost the same except that, instead of calling memoryStream.GetBuffer() to copy all the bytes, it just passes the memory stream object. This is an improvement as I am not needlessly copying the bytes.

However, the downside is that I have to remove my two using statements or else I'll get an exception:

ObjectDisposedException: Cannot access a closed Stream.

Looks like it's a trade off between copying the bytes an extra time or not cleaning up my streams and CSV writer.

In the end, I'm able to prevent the CSV writer from closing the stream when it's disposed, and since MemoryStream does not have unmanaged resources there should be no harm in leaving it open.

Body:
So here's what I came up with.

Markup:

<a class="btn btn-success" asp-page-handler="DownloadCsv">
    Download CSV
</a>

Handler:

public IActionResult OnGetDownloadCsv()
{
    using MemoryStream memoryStream = new MemoryStream();
    using CsvWriter writer = new CsvWriter(memoryStream);

    // Write to memoryStream using SoftCircuits.CsvParser

    writer.Flush(); // This is important!

    FileContentResult result = new FileContentResult(memoryStream.GetBuffer(), "text/csv")
    {
        FileDownloadName = "Filename.csv""
    };
    return result;
}

This code works but I wish it used memory more efficiently. As is, it writes the entire file contents to memory, and then copies that memory to the result. So a large file would exist twice in memory before anything is written to the response stream. I was curious about FileStreamResult but wasn't able to get that working.

If someone can improve on this, I'd gladly mark your answer as the accepted one.

UPDATE:

So I realized I can adapt the code above to use FileStreamResult by replacing the last block with this:

memoryStream.Seek(0, SeekOrigin.Begin);
FileStreamResult result = new FileStreamResult(memoryStream, "text/csv")
{
    FileDownloadName = "Filename.csv"
};
return result;

This works almost the same except that, instead of calling memoryStream.GetBuffer() to copy all the bytes, it just passes the memory stream object. This is an improvement as I am not needlessly copying the bytes.

However, the downside is that I have to remove my two using statements or else I'll get an exception:

ObjectDisposedException: Cannot access a closed Stream.

Looks like it's a trade off between copying the bytes an extra time or not cleaning up my streams and CSV writer.

In the end, I'm able to prevent the CSV writer from closing the stream when it's disposed, and since MemoryStream does not have unmanaged resources there should be no harm in leaving it open.


问:
Configure nodemon to refresh same tab
This could be really rookie. I want to know if there is a way that I can configure nodemon to refresh the same tab instead of opening a new tab each time I make a change in my js files.</p>

答:
I use a package called reload. Assuming you are doing this on your FE and that you already installed express.js and nodemon
first install reload

```<code>npm install --save-dev reload
</code>```

Than create a index.js file or server.js or whatever name your want

this is my index.js:

const express = require('express')
const http = require('http')
const reload = require('reload')
const opn = require('opn')

const app = express()

app.engine('html', require('ejs').renderFile)
app.set('view engine', 'html')
app.set('src', './src')
app.use(express.static('src'))

app.get('/', (req, res) => res.render('index'))

const server = http.createServer(app)
server.listen(8080, function() {
  console.log('Listening to port 8080...')
})

opn('http://localhost:8080')

reload(app)```
</div>
</div>
</p>

<p>the opn package can be intalled with </p>

```npm install opn
```

<p>it will automatically open your localhost once you type npm start on your terminal</p>

<p>on HTML you have to insert something like this after the closing body tag:</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-html lang-html prettyprint-override"><code></body>
<script src="/reload/reload.js"></script></code>```

and on package.json the following:

```<code>"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js -e els,js,html,css,json"
</code>```

},

The only problem with this is that it will reopen the browser every time you make a change to those files and well as reload the current opened one sure to the opn package. I am still going to create a function to prevent that, eventually. Hope that helps!

Title: Configure nodemon to refresh same tab

Body:
I use a package called reload. Assuming you are doing this on your FE and that you already installed express.js and nodemon
first install reload

npm install --save-dev reload

Than create a index.js file or server.js or whatever name your want

this is my index.js:

const express = require('express')
const http = require('http')
const reload = require('reload')
const opn = require('opn')

const app = express()

app.engine('html', require('ejs').renderFile)
app.set('view engine', 'html')
app.set('src', './src')
app.use(express.static('src'))

app.get('/', (req, res) => res.render('index'))

const server = http.createServer(app)
server.listen(8080, function() {
  console.log('Listening to port 8080...')
})

opn('http://localhost:8080')

reload(app)

the opn package can be intalled with

npm install opn

it will automatically open your localhost once you type npm start on your terminal

on HTML you have to insert something like this after the closing body tag:

</body>
<script src="/reload/reload.js"></script>

and on package.json the following:

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js -e els,js,html,css,json"

},

The only problem with this is that it will reopen the browser every time you make a change to those files and well as reload the current opened one sure to the opn package. I am still going to create a function to prevent that, eventually. Hope that helps!


问:
Image as cell note in Google Sheets, to be displayed at mouseover/hover
I'd like to attach images to certain cells of my Google spreadsheet, to appear upon hovering the mouse upon that cell, similar to how the native text-only regular cell notes (Shift+F2) appear.

Natively, Google Sheets supports inserting images in the cell. My image sizes are however too big, and I'd have to make the row/column width/height huge for them to be displayed at 100%. Plus, I'd want the images to only appear upon mouseover, and not always be visible.

(I should add that the functionality I describe is actually very easily achievable in Excel, which allows setting a picture-background for cell comments, something that Google Sheets does not.)

I discovered a Google Sheets addon which seems to extend regular cell notes to include richer content, including images. Inconveniently, it requires each image be uploaded to an image server rather than be loaded from the PC. That would have still been fine, except I couldn't get it to achieve the above stated goal.

Finally, I found this suggested workaround, which for me does not work, in the sense that the image is not loaded as a preview upon mousing over the URL (whether it ends with .jpg or not), only the URL itself is:

Interestingly, the effect I'm after actually exists in Google Docs, when the link isn't even an image but just a page:

答:
Issue:

There is no native way to trigger actions on hover events in Sheets, and there is no way to retrieve images that have been uploaded from the computer and don't have a valid URL. This greatly limits what you can accomplish.

Nevertheless, there are workarounds available that can get you close to the functionality you're asking for.

Workaround (showModelessDialog):

You could, for example create a modeless dialog whose purpose would be to show the image corresponding to the selected cell.

Ideally, onSelectionChange trigger would be used, since this trigger to refresh the modeless dialog with current image when the user changes the selected cell, but since creating a modeless dialog requires authorization, simple triggers cannot run services that require authorization, and onSelectionChange is only available as a simple trigger (cannot be installed), that won't be possible.

So one possible workflow could be the following:

Show a modeless dialog when the spreadsheet is opened by a user.

The user selects the cell with the image that should be shown.

User clicks a button in the modeless dialog (or the previous image) to refresh the modeless dialog with the currently selected image.

How to do this:

To achieve this, you can follow these steps:

Install onOpen trigger that creates modeless dialog when the user opens the spreadsheet (the trigger needs to be installed, since, as I mentioned, simple triggers cannot use services that require authorization). To do that, go to the Apps Script editor (selecting Tools > Script editor), copy this function to your Code.gs file, and install the trigger following these steps:

function onOpenTrigger(e) {
  var html = HtmlService.createTemplateFromFile("Page").evaluate()
      .setWidth(800) // Change dimensions according to your preferences
      //.setHeight(600) // Change dimensions according to your preferences
  SpreadsheetApp.getUi()
      .showModelessDialog(html, "My image");
}
```

<ul>
<li><strong>Create the HTML template corresponding to the modeless dialog</strong>. The idea here would be: when the page loads, the currently selected image is shown. If the button (or the image itself) gets clicked, the page will refresh with current image (see <code>retrieveImage</code> and <code>refreshImage</code>). Create an HTML file in the editor via <code>File > New > HTML file</code>, and copy the following code:</li>
</ul>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body onload="retrieveImage()">
    <img id="currentImage" onclick="retrieveImage()" alt="No image is selected" width="600">
    <button onclick="retrieveImage()">Click to refresh image!</button>
  </body>
  <script>
    function retrieveImage() {
      google.script.run.withSuccessHandler(refreshImage).getSelectedImage();
    }

    function refreshImage(imageUrl) {
      if (imageUrl) document.getElementById("currentImage").src = imageUrl;
    }
  </script>
</html>
</code>```

Back in your script file (.gs), create a function to retrieve the image URL from current cell (in case this cell has an image). This function will get called by the modeless dialog when it loads and when its button is clicked. It could be like this (regex is used to retrieve that — see this answer:

function getSelectedImage() {
  var formula = SpreadsheetApp.getActiveRange().getFormula();
  var regex = /=image\("(.*)"/i;
  var matches = formula.match(regex);
  return matches ? matches[1] : null;
}
```

Note:

You can adapt the dimensions of both the selected image () and the modeless dialog (.setWidth, .setHeight) according to your preferences.

Reference:

Dialogs and Sidebars in G Suite Documents

Installable Triggers: Managing triggers manually

getActiveRange()

Body:
Issue:

There is no native way to trigger actions on hover events in Sheets, and there is no way to retrieve images that have been uploaded from the computer and don't have a valid URL. This greatly limits what you can accomplish.

Nevertheless, there are workarounds available that can get you close to the functionality you're asking for.

Workaround (showModelessDialog):

You could, for example create a modeless dialog whose purpose would be to show the image corresponding to the selected cell.

Ideally, onSelectionChange trigger would be used, since this trigger to refresh the modeless dialog with current image when the user changes the selected cell, but since creating a modeless dialog requires authorization, simple triggers cannot run services that require authorization, and onSelectionChange is only available as a simple trigger (cannot be installed), that won't be possible.

So one possible workflow could be the following:

Show a modeless dialog when the spreadsheet is opened by a user.

The user selects the cell with the image that should be shown.

User clicks a button in the modeless dialog (or the previous image) to refresh the modeless dialog with the currently selected image.

How to do this:

To achieve this, you can follow these steps:

Install onOpen trigger that creates modeless dialog when the user opens the spreadsheet (the trigger needs to be installed, since, as I mentioned, simple triggers cannot use services that require authorization). To do that, go to the Apps Script editor (selecting Tools > Script editor), copy this function to your Code.gs file, and install the trigger following these steps:

function onOpenTrigger(e) {
  var html = HtmlService.createTemplateFromFile("Page").evaluate()
      .setWidth(800) // Change dimensions according to your preferences
      //.setHeight(600) // Change dimensions according to your preferences
  SpreadsheetApp.getUi()
      .showModelessDialog(html, "My image");
}

Create the HTML template corresponding to the modeless dialog. The idea here would be: when the page loads, the currently selected image is shown. If the button (or the image itself) gets clicked, the page will refresh with current image (see retrieveImage and refreshImage). Create an HTML file in the editor via File > New > HTML file, and copy the following code:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body onload="retrieveImage()">
    <img id="currentImage" onclick="retrieveImage()" alt="No image is selected" width="600">
    <button onclick="retrieveImage()">Click to refresh image!</button>
  </body>
  <script>
    function retrieveImage() {
      google.script.run.withSuccessHandler(refreshImage).getSelectedImage();
    }

    function refreshImage(imageUrl) {
      if (imageUrl) document.getElementById("currentImage").src = imageUrl;
    }
  </script>
</html>

Back in your script file (.gs), create a function to retrieve the image URL from current cell (in case this cell has an image). This function will get called by the modeless dialog when it loads and when its button is clicked. It could be like this (regex is used to retrieve that — see this answer:

function getSelectedImage() {
  var formula = SpreadsheetApp.getActiveRange().getFormula();
  var regex = /=image\("(.*)"/i;
  var matches = formula.match(regex);
  return matches ? matches[1] : null;
}

Note:

You can adapt the dimensions of both the selected image (<img width="" height="">) and the modeless dialog (.setWidth, .setHeight) according to your preferences.

Reference:

Dialogs and Sidebars in G Suite Documents

Installable Triggers: Managing triggers manually

getActiveRange()


问:
Preferred way to decrease learning rate for Adam optimiser in PyTorch
I have been seeing code that uses an Adam optimizer . And the way they decrease the learning rate is as follows:

```<code>
    optimizer = torch.optim.Adam(net.parameters(),lr=0.01)
    (training...
    optimizer.step()...)

    if iteration >= some_threshold:
        for param_group in optimizer.param_groups:
            param_group['lr'] = 0.001

</code>```

I thought we have the same learning rate for all parameters. So why then iterate over the param_groups and individually set learning rate for each parameter?

Wouldn't the following be faster and have an identical effect?

```<code>
    optimizer = torch.optim.Adam(net.parameters(),lr=0.01)
    scheduler = MultiStepLR(optimizer, milestones=[some_threshold], gamma=0.1)
    (training...
    optimizer.step()
    scheduler.step())

</code>```

Thank you

答:
You need to iterate over param_groups because if you don't specify multiple groups of parameters in the optimiser, you automatically have a single group. That doesn't mean you set the learning rate for each parameter, but rather each parameter group.

In fact the learning rate schedulers from PyTorch do the same thing. From _LRScheduler (base class of learning rate schedulers):

with _enable_get_lr_call(self):
    if epoch is None:
        self.last_epoch += 1
        values = self.get_lr()
    else:
        warnings.warn(EPOCH_DEPRECATION_WARNING, UserWarning)
        self.last_epoch = epoch
        if hasattr(self, "_get_closed_form_lr"):
            values = self._get_closed_form_lr()
        else:
            values = self.get_lr()

for param_group, lr in zip(self.optimizer.param_groups, values):
    param_group['lr'] = lr
```

Yes, it has the identical effect in this case, but it wouldn't be faster.

Body:
I have been seeing code that uses an Adam optimizer . And the way they decrease the learning rate is as follows:

    optimizer = torch.optim.Adam(net.parameters(),lr=0.01)
    (training...
    optimizer.step()...)

    if iteration >= some_threshold:
        for param_group in optimizer.param_groups:
            param_group['lr'] = 0.001

I thought we have the same learning rate for all parameters. So why then iterate over the param_groups and individually set learning rate for each parameter?

Wouldn't the following be faster and have an identical effect?

    optimizer = torch.optim.Adam(net.parameters(),lr=0.01)
    scheduler = MultiStepLR(optimizer, milestones=[some_threshold], gamma=0.1)
    (training...
    optimizer.step()
    scheduler.step())

Thank you

Body:
You need to iterate over param_groups because if you don't specify multiple groups of parameters in the optimiser, you automatically have a single group. That doesn't mean you set the learning rate for each parameter, but rather each parameter group.

In fact the learning rate schedulers from PyTorch do the same thing. From _LRScheduler (base class of learning rate schedulers):

with _enable_get_lr_call(self):
    if epoch is None:
        self.last_epoch += 1
        values = self.get_lr()
    else:
        warnings.warn(EPOCH_DEPRECATION_WARNING, UserWarning)
        self.last_epoch = epoch
        if hasattr(self, "_get_closed_form_lr"):
            values = self._get_closed_form_lr()
        else:
            values = self.get_lr()

for param_group, lr in zip(self.optimizer.param_groups, values):
    param_group['lr'] = lr

Yes, it has the identical effect in this case, but it wouldn't be faster.


问:
Pip cannot install - error "Temporary failure in name resolution" on Debian WSL
This is my first stackoverflow question!

Recently python pip install has stopped working and is giving the following error:

pip3 install django

```<code>WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f07a41b75c0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/django/
</code>```

The error repeats several times until it gives up.

I'm using Python3 in Linux Debian on WSL (Windows Subsystem for Linux), on Windows 10.

After some searching and seeing some suggestions I found that my /etc/resolv.conf contains only:

```<code>^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
</code>```

This doesn't look quite right... could this be the problem?

What is resolv.conf supposed to contain?

Thinking about what could be the root cause... before this happened the computer was accidentally switched off at the mains whilst apache2 and mysql services were running (in debian on WSL), could this have caused the problem?

Thanks in advance, Mark

答:
/etc/resolv.conf (manpage) usually only has a few, often automatically generated, lines that are pulled in from its network's configured DNS configuration.

In my WSL OpenSUSE, the entire resolv.conf file is:

```<code># This file was automatically generated by WSL. To stop automatic generation of this file, remove this line.
nameserver 1.1.1.1
</code>```

Which it pulls from the configuration in my home router.

I am not sure why your resolv.conf would be any different from that, unless it is something weird with the newer WSL2 that I have yet to try.

You can try manually configuring a nameserver or two with a public DNS like 1.1.1.1 or 8.8.8.8. Though that may not keep it from being overwritten until you figure out if there is an underlying problem.

On an installed Linux system instead of a WSL, that uses NetworkManager, it would be prefixed with # Generated by NetworkManager instead of the above WSL note.

Body:
This is my first stackoverflow question!

Recently python pip install has stopped working and is giving the following error:

pip3 install django

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f07a41b75c0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/django/

The error repeats several times until it gives up.

I'm using Python3 in Linux Debian on WSL (Windows Subsystem for Linux), on Windows 10.

After some searching and seeing some suggestions I found that my /etc/resolv.conf contains only:

^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@

This doesn't look quite right... could this be the problem?

What is resolv.conf supposed to contain?

Thinking about what could be the root cause... before this happened the computer was accidentally switched off at the mains whilst apache2 and mysql services were running (in debian on WSL), could this have caused the problem?

Thanks in advance, Mark

Body:
/etc/resolv.conf (manpage) usually only has a few, often automatically generated, lines that are pulled in from its network's configured DNS configuration.

In my WSL OpenSUSE, the entire resolv.conf file is:

# This file was automatically generated by WSL. To stop automatic generation of this file, remove this line.
nameserver 1.1.1.1

Which it pulls from the configuration in my home router.

I am not sure why your resolv.conf would be any different from that, unless it is something weird with the newer WSL2 that I have yet to try.

You can try manually configuring a nameserver or two with a public DNS like 1.1.1.1 or 8.8.8.8. Though that may not keep it from being overwritten until you figure out if there is an underlying problem.

On an installed Linux system instead of a WSL, that uses NetworkManager, it would be prefixed with # Generated by NetworkManager instead of the above WSL note.


问:
Simple Framework Mechanics
I'm building a simple framework and hoping it will help me better understand OOP. Well, I've come across my first hurdle.

I'm naturally using MVC pattern and I have a user model. I then have a 'table' which manages the collection of user objects. I have an abstract model and table. Similar to Zend Framework layout.

Anyway, I'm now wondering what is the best way to execute a query? I have a database object which manages the database layer. Currently using mysqli object.

Trouble is my connection is a member of my application object, how do I access that from within my table object to execute a query? I obviously can't create a new object because that will connect to the database again. I need to reuse this same db object.

Any ideas? I understand if this isn't optimal design. Right now I'm just looking for advice.

Edit: Should I just use Doctrine?

答:
doctrine or not?

If your intention is to learn how to write SQL Queries and to create something for your own, use mysqli or PDO.

If you would like to learn how to use a real object oriented database layer, use doctrine. With 3 pages tutorial, you can do the most general things. However some very special cases are better coded in raw sql than with doctrine. But if you know how to do things with doctrine it is a very useful library and you end up writing better, consistenter, more readabler and extensiabler (:-)) code.

Title: Simple Framework Mechanics


问:
"#_no-deeplink-found_ " is automatically appending to home page url
I am using wordpress for a website. When I hit home page,"#no-deeplink-found" is automatically is appending to the url. I have no idea about deep links and why it is appending to the url.

I have searched all the plugins settings, fond no solution to remove it. I have disabled some SEO related plugins, but found no solution for it.

Please help me to remove this. I don't want any additional parameters to be added to the homepage url.

Below are the screen snap of the issue:
enter image description here

Additional Info
Theme : solomedic

Any help will be appreciated!!!!!

答: In a Similar case of mine, an issue found with "WP-Bakery page editor > Layerslider" component in WordPress page editor. When we delete this layer, page loads fine. Therefore, you may test by deleting this layer or verifying its setting.


问:
DAX constant vs. reference: constant works, reference doesn't
I have a table where I would like to calculate the sum of the hours in the first month of the data.
I have a calculated field that dynamically finds the min. month in the table:

MinMonth:=CALCULATE(MONTH(MIN([Month])))

This outputs 1, 2, ..., 12

I then have a field that calculates the sum. If i type a static number

CALCULATE(SUM([Hours]);[Month]=1)

It works. But if I type a reference to the calculated field:

CALCULATE(SUM([Hours]);[MonthNo]=[MinMonth])

It doesn't. Even if I create a cell:

MinMonthTest:=1

And reference it, it doesn't work. Anyone know why?

Thanks

答:
You can't use a measure in a simple boolean filter. The easiest workaround is to pre-calculated it as a static variable.

```<code>Measure =
VAR MinMonth = [MinMonth]
RETURN
    CALCULATE ( SUM ( [Hours] ); [Month] = MinMonth )
</code>```

The other option is to use a FILTER argument:

```<code>Measure =
CALCULATE (
    SUM ( [Hours] ),
    FILTER ( VALUES ( [Month] ), [Month] = [MinMonth] )
)
</code>```

These still may not return what you expect though since [MinMonth] will be evaluated within the filter context it is called in and it's not entirely clear if that's what you want or not. If not, then you probably want something more like this to ignore that evaluation context:

```<code>MinMonth := CALCULATE ( MONTH ( MIN ( [Month] ) ), ALL ( TableName ) )
</code>```

Body:
You can't use a measure in a simple boolean filter. The easiest workaround is to pre-calculated it as a static variable.

Measure =
VAR MinMonth = [MinMonth]
RETURN
    CALCULATE ( SUM ( [Hours] ); [Month] = MinMonth )

The other option is to use a FILTER argument:

Measure =
CALCULATE (
    SUM ( [Hours] ),
    FILTER ( VALUES ( [Month] ), [Month] = [MinMonth] )
)

These still may not return what you expect though since [MinMonth] will be evaluated within the filter context it is called in and it's not entirely clear if that's what you want or not. If not, then you probably want something more like this to ignore that evaluation context:

MinMonth := CALCULATE ( MONTH ( MIN ( [Month] ) ), ALL ( TableName ) )


问:
Svelte 3, async onMount or a valid alternative?
What I need is to use async-await in Svelte onMount().

Or maybe you can suggest me what is wrong and what I can use alternatively.

To Reproduce

go here: https://svelte.dev/repl/000ae69c0fe14d9483678d4ace874726?version=3.23.0

open the console

click on the button

you should see messages: "Mounting..." and "A lot of background work..."

if you click again the destroy message is not written

WHY?

Did onMount() recognizes the async function promise? Should it?

I need that async behavior because I need to wait for function lazyLoading() before rendering the Child component.

Is there an alternative way to do this in Svelte?

答:
onMount must be synchronous. However, you can use an {#await} block in your markup and make lazyLoading async, for example:

{#await lazyLoading() then data}
  I'm the child and I loaded "{data}".
{/await}
```

<p>You could also do...</p>

<pre class="lang-html prettyprint-override"><code><script>
  let dataPromise = lazyLoading()
</script>

{#await dataPromise then data}
  I'm the child and I loaded "{data}".
{/await}
</code>```

See my working example here.

This has the additional benefit of allowing you to use a loader as well as markup that appears when the promise is rejected, using this syntax:

{#await promise}
  loading
{:then value}
  loaded {value}
{:catch error}
  failed with {error}
{/await}
```

Body:
onMount must be synchronous. However, you can use an {#await} block in your markup and make lazyLoading async, for example:

{#await lazyLoading() then data}
  I'm the child and I loaded "{data}".
{/await}

You could also do...

<script>
  let dataPromise = lazyLoading()
</script>

{#await dataPromise then data}
  I'm the child and I loaded "{data}".
{/await}

See my working example here.

This has the additional benefit of allowing you to use a loader as well as markup that appears when the promise is rejected, using this syntax:

{#await promise}
  loading
{:then value}
  loaded {value}
{:catch error}
  failed with {error}
{/await}