问:
Node.js pm2 is not working in the jenkins pipeline
I have used pm2 for node.js application to build with help of jenkins pipeline. For my application to start, it needs the another application to running on the particular port. For achieving this with CI on jenkins I used pm2 to run the process in background so it can go for next stage.

In my local machine pm2 is running successfully .But in jenkins it is not starting the application, and also it does not shows any error message, but I am sure the application was not running with pm2. What may be a reason.

Any Help.

Thanks.

答:
Try

```<code>pm2 startup
</code>```

And execute the suggested command.

If you are using NVM and you execute a shell script with Jenkins, add this at the beginning.

```<code>export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

</code>```

Body:
Try

pm2 startup

And execute the suggested command.

If you are using NVM and you execute a shell script with Jenkins, add this at the beginning.

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"


来源: stackexchange

问:
WCF: Updating Service Reference gives duplicate config entries
I have a WPF application using service references to a WCF service. When doing updates on the service I need to update the service reference, so I right click it and hit "Update Service Reference".

Doing this results in duplicate entries in the App.config file of the client project.

It duplicates a binding under wsHttpBinding - adding an equal entry with postfix number in name: WSHttpBinding_ISomeService --> WSHttpBinding_ISomeService1.

And it duplicates the endpoint definition under binding such that there is one endpoint for each wsHttpBinding. This too is a pure duplicate except of the name.

Why does it duplicate the config? Isn't it just supposed to update the name? And how can I make it stop?

答:
code-zoop says that this known bug is resolved in VS2010, but I'm getting it in VS2010 as well.

Happens when I manually modify the default value for the MaxReceivedMessageSize property (and others) of the basicHttpBinding in App.config (as per this post: WCF - How to Increase Message Size Quota)

Just thought I'd mention that this happens in VS2010 as well. For the moment, I'm taking Shiraz Bhaiji's advice and just deleting the duplicate, which seems to be working for the moment being.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Can't apply background image in css (flask template)
I want to apply background image in internal css. I'm using flask template. this is my directory

```<code>src - templates - image - img.jpg
src- templates - upload.html
</code>```

I want to apply the background image at upload.html. but I got 404 error. can someone help me please?

my code:

```<code>background-image: url("/image/img.jpg");
</code>```

error message:

get /image/img.jpg HTTP/1.1 404

答:
The (Flask) standard way of doing this, which you'll see done in examples and tutorials, is to put static files in a static folder at the root of the project. Assuming your CSS is also in static,

```<code>background-image: url('/static/img.jpg');
</code>```

does what you want. But if you're embedding styles in templates,

```<code>background-image: url({{ url_for('static', filename='img.jpg') }});
</code>```

is preferred, though the former will work just fine.

If things get more complicated and you start using blueprints, consult the documentation.

ContentLicense: CC BY-SA 4.0

Body:
I want to apply background image in internal css. I'm using flask template. this is my directory

src - templates - image - img.jpg
src- templates - upload.html

I want to apply the background image at upload.html. but I got 404 error. can someone help me please?

my code:

background-image: url("/image/img.jpg");

error message:

get /image/img.jpg HTTP/1.1 404

Body:
The (Flask) standard way of doing this, which you'll see done in examples and tutorials, is to put static files in a static folder at the root of the project. Assuming your CSS is also in static,

background-image: url('/static/img.jpg');

does what you want. But if you're embedding styles in templates,

background-image: url({{ url_for('static', filename='img.jpg') }});

is preferred, though the former will work just fine.

If things get more complicated and you start using blueprints, consult the documentation.


问:
How to move all elements that are zero to the end of an array?
Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

```<code>function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}
</code>```

input:

```<code>[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]
</code>```

Expected:

```<code>[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
</code>```

Actual:

```<code>[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
</code>```

Result is coming as correct but I need to do it without array.push() or array.splice()

答:
You could use sort:

const arr = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

arr.sort((a, b) => (a === 0) - (b === 0))

console.log(arr)```
</div>
</div>
</p>
<p>Subtracting booleans returns a 1, -1 or 0.</p>
```true - false === 1
false - true === -1
true - true === 0
```
<p>If <code>a</code> is 0 and <code>b</code> isn't, 1 will be returned and <code>a</code> will be moved to the end of the array. If both <code>a</code> and <code>b</code> are zero or non-zero, they aren't moved relative to each other.</p>
<hr />
<p>The simplest way to move certain items to one end is to collect the items to 2 separate arrays based on the condition and concatenate them in the end.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14],
      zeros = [],
      nonZeros = []

for (const n of arr) {
  if (n === 0)
    zeros.push(n)
  else
    nonZeros.push(n)
}

const output = nonZeros.concat(zeros);
console.log(output)</code>```

Body:
Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}

input:

[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

Expected:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Actual:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Result is coming as correct but I need to do it without array.push() or array.splice()

Body:
You could use sort:

const arr = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

arr.sort((a, b) => (a === 0) - (b === 0))

console.log(arr)

Subtracting booleans returns a 1, -1 or 0.

true - false === 1
false - true === -1
true - true === 0

If a is 0 and b isn't, 1 will be returned and a will be moved to the end of the array. If both a and b are zero or non-zero, they aren't moved relative to each other.

The simplest way to move certain items to one end is to collect the items to 2 separate arrays based on the condition and concatenate them in the end.

const arr = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14],
      zeros = [],
      nonZeros = []

for (const n of arr) {
  if (n === 0)
    zeros.push(n)
  else
    nonZeros.push(n)
}

const output = nonZeros.concat(zeros);
console.log(output)


问:
I'm trying to display an image from my database, but the image wont populate the src of the img html attribute
I have an image saved to a database by converting to a byte array to a string then i am trying to remake the image on the view. But I wanted to make it for if the image was null(no image upload) that they will get a default "no image" image. But it seems when i try to make an if statement within my view with razor. The img src is not able to find the var in the if statement. The reason i need it to fill the src on the img outside of the if statement is because when i submit the form i need it to send the img data back to the action in the controller to reconvert it and save it on the database.

I trying a view different ways to fix it, the best i can do it make scripts inside my if statement. but it still will not connect to my img src.

```<code>    <!--Remaking the image from a stromg to a char
    array to a byte array to a imagefrom the
    database to the original image-->
    @if (Model.ImagePath != null)
    {

        char[] imageChars = Model.ImagePath.ToCharArray();
        byte[] imageBytes = imageChars.Select(b => (byte)b).ToArray();
        var base64 = Convert.ToBase64String(imageBytes);
        var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
        <script>
            var img = getElementById("ImagePath").src;
            img.src = "@imgSrc";
        </script>
    }
    else
    {
        <script>
            var img = getElementById("ImagePath");
            img.src = "~/Content/no-image-icon.jpg";
            getElementById("ImagePath").width = "100";
            getElementById("ImagePath").height = "100";
        </script>
    }
    <img id="ImagePath" alt=""/>
</code>```

when i inspect the page the script has the image converted back into the right format it just wont send it to the img src.

答: I figured it out i made a new vareriable in my model and added the string to it in my action that loads the page then just set that as the img src. Thank you for the help tho!</p>

Body:
I have an image saved to a database by converting to a byte array to a string then i am trying to remake the image on the view. But I wanted to make it for if the image was null(no image upload) that they will get a default "no image" image. But it seems when i try to make an if statement within my view with razor. The img src is not able to find the var in the if statement. The reason i need it to fill the src on the img outside of the if statement is because when i submit the form i need it to send the img data back to the action in the controller to reconvert it and save it on the database.

I trying a view different ways to fix it, the best i can do it make scripts inside my if statement. but it still will not connect to my img src.

    @if (Model.ImagePath != null)
    {

        char[] imageChars = Model.ImagePath.ToCharArray();
        byte[] imageBytes = imageChars.Select(b => (byte)b).ToArray();
        var base64 = Convert.ToBase64String(imageBytes);
        var imgSrc = String.Format("data:image/gif;base64,{0}", base64);

    }
    else
    {

    }

when i inspect the page the script has the image converted back into the right format it just wont send it to the img src.


问:
DocuSign API - Difference Between the formData array and the recipientFormData array
I'm using the EnvelopeFormData to GET the form data for a specified envelope. I've noticed there are 2 arrays that are returned: formData and recipientFormData. They are both very similar and the name/value pairs from the recipientFormData array also appears in the formData array.

I haven't been able to find out what the difference between these is and whether I should be retrieving data from the formData or the recipientFormData array?

答:
I believe that recipientFormData are the tabs (fields) organized per recipient (note the array).

Vs formData is the aggregate tab data for the envelope as a whole.

To test, use the method call with an envelope with multiple signing recipients, each with their own set of tabs.


问:
How to make a while loop throughout entire code. (Python)
I'm currently making a text-based game about walking through an abandoned house, and finding items to ward of monsters and all of that. I want a while loop system where if your health reaches below 0 (health=20), then the code ends by saying "You died to (insert event here)". I'm new to coding with python, so I'm not entirely sure how to code that.

I've tried setting up a while loop with an if statement that checks if the health is below 0. This is near the top of the code below the variables and above the functions

```<code>health = 20 #variable

while ( health < 0):
    print("You died to [insert event here]\n")
    break
</code>```

Instead of it doing anything, it completely ignores it. I'm not sure how I would place the code into the function because I still need to use "global" to import variables into them. If you know the answer to this problem, or you know an alternative code to solve this problem, please tell me. Again I'm new to python so please explain in a way I can understand.

答:
You may write it as:

```<code>health = 20
while health > 0:
    print("You died to XYZ")
    health -= 1
</code>```

This will print "You died to XYZ" 20 times as loop will run for 20 times from health = 20 to health = 0.

But, while health < 0 would consider it to be zero outcome because python understand loop to run till health reaches zero.

Body:
I'm currently making a text-based game about walking through an abandoned house, and finding items to ward of monsters and all of that. I want a while loop system where if your health reaches below 0 (health=20), then the code ends by saying "You died to (insert event here)". I'm new to coding with python, so I'm not entirely sure how to code that.

I've tried setting up a while loop with an if statement that checks if the health is below 0. This is near the top of the code below the variables and above the functions

health = 20 #variable

while ( health < 0):
    print("You died to [insert event here]\n")
    break

Instead of it doing anything, it completely ignores it. I'm not sure how I would place the code into the function because I still need to use "global" to import variables into them. If you know the answer to this problem, or you know an alternative code to solve this problem, please tell me. Again I'm new to python so please explain in a way I can understand.

Body:
You may write it as:

health = 20
while health > 0:
    print("You died to XYZ")
    health -= 1

This will print "You died to XYZ" 20 times as loop will run for 20 times from health = 20 to health = 0.

But, while health < 0 would consider it to be zero outcome because python understand loop to run till health reaches zero.


问:
Android LinearLayout and RecyclerView BottomNavigation Alignment
so I can't figure out how to align my bottom navigation in a LinearLayout under a RecyclerView. The items are RecyclerView:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".CategoryActivity">

   <android.support.design.widget.AppBarLayout
           android:theme="@style/AppTheme.AppBarOverlay"
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:background="?attr/colorPrimary"
               app:popupTheme="@style/AppTheme.PopupOverlay"
               android:layout_width="match_parent"
               android:layout_height="?attr/actionBarSize">
       </android.support.v7.widget.Toolbar>

   </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_category"
            android:layout_margin="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            android:layout_alignParentBottom="true"
            app:menu="@menu/bottom_nav_menu"/>

</LinearLayout>
</code>```

The navigation should be always at the bottom.

答:
Not sure but try adding this:

android:layout_gravity="bottom"

Body:
so I can't figure out how to align my bottom navigation in a LinearLayout under a RecyclerView. The items are RecyclerView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".CategoryActivity">

   <android.support.design.widget.AppBarLayout
           android:theme="@style/AppTheme.AppBarOverlay"
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:background="?attr/colorPrimary"
               app:popupTheme="@style/AppTheme.PopupOverlay"
               android:layout_width="match_parent"
               android:layout_height="?attr/actionBarSize">
       </android.support.v7.widget.Toolbar>

   </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_category"
            android:layout_margin="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            android:layout_alignParentBottom="true"
            app:menu="@menu/bottom_nav_menu"/>

</LinearLayout>

The navigation should be always at the bottom.


问:
How can i use substring in appropriate way?
When i try to print parts of string using substr() i got error titled by "out of range" , how can i fix this problem.

```<code>#include <string>
#include <iostream>
using namespace std;

int main()
{

    int cut;
    string n;
    cout << "Enter string: " << endl;
    cin >> n;
    cout << "Enter size to cut: " << endl;
    cin >> cut;
    string res;
    int deli = 0;
    for(int i = 0; i < n.size(); i++)
    {

        res = n.substr(deli,cut);
        cout << "The deli is: " << deli << endl;
        deli+=cut;

        cout << res << endl;
    }

    return 0;
}
</code>```

答:
You should change your loop to stop when the position to cut at is bigger than  or the same size of the string instead of using i because cut can be bigger than 1, something like:

```<code>while(deli < n.size())
{
    res = n.substr(deli,cut);
    cout << "The deli is: " << deli << endl;
    deli+=cut;

    cout << res << endl;
}
</code>```

Body:
When i try to print parts of string using substr() i got error titled by "out of range" , how can i fix this problem.

#include <string>
#include <iostream>
using namespace std;

int main()
{

    int cut;
    string n;
    cout << "Enter string: " << endl;
    cin >> n;
    cout << "Enter size to cut: " << endl;
    cin >> cut;
    string res;
    int deli = 0;
    for(int i = 0; i < n.size(); i++)
    {

        res = n.substr(deli,cut);
        cout << "The deli is: " << deli << endl;
        deli+=cut;

        cout << res << endl;
    }

    return 0;
}

Body:
You should change your loop to stop when the position to cut at is bigger than  or the same size of the string instead of using i because cut can be bigger than 1, something like:

while(deli < n.size())
{
    res = n.substr(deli,cut);
    cout << "The deli is: " << deli << endl;
    deli+=cut;

    cout << res << endl;
}


问:
Markov Chain from String
I am currently sitting on a problem considering Markov chains were an input is given in the form of a list of strings. This input has to be transformed into a Markov chain. I have been sitting on this problem already a couple of hours.

My idea: As you can see below I have tried to use the counter from collections to count all transitions, which has worked. Now I am trying to count all the tuples where A and B are the first elements. This gives me all possible transitions for A.

Then I'll count the transitions like (A, B).
Then I want to use these to create a matrix with all probabilities.

def markov(seq):

    states = Counter(seq).keys()
    liste = []
    print(states)
    a = zip(seq[:-1], seq[1:])
    print(list(a))

print(markov(["A","A","B","B","A","B","A","A","A"]))
```

So far I can't get the counting of the tuples to work.
Any help or new ideas on how to solve this is appreciated

答:
To count the tuple, you can create another counter.

```<code>b = Counter()
for word_pair in a:
    b[word_pair] += 1
</code>```

b will keep the count of the pair.

To create the matrix, you can use numpy.

```<code>c = np.array([[b[(i,j)] for j in states] for i in states], dtype = float)
</code>```

I will leave the task of normalizing each row sum to 1 as an exercise.

Title: Markov Chain from String

Body:
I am currently sitting on a problem considering Markov chains were an input is given in the form of a list of strings. This input has to be transformed into a Markov chain. I have been sitting on this problem already a couple of hours.

My idea: As you can see below I have tried to use the counter from collections to count all transitions, which has worked. Now I am trying to count all the tuples where A and B are the first elements. This gives me all possible transitions for A.

Then I'll count the transitions like (A, B).
Then I want to use these to create a matrix with all probabilities.

def markov(seq):

    states = Counter(seq).keys()
    liste = []
    print(states)
    a = zip(seq[:-1], seq[1:])
    print(list(a))

print(markov(["A","A","B","B","A","B","A","A","A"]))

So far I can't get the counting of the tuples to work.
Any help or new ideas on how to solve this is appreciated

Body:
To count the tuple, you can create another counter.

b = Counter()
for word_pair in a:
    b[word_pair] += 1

b will keep the count of the pair.

To create the matrix, you can use numpy.

c = np.array([[b[(i,j)] for j in states] for i in states], dtype = float)

I will leave the task of normalizing each row sum to 1 as an exercise.


问:
How to reduce select * from table_name query execution time for table with 200k+ records?
I have mysql table set in RDS and I am querying from my web application. The query itself takes more than 20 seconds while other customized operations takes less than 0.5 seconds combined. Is there any way to reduce the query execution time to 2-3 seconds?

I tried indexing but it doesn't help either.

```<code>$table_data = select * from table_name
</code>```

I expect the above query to take as less time to execute as possible.

答:
Here's the thing:

Your query has no filtering predicates (no WHERE clause). Then you are selecting all the rows of the table.

Your query has a * instead of a subset of columns. Therefore, it's selecting all the columns of the table.

In sum you are getting the whole table, every time.

There's nothing you can do on the SQL side. Your chances now reside on the admin side of the database. Get more hardware (faster CPU), increase paralellism (more cores), a faster SSD maybe?

Alternatively, you could use caching on your app side. Run the query only once every 5 mins, and keep the rows in memory.

Body:
I have mysql table set in RDS and I am querying from my web application. The query itself takes more than 20 seconds while other customized operations takes less than 0.5 seconds combined. Is there any way to reduce the query execution time to 2-3 seconds?

I tried indexing but it doesn't help either.

$table_data = select * from table_name

I expect the above query to take as less time to execute as possible.


问:
indentationerror expected an indented block function
how can i have a problem.  I'm doing the function that I can rerun</p>

```<code>def sesver():
    r = sr.Recognizer()
    with sr.Microphone() as source:
      print("Bir sey de!")
      audio = r.listen(source)
    data = ""
    try:
      data = r.recognize_google(audio, language='tr-tr')
      data = data.lower()
      return data
    except ValueError:

data = sesver()
</code>```

答: I'm assuming your code listing is incorrectly formatted and the function body is actually indented. Your problem then is in except ValueError:. It expects an indented block after it. If you simply want to ignore any ValueErrors, write pass in the indented block.

Body:
how can i have a problem.  I'm doing the function that I can rerun

def sesver():
    r = sr.Recognizer()
    with sr.Microphone() as source:
      print("Bir sey de!")
      audio = r.listen(source)
    data = ""
    try:
      data = r.recognize_google(audio, language='tr-tr')
      data = data.lower()
      return data
    except ValueError:

data = sesver()


问:
Reset Cuda Context after exception
I have a working app which uses Cuda / C++, but sometimes, because of memory leaks,  throws exception. I need to be able to reset the GPU on live, my app is a server so it has to stay available.

I tried something like this, but it doesnt seems to work:

```<code>try
{
    // do process using GPU
}
catch (std::exception &e)
{
    // catching exception from cuda only

    cudaSetDevice(0);
    CUDA_RETURN_(cudaDeviceReset());
}
</code>```

My idea is to reset the device each times I get an exception from the GPU, but I cannot manage to make it working. :(
Btw, for some reasons, I cannot fix every problems of my Cuda code, I need a temporary solution. Thanks !

答:
The only method to restore proper device functionality after a non-recoverable ("sticky") CUDA error is to terminate the host process that initiated  (i.e. issued the CUDA runtime API calls that led to) the error.

Therefore, for a single-process application, the only method is to terminate the application.

It should be possible to design a multi-process application, where the initial ("parent")  process makes no usage of CUDA whatsoever, and spawns a child process that uses the GPU.  When the child process encounters an unrecoverable CUDA error, it must terminate.

The parent process can, optionally, monitor the child process. If it determines that the child process has terminated, it can re-spawn the process and restore CUDA functional behavior.

Sticky vs. non-sticky errors are covered elsewhere, such as here.

An example of a proper multi-process app that uses e.g. fork() to spawn a child process that uses CUDA is available in the CUDA sample code simpleIPC.  Here is a rough example assembled from the simpleIPC example (for linux):

```<code>$ cat t477.cu
/*
 * Copyright 1993-2015 NVIDIA Corporation.  All rights reserved.
 *
 * Please refer to the NVIDIA end user license agreement (EULA) associated
 * with this source code for terms and conditions that govern your use of
 * this software. Any use, reproduction, disclosure, or distribution of
 * this software and related documentation outside the terms of the EULA
 * is strictly prohibited.
 *
 */

// Includes
#include <stdio.h>
#include <assert.h>

// CUDA runtime includes
#include <cuda_runtime_api.h>

// CUDA utilities and system includes
#include <helper_cuda.h>

#define MAX_DEVICES          1
#define PROCESSES_PER_DEVICE 1
#define DATA_BUF_SIZE        4096

#ifdef __linux
#include <unistd.h>
#include <sched.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <linux/version.h>

typedef struct ipcDevices_st
{
    int count;
    int results[MAX_DEVICES];
} ipcDevices_t;

// CUDA Kernel
__global__ void simpleKernel(int *dst, int *src, int num)
{
    // Dummy kernel
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    dst[idx] = src[idx] / num;
}

void runTest(int index, ipcDevices_t* s_devices)
{
    if (s_devices->results[0] == 0){
        simpleKernel<<<1,1>>>(NULL, NULL, 1);  // make a fault
        cudaDeviceSynchronize();
        s_devices->results[0] = 1;}
    else {
        int *d, *s;
        int n = 1;
        cudaMalloc(&d, n*sizeof(int));
        cudaMalloc(&s, n*sizeof(int));
        simpleKernel<<<1,1>>>(d, s, n);
        cudaError_t err = cudaDeviceSynchronize();
        if (err != cudaSuccess)
          s_devices->results[0] = 0;
        else
          s_devices->results[0] = 2;}
    cudaDeviceReset();
}
#endif

int main(int argc, char **argv)
{

    ipcDevices_t *s_devices = (ipcDevices_t *) mmap(NULL, sizeof(*s_devices),
                                                    PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
    assert(MAP_FAILED != s_devices);

    // We can't initialize CUDA before fork() so we need to spawn a new process
    s_devices->count = 1;
    s_devices->results[0] = 0;

    printf("\nSpawning child process\n");
    int index = 0;

    pid_t pid = fork();

    printf("> Process %3d\n", pid);
    if (pid == 0) { // child process
    // launch our test
      runTest(index, s_devices);
    }
    // Cleanup and shutdown
    else { // parent process
            int status;
            waitpid(pid, &status, 0);
            if (s_devices->results[0] < 2) {
              printf("first process launch reported error: %d\n", s_devices->results[0]);
              printf("respawn\n");
              pid_t newpid = fork();
              if (newpid == 0) { // child process
                    // launch our test
                 runTest(index, s_devices);
                  }
    // Cleanup and shutdown
              else { // parent process
                int status;
                waitpid(newpid, &status, 0);
                if (s_devices->results[0] < 2)
                  printf("second process launch reported error: %d\n", s_devices->results[0]);
                else
                  printf("second process launch successful\n");
                }

            }

    }

    printf("\nShutting down...\n");

    exit(EXIT_SUCCESS);

}
$ nvcc -I/usr/local/cuda/samples/common/inc t477.cu -o t477
$ ./t477

Spawning child process
> Process 10841
> Process   0

Shutting down...
first process launch reported error: 1
respawn

Shutting down...
second process launch successful

Shutting down...
$
</code>```

For windows, the only changes need should be to use a windows IPC mechanism for host interprocess communication.

Title: Reset Cuda Context after exception

Body:
I have a working app which uses Cuda / C++, but sometimes, because of memory leaks,  throws exception. I need to be able to reset the GPU on live, my app is a server so it has to stay available.

I tried something like this, but it doesnt seems to work:

try
{
    // do process using GPU
}
catch (std::exception &e)
{
    // catching exception from cuda only

    cudaSetDevice(0);
    CUDA_RETURN_(cudaDeviceReset());
}

My idea is to reset the device each times I get an exception from the GPU, but I cannot manage to make it working. :(
Btw, for some reasons, I cannot fix every problems of my Cuda code, I need a temporary solution. Thanks !

Body:
The only method to restore proper device functionality after a non-recoverable ("sticky") CUDA error is to terminate the host process that initiated  (i.e. issued the CUDA runtime API calls that led to) the error.

Therefore, for a single-process application, the only method is to terminate the application.

It should be possible to design a multi-process application, where the initial ("parent")  process makes no usage of CUDA whatsoever, and spawns a child process that uses the GPU.  When the child process encounters an unrecoverable CUDA error, it must terminate.

The parent process can, optionally, monitor the child process. If it determines that the child process has terminated, it can re-spawn the process and restore CUDA functional behavior.

Sticky vs. non-sticky errors are covered elsewhere, such as here.

An example of a proper multi-process app that uses e.g. fork() to spawn a child process that uses CUDA is available in the CUDA sample code simpleIPC.  Here is a rough example assembled from the simpleIPC example (for linux):

$ cat t477.cu
/*
 * Copyright 1993-2015 NVIDIA Corporation.  All rights reserved.
 *
 * Please refer to the NVIDIA end user license agreement (EULA) associated
 * with this source code for terms and conditions that govern your use of
 * this software. Any use, reproduction, disclosure, or distribution of
 * this software and related documentation outside the terms of the EULA
 * is strictly prohibited.
 *
 */

// Includes
#include <stdio.h>
#include <assert.h>

// CUDA runtime includes
#include <cuda_runtime_api.h>

// CUDA utilities and system includes
#include <helper_cuda.h>

#define MAX_DEVICES          1
#define PROCESSES_PER_DEVICE 1
#define DATA_BUF_SIZE        4096

#ifdef __linux
#include <unistd.h>
#include <sched.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <linux/version.h>

typedef struct ipcDevices_st
{
    int count;
    int results[MAX_DEVICES];
} ipcDevices_t;

// CUDA Kernel
__global__ void simpleKernel(int *dst, int *src, int num)
{
    // Dummy kernel
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    dst[idx] = src[idx] / num;
}

void runTest(int index, ipcDevices_t* s_devices)
{
    if (s_devices->results[0] == 0){
        simpleKernel<<<1,1>>>(NULL, NULL, 1);  // make a fault
        cudaDeviceSynchronize();
        s_devices->results[0] = 1;}
    else {
        int *d, *s;
        int n = 1;
        cudaMalloc(&d, n*sizeof(int));
        cudaMalloc(&s, n*sizeof(int));
        simpleKernel<<<1,1>>>(d, s, n);
        cudaError_t err = cudaDeviceSynchronize();
        if (err != cudaSuccess)
          s_devices->results[0] = 0;
        else
          s_devices->results[0] = 2;}
    cudaDeviceReset();
}
#endif

int main(int argc, char **argv)
{

    ipcDevices_t *s_devices = (ipcDevices_t *) mmap(NULL, sizeof(*s_devices),
                                                    PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
    assert(MAP_FAILED != s_devices);

    // We can't initialize CUDA before fork() so we need to spawn a new process
    s_devices->count = 1;
    s_devices->results[0] = 0;

    printf("\nSpawning child process\n");
    int index = 0;

    pid_t pid = fork();

    printf("> Process %3d\n", pid);
    if (pid == 0) { // child process
    // launch our test
      runTest(index, s_devices);
    }
    // Cleanup and shutdown
    else { // parent process
            int status;
            waitpid(pid, &status, 0);
            if (s_devices->results[0] < 2) {
              printf("first process launch reported error: %d\n", s_devices->results[0]);
              printf("respawn\n");
              pid_t newpid = fork();
              if (newpid == 0) { // child process
                    // launch our test
                 runTest(index, s_devices);
                  }
    // Cleanup and shutdown
              else { // parent process
                int status;
                waitpid(newpid, &status, 0);
                if (s_devices->results[0] < 2)
                  printf("second process launch reported error: %d\n", s_devices->results[0]);
                else
                  printf("second process launch successful\n");
                }

            }

    }

    printf("\nShutting down...\n");

    exit(EXIT_SUCCESS);

}
$ nvcc -I/usr/local/cuda/samples/common/inc t477.cu -o t477
$ ./t477

Spawning child process
> Process 10841
> Process   0

Shutting down...
first process launch reported error: 1
respawn

Shutting down...
second process launch successful

Shutting down...
$

For windows, the only changes need should be to use a windows IPC mechanism for host interprocess communication.


问:
Is there a way to store both Image and string variables in one array? (Unity)
I am making a 3D game in unity where player can interact with images and notes (approximately 3-4 paragraphs).

I created the canvas, when player interacts with the notes on the ground, the menu(canvas) pops up.

I wonder, is there any way to store string variables with Image gameObjects in the same array?
Also, i'm going to use these images on the canvas, so should i create as an Image or as a Sprite ?

答:
You should use a common base type from which both inherit. If both things you want to store are e.g. of type MonoBehaviour it would make a lot of sense to use this as a base type instead of object.

```<code>public List<MonoBehaviour> List = new List<MonoBehaviour>();
</code>```

That would at least provide you with all functionality that MonoBehaviour/Component implements. It sounds e.g. like are later interrested in .transform.position.

If you are speaking a about UI stuff like Image and Text you can even use UI.MaskableGraphic as common type

```<code>public List<MaskableGraphic> List = new List<MaskableGraphic>();
</code>```

which provides even more UI related properties like e.g. color or canvas.

Body:
You should use a common base type from which both inherit. If both things you want to store are e.g. of type MonoBehaviour it would make a lot of sense to use this as a base type instead of object.

public List<MonoBehaviour> List = new List<MonoBehaviour>();

That would at least provide you with all functionality that MonoBehaviour/Component implements. It sounds e.g. like are later interrested in .transform.position.

If you are speaking a about UI stuff like Image and Text you can even use UI.MaskableGraphic as common type

public List<MaskableGraphic> List = new List<MaskableGraphic>();

which provides even more UI related properties like e.g. color or canvas.


答:
Try this,

```<code>def sesver():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print 'Bir sey de!'
        audio = r.listen(source)
    data = ''
    try:
        data = r.recognize_google(audio, language='tr-tr')
        data = data.lower()
        return data
    except ValueError: # ':' was missing
        pass           # you pass or show exception message

data = sesver()
</code>```

If you are new, try online indentations checkers. It will help to create a clean indented code.

Title: indentationerror expected an indented block function

Body:
Try this,

def sesver():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print 'Bir sey de!'
        audio = r.listen(source)
    data = ''
    try:
        data = r.recognize_google(audio, language='tr-tr')
        data = data.lower()
        return data
    except ValueError: # ':' was missing
        pass           # you pass or show exception message

data = sesver()

If you are new, try online indentations checkers. It will help to create a clean indented code.


问:
Simple Alexa skill with logging
I've a simple Alexa Skill - developed in the Alexa developer console with some simple JS in the index.js. Alexa is doing well in the Test-Tab (just responding with an 'Hello' to the launchEvent.

I now wanted to implement some logging via console.log(...)

But all I can find on information is: "Just do console.log and you'll find the output somewhere in the Cloudwatch"

But in AWS Cloudwatch, I can create "LogGroups" under "Logs" - but how do I connect such a log group with my Alexa skill? Or do the console.log outputs appear somewhere else automatically?

答:
You don't have to create anything on cloudwatch. Just go to cloudwatch console and click "logs" from left panel. Click the log group with the name containing your lambda function name (just make sure your lambda function has "basic execution role policy"). Now you'll see the list of logs. Just click the one with latest timestamp. Your every deployment will create a new entry in those logs. I'll suggest you sort the logs by time in descending order. Tell me me in comments if you still face any problem.

Again make sure your lambda function has the permission to write on cloudwatch.

Title: Simple Alexa skill with logging


问:
HIChart not showing graph when first time loads android
I am using HiChart android library, I have done all setup but does not show graph when it loads first time. If i pause the activity and start it again then graph shows.</p>

答:
```<code>chartview.setFocusable(true);
</code>```

This line will help you.

Body:
chartview.setFocusable(true);

This line will help you.


答:
You must add 4 spaces for indent.</p>

```<code>def sesver():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Bir sey de!")
        audio = r.listen(source)
        data = ""
        try:
            data = r.recognize_google(audio, language='tr-tr')
            data = data.lower()
            return data
        except ValueError:
            pass

data = sesver()
</code>```

Body:
You must add 4 spaces for indent.

def sesver():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Bir sey de!")
        audio = r.listen(source)
        data = ""
        try:
            data = r.recognize_google(audio, language='tr-tr')
            data = data.lower()
            return data
        except ValueError:
            pass

data = sesver()


问:
Accessing FragmentManager in a custom view class
In my custom view I have a Java class running a simple game. When the game is finished I'd like to display my DialogFragment, but the getFragmentManager() method seems to be undefined.

```<code>FragmentManager manager = getFragmentManager();
Finish finish = new Finish();
finish.show(manager, "done");
</code>```

I've tried getting the manager through a Fragment obj as:

```<code>Fragment fragment = new Fragment();
FragmentManager manager = fragment.getFragmentManager();
</code>```

But that returns as null. I know it's a new Fragment instance, but I'm not sure what value to give it. Any help would be much appreciated.

答:
For AndroidX, you can try:

```<code>ContextThemeWrapper themeWrapper = (ContextThemeWrapper) getContext();
FragmentManager fm = ((AppCompatActivity) themeWrapper.getBaseContext()).getSupportFragmentManager();
</code>```

As recommoned by @k0sh, instaceof safety check is recommonded.

Body:
In my custom view I have a Java class running a simple game. When the game is finished I'd like to display my DialogFragment, but the getFragmentManager() method seems to be undefined.

FragmentManager manager = getFragmentManager();
Finish finish = new Finish();
finish.show(manager, "done");

I've tried getting the manager through a Fragment obj as:

Fragment fragment = new Fragment();
FragmentManager manager = fragment.getFragmentManager();

But that returns as null. I know it's a new Fragment instance, but I'm not sure what value to give it. Any help would be much appreciated.

Body:
For AndroidX, you can try:

ContextThemeWrapper themeWrapper = (ContextThemeWrapper) getContext();
FragmentManager fm = ((AppCompatActivity) themeWrapper.getBaseContext()).getSupportFragmentManager();

As recommoned by @k0sh, instaceof safety check is recommonded.


问:
cant schedule prometheus-server pod on kubernetes, pod reports taints but nodes dont have any taint
i am getting

```<code>0/7 nodes are available: 2 node(s) had taints that the pod didn't tolerate, 5 node(s) had volume node affinity conflict.
</code>```

for my prometheus server pod but if i check each nodes there are no taints. and there is enough cpu and memory to be allocated.. what am i missing here?

i tried deleting the pods and even the deployment object but the error still persists

all nodes have 0 taints..
this is a fresh prometheus install on a new kubernetes cluster
the yaml files that i have used to work until now when i needed to deploy a new kubernetes cluster

答:
0/7 nodes are available: 2 node(s) had taints that the pod didn't tolerate, 5 node(s) had volume node affinity conflict.

The message is specific: it's not the taints that are keeping your prometheus pods off of your workers, it's the volume that is the problem. If you are in AWS, it's because your volume is in an availability zone that your workers are not (so, a us-west-2a volume and us-west-2c workers, for example)

The shortest path to success in your situation may be to either recreate the volume in the correct A.Z. if it was empty, or manually create a new volume and copy the data into an A.Z. that matches your workers, or (of course) spin up a new worker in the A.Z. that matches the volume

all nodes have 0 taints..

Is for sure not true for two reasons: because the scheduler clearly says there are two Nodes with taints, and because unless you specifically stripped them off, the masters are almost always(?) provisioned with node.kubernetes.io/master:NoSchedule taints explicitly to keep workloads off of them

Body:
i am getting

0/7 nodes are available: 2 node(s) had taints that the pod didn't tolerate, 5 node(s) had volume node affinity conflict.

for my prometheus server pod but if i check each nodes there are no taints. and there is enough cpu and memory to be allocated.. what am i missing here?

i tried deleting the pods and even the deployment object but the error still persists

all nodes have 0 taints..
this is a fresh prometheus install on a new kubernetes cluster
the yaml files that i have used to work until now when i needed to deploy a new kubernetes cluster


问:
Warning "Potential leak of an object allocated on line ..." when declaring a 2D array
Initially i declared a 2D array in this way:

```<code>subUrb = [[NSArray alloc] initWithObjects:
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] ,
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil],
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil],
     nil];
</code>```

But when i try to 'analyze' the warnings of the project, i got three same type of issues in this chunk of code - "potential leak of an object allocated on line xxx"

I noticed that to get rid of it, i have to write sth like this:

```<code>subUrb =
    [[NSArray alloc] initWithObjects:
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil] autorelease],
        nil];
</code>```

Then i will not get any analyze warnings. But i dun like this...it is not logical. This 2D array should never be released in my controller actually, the entire 2D array should be retained for the entire life time of the controller for a PickerView.

How should I declare the 2D array more elegantly?

答: Your second method is correct. The point is that the enclosing array will take ownership of the nested objects, while the additional ownership lien you gain via alloc is left dangling. A marginally neater approach is to use the class method arrayWithObjects instead of alloc/initWithObjects/autorelease but it amounts to the same thing.

Body:
Initially i declared a 2D array in this way:

subUrb = [[NSArray alloc] initWithObjects:
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] ,
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil],
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil],
     nil];

But when i try to 'analyze' the warnings of the project, i got three same type of issues in this chunk of code - "potential leak of an object allocated on line xxx"

I noticed that to get rid of it, i have to write sth like this:

subUrb =
    [[NSArray alloc] initWithObjects:
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil] autorelease],
        nil];

Then i will not get any analyze warnings. But i dun like this...it is not logical. This 2D array should never be released in my controller actually, the entire 2D array should be retained for the entire life time of the controller for a PickerView.

How should I declare the 2D array more elegantly?


问:
GCC |warning: implicit declaration of function '_stricmp' [-Wimplicit-function-declaration]|
Written in pure C..

But I have included string.h as:

```<code>#include <string.h>     // for strnlen
#include <stdlib.h>     // for _countof, _itoa fns, _MAX_COUNT macros
#include <conio.h>      // for  _getch
#include <process.h>    // for system
#include <io.h>         // for findfirst
#include <locale.h>
</code>```

called here:

```<code>if( argc != 2 )   {
  printf("Usage: extension .001 or .alm only\n");
  return(0);
}
else printf("Read %d %s\n",argc, argv[1]);

if( !_getcwd((char *)cdir, sizeof(cdir)))    {
  printf("\n ! ERROR ! obtaining current disc directory!");
  printf("\n .. any key ..");
  _getch();
  exit(-1);
}
printf("\n Directory: %s\n", cdir);

if(!_stricmp(argv[1],"alm"))
  sprintf(csrch,"*.alm");
else
  sprintf(csrch,"*.001");
</code>```

So why the error/warning?

答:
Maybe you could manually convert the strings to all lowercase and then use strcmp?</p>

```<code>int stricmp(const char *string1, const char *string2) {
    char* tmp1 = malloc(sizeof(string1));
    char* tmp2 = malloc(sizeof(string2));

    strcpy(tmp1, string1);
    strcpy(tmp2, string2);

    for (int i = 0; i < strlen(tmp1); i++)
        tmp1[i] = tolower(tmp1[i]);

    for (int i = 0; i < strlen(tmp2); i++)
        tmp2[i] = tolower(tmp2[i]);

    int res = strcmp(tmp1, tmp2);

    free(tmp1);
    free(tmp2);

    return res;
}
</code>```

Body:
Written in pure C..

But I have included string.h as:

#include <string.h>     // for strnlen
#include <stdlib.h>     // for _countof, _itoa fns, _MAX_COUNT macros
#include <conio.h>      // for  _getch
#include <process.h>    // for system
#include <io.h>         // for findfirst
#include <locale.h>

called here:

if( argc != 2 )   {
  printf("Usage: extension .001 or .alm only\n");
  return(0);
}
else printf("Read %d %s\n",argc, argv[1]);

if( !_getcwd((char *)cdir, sizeof(cdir)))    {
  printf("\n ! ERROR ! obtaining current disc directory!");
  printf("\n .. any key ..");
  _getch();
  exit(-1);
}
printf("\n Directory: %s\n", cdir);

if(!_stricmp(argv[1],"alm"))
  sprintf(csrch,"*.alm");
else
  sprintf(csrch,"*.001");

So why the error/warning?

Body:
Maybe you could manually convert the strings to all lowercase and then use strcmp?

int stricmp(const char *string1, const char *string2) {
    char* tmp1 = malloc(sizeof(string1));
    char* tmp2 = malloc(sizeof(string2));

    strcpy(tmp1, string1);
    strcpy(tmp2, string2);

    for (int i = 0; i < strlen(tmp1); i++)
        tmp1[i] = tolower(tmp1[i]);

    for (int i = 0; i < strlen(tmp2); i++)
        tmp2[i] = tolower(tmp2[i]);

    int res = strcmp(tmp1, tmp2);

    free(tmp1);
    free(tmp2);

    return res;
}


问:
Switch between different types of buttons
So I used a codepen to implement buttons into my homepage here. The buttons work, but the issue is now the ToDo (+) button on the right, and the ToDo (x) button which appears after adding one, also have the effect of the button ToDo(+). Specifically, hovering over them has two parallel lines swing in from opposite ends. How do I separate them from each other so one doesn't affect the other? The specific css code is here:

```<code>button{
  background:#00000088;
  color:#fff;
  border:none;
  position:relative;
  height:40px;
  font-size:1.2em;
  padding:0 1em;
  cursor:pointer;
  margin: 0 0.25em;
  transition:800ms ease all;
  outline:none;
}
button:hover{
  background:#ffffff;
  color:#000;
}
button:before,button:after{
  content:'';
  position:absolute;
  top:0;
  right:0;
  height:3px;
  width:0;
  background: #bd818d;
  transition:400ms ease all;
}
button:after{
  right: inherit;
  top: 47px;
  left: -5px;
  bottom: 0;
}
button:hover:before,button:hover:after{
  width:100%;
  transition:800ms ease all;
}
</code>```

答:
This is where the problem is:

```<code>button{ /* YourStyle */}
</code>```

This is telling your browser that it must apply YourStyle above everywhere where it sees a button element. And your browser, remains loyal and obeys your instructions. To solve this, you must give a button names that defines it.

Example:

```<code><button class='todo add'></button>
<button class='todo close'></button>
</code>```

Referencing these buttons with css:

```<code>/* When you want to reference all buttons */
button{} or .todo{}

/* When you wish to target the todo add only */
.todo.add{} or .add{}

/* When you wish to target the todo close only */
.todo.close{} or .close{}
</code>```

try giving your buttons class names or id and referencing them from css styles.

Body:
So I used a codepen to implement buttons into my homepage here. The buttons work, but the issue is now the ToDo (+) button on the right, and the ToDo (x) button which appears after adding one, also have the effect of the button ToDo(+). Specifically, hovering over them has two parallel lines swing in from opposite ends. How do I separate them from each other so one doesn't affect the other? The specific css code is here:

button{
  background:#00000088;
  color:#fff;
  border:none;
  position:relative;
  height:40px;
  font-size:1.2em;
  padding:0 1em;
  cursor:pointer;
  margin: 0 0.25em;
  transition:800ms ease all;
  outline:none;
}
button:hover{
  background:#ffffff;
  color:#000;
}
button:before,button:after{
  content:'';
  position:absolute;
  top:0;
  right:0;
  height:3px;
  width:0;
  background: #bd818d;
  transition:400ms ease all;
}
button:after{
  right: inherit;
  top: 47px;
  left: -5px;
  bottom: 0;
}
button:hover:before,button:hover:after{
  width:100%;
  transition:800ms ease all;
}

Body:
This is where the problem is:

button{ /* YourStyle */}

This is telling your browser that it must apply YourStyle above everywhere where it sees a button element. And your browser, remains loyal and obeys your instructions. To solve this, you must give a button names that defines it.

Example:

<button class='todo add'></button>
<button class='todo close'></button>

Referencing these buttons with css:

/* When you want to reference all buttons */
button{} or .todo{}

/* When you wish to target the todo add only */
.todo.add{} or .add{}

/* When you wish to target the todo close only */
.todo.close{} or .close{}

try giving your buttons class names or id and referencing them from css styles.


答:
The error (exception) is rather informative:

```<code>terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr: __pos (which is 8) > this->size() (which is 7)
</code>```

so you know that you are accessing memory that string of yours (n (also why call it n, and not str, for example? Anyway.)). When you do:

```<code>for(int i = 0; i < n.size(); i++)
</code>```

and then request the substring, when you reach towards the end, you go out of range, since you go one by one (i++), **regardless of what deli's value is. However, deli grows according to the value of cut, thus you should check if deli is less that the size of your initial string to keep looping.

Minimal working example:

```<code>#include <string>
#include <iostream>
using namespace std;

int main() {

    int cut;
    string n;
    cout << "Enter string: " << endl;
    cin >> n;
    cout << "Enter size to cut: " << endl;
    cin >> cut;
    string res;
    unsigned int deli = 0;
    do {
      res = n.substr(deli,cut);
      cout << "The deli is: " << deli << endl;
      deli += cut;
      cout << res << endl;
    } while (deli < n.size());

    return 0;
}
</code>```

Output:

```<code>Enter string: Stackoverflow
Enter size to cut: 5
The deli is: 0
Stack
The deli is: 5
overf
The deli is: 10
low
</code>```

Title: How can i use substring in appropriate way?

Body:
When i try to print parts of string using substr() i got error titled by "out of range" , how can i fix this problem.

#include <string>
#include <iostream>
using namespace std;

int main()
{

    int cut;
    string n;
    cout << "Enter string: " << endl;
    cin >> n;
    cout << "Enter size to cut: " << endl;
    cin >> cut;
    string res;
    int deli = 0;
    for(int i = 0; i < n.size(); i++)
    {

        res = n.substr(deli,cut);
        cout << "The deli is: " << deli << endl;
        deli+=cut;

        cout << res << endl;
    }

    return 0;
}

Body:
The error (exception) is rather informative:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr: __pos (which is 8) > this->size() (which is 7)

so you know that you are accessing memory that string of yours (n (also why call it n, and not str, for example? Anyway.)). When you do:

for(int i = 0; i < n.size(); i++)

and then request the substring, when you reach towards the end, you go out of range, since you go one by one (i++), **regardless of what deli's value is. However, deli grows according to the value of cut, thus you should check if deli is less that the size of your initial string to keep looping.

Minimal working example:

#include <string>
#include <iostream>
using namespace std;

int main() {

    int cut;
    string n;
    cout << "Enter string: " << endl;
    cin >> n;
    cout << "Enter size to cut: " << endl;
    cin >> cut;
    string res;
    unsigned int deli = 0;
    do {
      res = n.substr(deli,cut);
      cout << "The deli is: " << deli << endl;
      deli += cut;
      cout << res << endl;
    } while (deli < n.size());

    return 0;
}

Output:

Enter string: Stackoverflow
Enter size to cut: 5
The deli is: 0
Stack
The deli is: 5
overf
The deli is: 10
low


问:
Large file to be read in chunks
I need a process a large file and insert into Db and don't want to spend lot of ram doing the same. I know we can read line in streaming mode by using apache commons API or buffered reader....bt I wish to insert in DB in  batch mode like 1000 insertions at 1 go and not 1 by 1. ....is reading the file line by line  ,adding to a list ,counting size ,inserting and refreshing the list of lines the only option to achieve this ?</p>

答:
According to your description, Spring-Batch fit very well.

Basically, it use chunk concept to read/process/write the content. By the way, it can be concurrent for performance.

    @Bean
    protected Step loadFeedDataToDbStep() {
        return stepBuilder.get("load new fincon feed").<com.xxx.Group, FinconFeed>chunk(250)
                .reader(itemReader(OVERRIDDEN_BY_EXPRESSION))
                .processor(itemProcessor(OVERRIDDEN_BY_EXPRESSION, OVERRIDDEN_BY_EXPRESSION_DATE, OVERRIDDEN_BY_EXPRESSION))
                .writer(itemWriter())
                .listener(archiveListener())
                .build();
    }
```

You can refer to here for more

Title: Large file to be read in chunks

Body:
According to your description, Spring-Batch fit very well.

Basically, it use chunk concept to read/process/write the content. By the way, it can be concurrent for performance.

    @Bean
    protected Step loadFeedDataToDbStep() {
        return stepBuilder.get("load new fincon feed").<com.xxx.Group, FinconFeed>chunk(250)
                .reader(itemReader(OVERRIDDEN_BY_EXPRESSION))
                .processor(itemProcessor(OVERRIDDEN_BY_EXPRESSION, OVERRIDDEN_BY_EXPRESSION_DATE, OVERRIDDEN_BY_EXPRESSION))
                .writer(itemWriter())
                .listener(archiveListener())
                .build();
    }

You can refer to here for more


问:
Deleting a specific tag in xml file
I am stuck in the code as I want to delete a specific tag from xml file. Actually my code finds the seType tag in xml file and delete data between in node which is working as per my expecations but I also want to delete that specific in tag also but unable to find solution for this. For example, when I give seType 921 then it will delete all the tags between  tags but it will not delete  tag</p>

答:
I would select the in node using XPath with Select-Xml instead, and then call RemoveChild to specifically remove that node:

```<code>$array = @($xml |Select-Xml -XPath "//in[se/seType[. = $name]]" |Select-Object -Expand Node)

$array | ForEach-Object {
  $_.ParentNode.RemoveChild($_)
} |Out-Null
</code>```

Title: Deleting a specific tag in xml file

Body:
I would select the in node using XPath with Select-Xml instead, and then call RemoveChild to specifically remove that node:

$array = @($xml |Select-Xml -XPath "//in[se/seType[. = $name]]" |Select-Object -Expand Node)

$array | ForEach-Object {
  $_.ParentNode.RemoveChild($_)
} |Out-Null


问:
A problem in the tableview section headview with hitTest method

I custom a lightGray view. The lightGray view has a property button. The button's backgroundColor is red.

I overwrite the  hitTest method in lightGray view.

```<code>- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
        if (!self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
            return nil;
        }

        if([self pointInside:point withEvent:event]){
             return self.testButton;
        }

        return nil;

    }
</code>```

As a result, the cursor at the point in the image above. I click the button could response.

If I click in the left area of lightGray view. The red button couldn't response.

What's the reason?

My real problem is the same problem in the tableview section headview. I write this demo to test and ask this question.

答:
I was able to reproduce this behaviour even not using a table view, just a custom view, and it really looks strange - if we return button from hitTest, button's action gets fired not at whole area of the gray view, but rather only at some distance around the button.

I added a test view with a tap gesture recognizer looking for difference with button behaviour and it works as expected. So as a workaround you may replace the button with a view plus gesture recognizer.

```<code>- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (!self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
        return nil;
    }

//    if (CGRectContainsPoint(self.bounds, point)) {
//        return self.testButton; // fires only at some distance
//    }

    if (CGRectContainsPoint(self.bounds, point)) {
        return self.testView; // fires for every point inside gray view
    }

    return [super hitTest:point withEvent:event];
}

- (IBAction)testButtonTouchUpInside:(UIButton *)sender
{
    NSLog(@"BTN HIT"); // Not OK
}

- (IBAction)testViewTap:(UITapGestureRecognizer *)sender
{
    NSLog(@"VIEW TAP"); // OK
}
</code>```

Body:
I custom a lightGray view. The lightGray view has a property button. The button's backgroundColor is red.

I overwrite the  hitTest method in lightGray view.

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
        if (!self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
            return nil;
        }

        if([self pointInside:point withEvent:event]){
             return self.testButton;
        }

        return nil;

    }

As a result, the cursor at the point in the image above. I click the button could response.

If I click in the left area of lightGray view. The red button couldn't response.

What's the reason?

My real problem is the same problem in the tableview section headview. I write this demo to test and ask this question.

Body:
I was able to reproduce this behaviour even not using a table view, just a custom view, and it really looks strange - if we return button from hitTest, button's action gets fired not at whole area of the gray view, but rather only at some distance around the button.

I added a test view with a tap gesture recognizer looking for difference with button behaviour and it works as expected. So as a workaround you may replace the button with a view plus gesture recognizer.

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (!self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
        return nil;
    }

//    if (CGRectContainsPoint(self.bounds, point)) {
//        return self.testButton; // fires only at some distance
//    }

    if (CGRectContainsPoint(self.bounds, point)) {
        return self.testView; // fires for every point inside gray view
    }

    return [super hitTest:point withEvent:event];
}

- (IBAction)testButtonTouchUpInside:(UIButton *)sender
{
    NSLog(@"BTN HIT"); // Not OK
}

- (IBAction)testViewTap:(UITapGestureRecognizer *)sender
{
    NSLog(@"VIEW TAP"); // OK
}


问:
How to make child components aware of nested init data in Vue?
So, this is my test code:

```<code>Vue.component('area-selectors-box', {
  template: `
    <div class="selectors-box">
      <area-selector v-for="select in selects"></area-selector>
    </div>
  `,
  props:['selects']
});

Vue.component('area-selector', {
  template: `
    <select>
      <option disabled selected value="">Seleziona continente</option>
      <option :areas="select.areas" v-for="area in areas">{{ area.name }}</option>
    </select>
  `,
  props:['select']
});

var dealer_manager = new Vue({
  el: '#dealers-main-box'
  ,data:{
    dealers:[],
    selects:[]
  }
  ,mounted: function(){
  }
  ,created: function(){
    this.get_dealers_data('00');
  }
  ,methods: {
    get_dealers_data: function(area_id){
      var app = this;

      $.ajax({
        type: 'GET'
        ,dataType: 'json'
        ,url: dealers_settings.api_url + area_id
      })
      .done(function(json_data, status, xhr){
        if(!json_data) return;
        var parsed = JSON.parse(json_data);
        if(parsed.type == 'areas'){
          app.selects.push({
            areas: parsed.items
          });
        } else if(parsed.type == 'dealers'){
          app.dealers = parsed.items;
        }
      }.bind(this))
      .fail(function( jqXHR, textStatus, errorThrown ){
      }.bind(this))
    }// get dealers data
  }
});
</code>```

This is the json data I get and pass to area-selectors-box:

Fine. But data in area-selector is empty. How can I make it aware of areas during initialization? As you can see, areas is an array of objects.

Strangely enough (for me), if I do all in one component, it will work properly:

```<code>Vue.component('area-selectors-box', {
  template: `
    <div class="selectors-box">
      <select :selects="selects" v-for="select in selects">
        <option disabled selected value="">Seleziona continente</option>
        <option v-for="area in select.areas">{{area.name}}</option>
      </select>
    </div>
  `,
  props:['selects']
});
</code>```

So I guess what I should learn is how to pass sub-data to sub-components... Any help? :)

答:
Solved: I have to pass quite anything..</p>

```<code>Vue.component('area-selectors-box', {
  template: `
    <div class="selectors-box">
      <area-selector v-for="select in selects" :select="select"></area-selector>
    </div>
  `,
  props:['selects']
});

Vue.component('area-selector', {
  template: `
    <select :select="select">
      <option disabled selected value="">Seleziona continente</option>
      <area-option v-for="area in select.areas" :area="area" :key="area.term_id"></area-option>
    </select>
  `,
  props:['select']
});

Vue.component('area-option', {
  template: `<option :area="area">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});
</code>```

Body:
So, this is my test code:

Vue.component('area-selectors-box', {
  template: `

      <area-selector v-for="select in selects"></area-selector>

  `,
  props:['selects']
});

Vue.component('area-selector', {
  template: `
    <select>
      <option disabled selected value="">Seleziona continente</option>
      <option :areas="select.areas" v-for="area in areas">{{ area.name }}</option>
    </select>
  `,
  props:['select']
});

var dealer_manager = new Vue({
  el: '#dealers-main-box'
  ,data:{
    dealers:[],
    selects:[]
  }
  ,mounted: function(){
  }
  ,created: function(){
    this.get_dealers_data('00');
  }
  ,methods: {
    get_dealers_data: function(area_id){
      var app = this;

      $.ajax({
        type: 'GET'
        ,dataType: 'json'
        ,url: dealers_settings.api_url + area_id
      })
      .done(function(json_data, status, xhr){
        if(!json_data) return;
        var parsed = JSON.parse(json_data);
        if(parsed.type == 'areas'){
          app.selects.push({
            areas: parsed.items
          });
        } else if(parsed.type == 'dealers'){
          app.dealers = parsed.items;
        }
      }.bind(this))
      .fail(function( jqXHR, textStatus, errorThrown ){
      }.bind(this))
    }// get dealers data
  }
});

This is the json data I get and pass to area-selectors-box:

Fine. But data in area-selector is empty. How can I make it aware of areas during initialization? As you can see, areas is an array of objects.

Strangely enough (for me), if I do all in one component, it will work properly:

Vue.component('area-selectors-box', {
  template: `

      <select :selects="selects" v-for="select in selects">
        <option disabled selected value="">Seleziona continente</option>
        <option v-for="area in select.areas">{{area.name}}</option>
      </select>

  `,
  props:['selects']
});

So I guess what I should learn is how to pass sub-data to sub-components... Any help? :)

Body:
Solved: I have to pass quite anything..

Vue.component('area-selectors-box', {
  template: `
    <div class="selectors-box">
      <area-selector v-for="select in selects" :select="select"></area-selector>
    </div>
  `,
  props:['selects']
});

Vue.component('area-selector', {
  template: `
    <select :select="select">
      <option disabled selected value="">Seleziona continente</option>
      <area-option v-for="area in select.areas" :area="area" :key="area.term_id"></area-option>
    </select>
  `,
  props:['select']
});

Vue.component('area-option', {
  template: `<option :area="area">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});


问:
ASP.NET Page_Load values are lagging one postback behind
I have a foreach loop in the Page_Load method of my one page to determine whether to Enable a button or not.

Code:

```<code>foreach (var class in classes)
{
    for (var i = studentsList.Count - 1; i >= 0; i--)
    {
        if (studentsList[i].Id == class.student_id)
            studenstList.Remove(studentsList[i]);
    }
}
if (studentsList.Count == 0)
{
    button1.Enabled = false;
    button1.Text = "a";
}
else
{
    button1.Enabled = true;
    button1.Text = "b";
}
if (Page.IsPostBack) { return; }
</code>```

The issue:

The value of studentsList.Count is lagging behind by a postback. If after the loop it should be 1, it only has the value of 1 at the next postback. I've debugged to confirm this is the case.

答:
You can move this foreach loop to the Page_PreLoad method and give it a try.

Here anof life cycle of an ASP.NET page: http://msdn.microsoft.com/en-us/library/ms178472.aspx#lifecycle_events

Body:
I have a foreach loop in the Page_Load method of my one page to determine whether to Enable a button or not.

Code:

foreach (var class in classes)
{
    for (var i = studentsList.Count - 1; i >= 0; i--)
    {
        if (studentsList[i].Id == class.student_id)
            studenstList.Remove(studentsList[i]);
    }
}
if (studentsList.Count == 0)
{
    button1.Enabled = false;
    button1.Text = "a";
}
else
{
    button1.Enabled = true;
    button1.Text = "b";
}
if (Page.IsPostBack) { return; }

The issue:

The value of studentsList.Count is lagging behind by a postback. If after the loop it should be 1, it only has the value of 1 at the next postback. I've debugged to confirm this is the case.


问:
Integrate Facebook messenger into CRM without bot?
we have built a very simple bot that simply passes any message onto our own application. (we want to answer questions asked from our customers to be handled straight from our CRM application for customer service purpose)

Now, the bot is declined with message:

Thank you for your submission. We tested the messenger experience on your associated page and received either no response from your messenger bot or received a human response. Please resubmit with the new, improved version of your bot.

Which raises the question for me: is it even allowed to do human assistance via the messenger API? Or is it bot only? I have read through all the platform policies, use case examples, etc.

So, how do I create the simplest integration? (send message straight through to one of our customer service users?)

答: Making a bot is easy if you use Wit.ai which is an NLP and speech API. It can integrate with the messenger/graph API. Basically, you send text to wit.ai and it returns the intent. For example: you send "get me a large pizza" to Wit and it returns something like (intent = pizza, size=large, time = now) You could also try api.ai but in my opinion, it is not as good yet.</p>


问:
How to make array of data as Key of Database Child
Previously, I wanted to query my array data in my Firebase, but I found that query is not support in array data in firebase. Therefore, I want to make my array as key with the value being true. Thank you in advance.

For example,
when I have the array = ["a", "b", "c"]

I want to change it as

```<code>subject
-------"a":"true"
-------"b":"true"
-------"c":"true"
</code>```

答:
I think what's being asked is how to take an array of strings as shown in the question and write them to Firebase where each string element is a key and it has a child value of true.

We can leverage a Swift Dictionary's uniqueKeysWithValues function to create key: value pairs and store them in a dictionary which can then be written to Firebase.

```<code>let array = ["a", "b", "c"]
let dict = Dictionary(uniqueKeysWithValues: array.map { ($0, true) })
fbRef.child("subject").setValue(dict)
</code>```

and the result will be

```<code>subject
   a: true
   b: true
   c: true
</code>```

Another option is to create an extension to add functionality to arrays (a sequence).

```<code>extension Sequence {
    func toDictionary() -> [String: Bool] {
        var dict = [String: Bool]()
        for element in self {
            if let s = element.self as? String {
                dict[s] = true
            }
        }
        return dict
    }
}
</code>```

and the usage

```<code>let anArray = ["x", "y", "z"]
let dict = anArray.toDictionary()
fbRef.child("subject").setValue(dict)
</code>```

This could use more error checking and assumes the elements are always strings.

Body:
Previously, I wanted to query my array data in my Firebase, but I found that query is not support in array data in firebase. Therefore, I want to make my array as key with the value being true. Thank you in advance.

For example,
when I have the array = ["a", "b", "c"]

I want to change it as

subject
-------"a":"true"
-------"b":"true"
-------"c":"true"

Body:
I think what's being asked is how to take an array of strings as shown in the question and write them to Firebase where each string element is a key and it has a child value of true.

We can leverage a Swift Dictionary's uniqueKeysWithValues function to create key: value pairs and store them in a dictionary which can then be written to Firebase.

let array = ["a", "b", "c"]
let dict = Dictionary(uniqueKeysWithValues: array.map { ($0, true) })
fbRef.child("subject").setValue(dict)

and the result will be

subject
   a: true
   b: true
   c: true

Another option is to create an extension to add functionality to arrays (a sequence).

extension Sequence {
    func toDictionary() -> [String: Bool] {
        var dict = [String: Bool]()
        for element in self {
            if let s = element.self as? String {
                dict[s] = true
            }
        }
        return dict
    }
}

and the usage

let anArray = ["x", "y", "z"]
let dict = anArray.toDictionary()
fbRef.child("subject").setValue(dict)

This could use more error checking and assumes the elements are always strings.


问:
Python3: f-string {} symbols screening
i want to use f-string in my python code to write some json, but got a problem with screening {} symbols. What the correct way to screen lonely { } symbols? For example i want to write:

```<code>data = f'{[{{prod_id},{quantity},{size}}]}'
</code>```

I cant get how to write it correctly, and basic python screening not working for me for some reason here.

答:
You can escape curly braces in f-strings by doubling them, e.g.</p>

```<code>data = f"{{[{{{prod_id},{quantity},{size}}}]}}"
</code>```

Title: Python3: f-string {} symbols screening

Body:
i want to use f-string in my python code to write some json, but got a problem with screening {} symbols. What the correct way to screen lonely { } symbols? For example i want to write:

data = f'{[{{prod_id},{quantity},{size}}]}'

I cant get how to write it correctly, and basic python screening not working for me for some reason here.

Body:
You can escape curly braces in f-strings by doubling them, e.g.

data = f"{{[{{{prod_id},{quantity},{size}}}]}}"


问:
php nested array and object structure path for copy&paste
When faced with complex nested php structures, what is a convenient way to print the path to a specific value -- for copy&paste -- as valid php code?

Example:
A big mess of objects holding arrays, holding other objects, holding more arrays.

```<code>$object->third->values[3]['eng']->source->raw->title['html'] =
</code>```

$object can easily be print_r() or var_dump() for an overview.
But I still need to assemble the path deep down to desired value, to acess it in code.
Which takes some time to get right during debugging.

答:
You can do with Xpath, was originally created to work with XML, but allows interate object by a path string.

```<code><?xml version="1.0" encoding="UTF-8"?>
<PRODUCTS>
<PRODUCT category="software">
<SKU>soft32323</SKU>
<SUB_CATEGORY>Business Analysis</SUB_CATEGORY>
<NAME>Widget Reporting</NAME>
<PRICE>4500</PRICE>
</PRODUCT>
<PRODUCT category="software">
<SKU>soft32323</SKU>
<SUB_CATEGORY>Business Analysis</SUB_CATEGORY>
<NAME>Pro Reporting</NAME>
<PRICE>2300</PRICE>
</PRODUCT>
<PRODUCT category="storage">
<SKU>soft32323</SKU>
<SUB_CATEGORY>Tape Systems</SUB_CATEGORY>
<NAME>Tapes Abound</NAME>
<PRICE>2300</PRICE>
</PRODUCT>
<PRODUCT category="storage">
<SKU>soft32323</SKU>
<SUB_CATEGORY>Disk Systems</SUB_CATEGORY>
<NAME>Widget100 Series</NAME>
<PRICE>6500</PRICE>
</PRODUCT>
</PRODUCTS>
</code>```

// PHP Code  sample usin SimpleXML

```<code>$xml = simplexml_load_file("products.xml");
$products = $xml->xpath("/PRODUCTS/PRODUCT/NAME");
print_r($products);
</code>```

OUTPUT:

```<code>Array ( [0] => SimpleXMLElement Object ( [0] => Widget Reporting )
[1] => SimpleXMLElement Object ( [0] => Pro Reporting ) [2] =>
SimpleXMLElement Object ( [0] => Tapes Abound ) [3] =>
SimpleXMLElement Object ( [0] => Widget100 Series ) )
</code>```

Body:
When faced with complex nested php structures, what is a convenient way to print the path to a specific value -- for copy&paste -- as valid php code?

Example:
A big mess of objects holding arrays, holding other objects, holding more arrays.

$object->third->values[3]['eng']->source->raw->title['html'] =

$object can easily be print_r() or var_dump() for an overview.
But I still need to assemble the path deep down to desired value, to acess it in code.
Which takes some time to get right during debugging.

Body:
You can do with Xpath, was originally created to work with XML, but allows interate object by a path string.

<?xml version="1.0" encoding="UTF-8"?>
<PRODUCTS>
<PRODUCT category="software">
<SKU>soft32323</SKU>
<SUB_CATEGORY>Business Analysis</SUB_CATEGORY>
<NAME>Widget Reporting</NAME>
<PRICE>4500</PRICE>
</PRODUCT>
<PRODUCT category="software">
<SKU>soft32323</SKU>
<SUB_CATEGORY>Business Analysis</SUB_CATEGORY>
<NAME>Pro Reporting</NAME>
<PRICE>2300</PRICE>
</PRODUCT>
<PRODUCT category="storage">
<SKU>soft32323</SKU>
<SUB_CATEGORY>Tape Systems</SUB_CATEGORY>
<NAME>Tapes Abound</NAME>
<PRICE>2300</PRICE>
</PRODUCT>
<PRODUCT category="storage">
<SKU>soft32323</SKU>
<SUB_CATEGORY>Disk Systems</SUB_CATEGORY>
<NAME>Widget100 Series</NAME>
<PRICE>6500</PRICE>
</PRODUCT>
</PRODUCTS>

// PHP Code  sample usin SimpleXML

$xml = simplexml_load_file("products.xml");
$products = $xml->xpath("/PRODUCTS/PRODUCT/NAME");
print_r($products);

OUTPUT:

Array ( [0] => SimpleXMLElement Object ( [0] => Widget Reporting )
[1] => SimpleXMLElement Object ( [0] => Pro Reporting ) [2] =>
SimpleXMLElement Object ( [0] => Tapes Abound ) [3] =>
SimpleXMLElement Object ( [0] => Widget100 Series ) )


问:
How to create Java project in Netbeans, without using Maven as default?
I'm currently trying to create a basic Java project. The first option that appears is "Java with Maven", which I already used, but isn't giving me the "Create Main Class" option that I need.

I'm using Apache Netbeans IDE 11.0, running on Windows 10, x64.
I've given it a whole day, updating and installing the most recent JDK versions I found, and still I'm unable to make it work.

I've also read this answer, but it's not working:
Can't create project on Netbeans 8.2

Here's an image of what I'm getting:

Any help is appreciated, thanks.

答:
The project templates were revised in Apache NetBeans 11.0 to give Maven projects greater prominence. From an Apache NetBeans blog post:

Restructuring of Project Templates in Apache NetBeans

There's been lots of discussion in the Apache NetBeans community about
  how best to express the fact that Apache Maven and Apache Gradle are
  more modern choices to be aware of than Apache Ant, while at the same
  time not implying that there's anything wrong with using Apache Ant.

Here's what we seem to have reached consensus around, i.e., move all
  Ant-based project templates into a separate Ant-specific folder, while
  putting the other two build systems higher and therefore more
  prominently in the list:

With the above, someone is less likely to simply go to the
  no-longer-existing Java category and then end up with an Ant-based
  project, without thinking about it. By default, the user of Apache
  NetBeans is now encouraged to consider Apache Maven and Apache Gradle
  first. The old Ant-related categories are still there, so as not to
  confuse anyone completely, just structured within a lower ranked "Java
  with Ant" category. The above also solves the discussion re "Java EE",
  i.e., here the idea, from discussions, is to name the category "Java
  Enterprise".

At startup, all categories are closed, i.e., none is more prominent
  initially than any other.

An objection one could have is that, if you're a complete Java newbie,
  you won't know what Maven, Gradle, or Ant are. Well, that has always
  been the case and NetBeans has artificially hidden that choice by
  having a category simply named "Java", which then resulted in everyone
  ending up with Ant-based projects. To turn that around and have a
  category simply named "Java" that results in Maven-based projects is
  probably not right either, i.e., a careful balance needs to be struck.

So if you created a project using File > New Project... > Java > Java Application in earlier releases of NetBeans, you should use File > New Project... > Java with Ant > Java Application in NetBeans 11.0.

Notes:

NetBeans Bug Report NETBEANS-2040 Maven First in New Project Wizard refers.

Also see the discussion at the start of this YouTube video The Rough Guide to Apache NetBeans 11.0.

Other project wizard changes in NetBeans 11.0:

In NetBeans 11.0 I had to install the Gradle plugin (Tools > Plugins > Available Plugins > Gradle) in order to see Java with Gradle in the Project Wizard.

In earlier releases of NetBeans you created a Java Enterprise project using File > New Project... > Java EE > ..., but in NetBeans 11.0 this has changed to File > New Project... > Java with Ant > Java Enterprise > ...


问:
@Value annotation is only loading default - not using property file

Problem

I think that I havn't understood something properly because my @Value is always loading the default calue.

Java Code

So I have the following:

```<code>@Value("${disableQuerySecurityDebug:false}")
private boolean disableQuerySecurityDebug;
</code>```

And this is set to false always.

Property file: application-disableQuerySecurityDebug.properties

I have a properties file called application-disableQuerySecurityDebug.properties.

And I have the following entry inside the file:

```<code>disableQuerySecurityDebugMne=true
</code>```

And I run the application with the following profile: disableQuerySecurityDebugMne

I was expecting the value to be set to true, but it is always false.

Update

Based on deadpool's answer, I ended up with the following:

```<code>    @Profile("disableQuerySecurityDebug") @Data
    @Configuration
    public class DisableSecurityConfig implements DisableQuerySecurityDebug {

        @Value("${disableQuerySecurityDebug:true}")
        private boolean securityDisabled;
    }

    @Profile("!disableQuerySecurityDebug") @Data
    @Configuration
    public class EnableSecurityConfig implements DisableQuerySecurityDebug{

        @Value("${disableQuerySecurityDebug:false}")
        private boolean securityDisabled;
    }

    public interface DisableQuerySecurityDebug{
        public boolean isSecurityDisabled();
    }
</code>```

答:
@Value annotation is only used to inject properties values into spring Beans from yml or properties file

This annotation can be used for injecting values into fields in Spring-managed beans and it can be applied at the field or constructor/method parameter level.

If you want to inject values based on profile specific then use @Profile on class

```<code>@Profile("disableQuerySecurityDebug")
@Configuration
public class Config {

 @Value("${disableQuerySecurityDebug:false}")
 private boolean disableQuerySecurityDebug;

  }
</code>```

You could also specify it on the command line by using the following switch:

```<code> java -jar demo.jar  --spring.profiles.active=disableQuerySecurityDebug
</code>```

Body:
Problem

I think that I havn't understood something properly because my @Value is always loading the default calue.

Java Code

So I have the following:

@Value("${disableQuerySecurityDebug:false}")
private boolean disableQuerySecurityDebug;

And this is set to false always.

Property file: application-disableQuerySecurityDebug.properties

I have a properties file called application-disableQuerySecurityDebug.properties.

And I have the following entry inside the file:

disableQuerySecurityDebugMne=true

And I run the application with the following profile: disableQuerySecurityDebugMne

I was expecting the value to be set to true, but it is always false.

Update

Based on deadpool's answer, I ended up with the following:

    @Profile("disableQuerySecurityDebug") @Data
    @Configuration
    public class DisableSecurityConfig implements DisableQuerySecurityDebug {

        @Value("${disableQuerySecurityDebug:true}")
        private boolean securityDisabled;
    }

    @Profile("!disableQuerySecurityDebug") @Data
    @Configuration
    public class EnableSecurityConfig implements DisableQuerySecurityDebug{

        @Value("${disableQuerySecurityDebug:false}")
        private boolean securityDisabled;
    }

    public interface DisableQuerySecurityDebug{
        public boolean isSecurityDisabled();
    }

Body:
@Value annotation is only used to inject properties values into spring Beans from yml or properties file

This annotation can be used for injecting values into fields in Spring-managed beans and it can be applied at the field or constructor/method parameter level.

If you want to inject values based on profile specific then use @Profile on class

@Profile("disableQuerySecurityDebug")
@Configuration
public class Config {

 @Value("${disableQuerySecurityDebug:false}")
 private boolean disableQuerySecurityDebug;

  }

You could also specify it on the command line by using the following switch:

 java -jar demo.jar  --spring.profiles.active=disableQuerySecurityDebug


问:
How to randomize a generator output in JavaScript?
Let's pretend I have a generator which eventually stops

function* letters () {
  let offset = 0
  while (offset < 26)
    yield String.fromCharCode(65 + offset++)
}

console.log(Array.from(letters()))
// => [ "A", "B", "C", ..., "X", "Y", "Z" ]```
</div>
</div>
</p>

<p>Using that generator as an input, I want to create another generator, but for this one I would like the values to come out in a randomized order</p>

```function* randomizeGen (gen) {
  // ...
}

Array.from(randomizeGen(letters()))
// => [ "X", "T", "L", "P", "A", ..., "G", "S", "B" ] (all 26 letters)
```

<p>The new generator should be lazy, like the first one, but I cannot figure out how to write it in a smart way</p>

```function shuffleArray (arr) {
  // return shuffled array
}

function* randomizeGen (gen) {
   const all = Array.from(gen) // help!
   for (const one of shuffleArray(all))
     yield one
}
```

This would work, but it does so by completely exhausting gen first. In reality, my initial generator outputs millions of values, so I don't think collecting them all in an array first is a good idea. The whole point of using a generator is that I can process the values one at a time

I honestly have no idea how to randomize the generator output but keep it lazy at the same time. Can someone please help?

答:
I'm not sure if it is the best approach. But you can use the below code to generate the alphabets in random order

function* letters() {
    let arr = [];
    let char = "";
    while (arr.length < 26) {
        let flag = true;
        while (flag) {
            char = String.fromCharCode(65 + Math.floor(Math.random() * 27));
            if (!arr.find(function(element){return element === char;})){
                arr.push(char);
                flag = false;
            }
        }
    yield char;
    }
}

console.log(Array.from(letters()))```

Body:
Let's pretend I have a generator which eventually stops

function* letters () {
  let offset = 0
  while (offset < 26)
    yield String.fromCharCode(65 + offset++)
}

console.log(Array.from(letters()))
// => [ "A", "B", "C", ..., "X", "Y", "Z" ]

Using that generator as an input, I want to create another generator, but for this one I would like the values to come out in a randomized order

function* randomizeGen (gen) {
  // ...
}

Array.from(randomizeGen(letters()))
// => [ "X", "T", "L", "P", "A", ..., "G", "S", "B" ] (all 26 letters)

The new generator should be lazy, like the first one, but I cannot figure out how to write it in a smart way

function shuffleArray (arr) {
  // return shuffled array
}

function* randomizeGen (gen) {
   const all = Array.from(gen) // help!
   for (const one of shuffleArray(all))
     yield one
}

This would work, but it does so by completely exhausting gen first. In reality, my initial generator outputs millions of values, so I don't think collecting them all in an array first is a good idea. The whole point of using a generator is that I can process the values one at a time

I honestly have no idea how to randomize the generator output but keep it lazy at the same time. Can someone please help?


问:
Is Docusign REST API supports signing group as a recipient?
I have not found any documentation in DocuSign REST API to add a signing group as a  recipient.

There is a SO post, but it is not helpful for me.

I have a signing group and DocuSign creates a signing group id. I have not set an alternate email address for notifications sent to this signing group.

Is there any option to add a signing group as a recipient ?

答:
Use the signingGroupId attribute of the signer tab type.

For the Apex SDK it looks like there is a Recipient.SigningGroup with attribute id


问:
How to wait for the 'end' of 'resize' event and only then perform an action?
So I currently use something like:

```<code>$(window).resize(function(){resizedw();});
</code>```

But this gets called many times while resizing process goes on. Is it possible to catch an event when it ends?

答:
This is what I use for delaying repeated actions, it can be called in multiple places in your code:

```<code>function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};
</code>```

Usage:

```<code>$(window).resize(function () {
   debounce(function() {
          //...
    }, 500);
});
</code>```

Body:
So I currently use something like:

$(window).resize(function(){resizedw();});

But this gets called many times while resizing process goes on. Is it possible to catch an event when it ends?

Body:
This is what I use for delaying repeated actions, it can be called in multiple places in your code:

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

Usage:

$(window).resize(function () {
   debounce(function() {
          //...
    }, 500);
});