问:
Is there a way to make different actions onresume() the first time the app start and after
I was making an app that needs a wifi connection to communicate with the app checks if it is connected and continue to mainActivity from the splash screen or asks you to connect and a button appears from back ground by animation and the button takes you to wifi setting. But when I return to my app it is stack in the page it only works when I restart the app it will check and continue </p>

```<code>public class MainActivity extends AppCompatActivity {
NetworkInfo wifiCheck;                               // declaration for the wifi checker
Timer timer;                                         // we declared a timer

ImageView bgapp, call, chat, file, vid;
TextView wifitext;
LinearLayout imagesplash, menu;
Animation frombottom;
Button btnCreat;
Button btnConnect;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    frombottom = AnimationUtils.loadAnimation(this, R.anim.frombottom);

    bgapp = (ImageView) findViewById(R.id.bgapp);
    call = (ImageView) findViewById(R.id.call);
    chat = (ImageView) findViewById(R.id.chat);
    file = (ImageView) findViewById(R.id.file);
    vid = (ImageView) findViewById(R.id.vid);
    wifitext = (TextView) findViewById(R.id.wifitext);
    imagesplash = (LinearLayout) findViewById(R.id.imgsplash);
    menu = (LinearLayout) findViewById(R.id.menu);

    initialApp();

    btnCreat = findViewById(R.id.btnCreat);
    btnCreat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent = new Intent(Intent.ACTION_MAIN, null);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.TetherSettings");
            intent.setComponent(cn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

        }

    });

    btnConnect = findViewById(R.id.btnConnect);
    btnConnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
        }
    });

}

public void openConnectedActivity() {
    Intent intent = new Intent(this, TheActivity.class);
    startActivity(intent);
    finish();
}

@Override
protected void onResume() {
    super.onResume();
    Toast.makeText(this, "I just came back", Toast.LENGTH_SHORT).show();

}

private void initialApp(){

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    wifiCheck = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (wifiCheck.isConnected()) {
        runIfConnected();
    } else {
        runIfnotConnected();
    }
}

private void runIfConnected(){
    // if it is connected it will do this
    imagesplash.animate().translationY(-350).setDuration(800).setStartDelay(8000);
    bgapp.animate().translationY(-490).setDuration(800).setStartDelay(8000);
    call.animate().alpha(0).setDuration(800).setStartDelay(8000);
    chat.animate().alpha(0).setDuration(800).setStartDelay(8000);
    file.animate().alpha(0).setDuration(800).setStartDelay(8000);
    vid.animate().alpha(0).setDuration(800).setStartDelay(8000);
    wifitext.animate().alpha(0).setDuration(800).setStartDelay(8000);

    menu.startAnimation(frombottom);

    // putting timer to start the Activity and kill the splash Screen

    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            openConnectedActivity();
        }
    }, 2000);
}

private void runIfnotConnected(){
    // if id is not connected is will do this

    imagesplash.animate().translationY(-350).setDuration(800).setStartDelay(8000);
    bgapp.animate().translationY(-490).setDuration(800).setStartDelay(8000);
    call.animate().alpha(0).setDuration(800).setStartDelay(8000);
    chat.animate().alpha(0).setDuration(800).setStartDelay(8000);
    file.animate().alpha(0).setDuration(800).setStartDelay(8000);
    vid.animate().alpha(0).setDuration(800).setStartDelay(8000);
    wifitext.animate().alpha(0).setDuration(800).setStartDelay(8000);

    menu.startAnimation(frombottom);

}

}
</code>```

答:
You could do 02 things:-

01:-Call the initialApp() method from the onResume() method.

02:-Use a handler to check if the device is connected to wifi repeatedly after a certain duration(for example 100 ms).If it is connected then call the initialApp() method.

Body:
I was making an app that needs a wifi connection to communicate with the app checks if it is connected and continue to mainActivity from the splash screen or asks you to connect and a button appears from back ground by animation and the button takes you to wifi setting. But when I return to my app it is stack in the page it only works when I restart the app it will check and continue

public class MainActivity extends AppCompatActivity {
NetworkInfo wifiCheck;                               // declaration for the wifi checker
Timer timer;                                         // we declared a timer

ImageView bgapp, call, chat, file, vid;
TextView wifitext;
LinearLayout imagesplash, menu;
Animation frombottom;
Button btnCreat;
Button btnConnect;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    frombottom = AnimationUtils.loadAnimation(this, R.anim.frombottom);

    bgapp = (ImageView) findViewById(R.id.bgapp);
    call = (ImageView) findViewById(R.id.call);
    chat = (ImageView) findViewById(R.id.chat);
    file = (ImageView) findViewById(R.id.file);
    vid = (ImageView) findViewById(R.id.vid);
    wifitext = (TextView) findViewById(R.id.wifitext);
    imagesplash = (LinearLayout) findViewById(R.id.imgsplash);
    menu = (LinearLayout) findViewById(R.id.menu);

    initialApp();

    btnCreat = findViewById(R.id.btnCreat);
    btnCreat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent = new Intent(Intent.ACTION_MAIN, null);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.TetherSettings");
            intent.setComponent(cn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

        }

    });

    btnConnect = findViewById(R.id.btnConnect);
    btnConnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
        }
    });

}

public void openConnectedActivity() {
    Intent intent = new Intent(this, TheActivity.class);
    startActivity(intent);
    finish();
}

@Override
protected void onResume() {
    super.onResume();
    Toast.makeText(this, "I just came back", Toast.LENGTH_SHORT).show();

}

private void initialApp(){

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    wifiCheck = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (wifiCheck.isConnected()) {
        runIfConnected();
    } else {
        runIfnotConnected();
    }
}

private void runIfConnected(){
    // if it is connected it will do this
    imagesplash.animate().translationY(-350).setDuration(800).setStartDelay(8000);
    bgapp.animate().translationY(-490).setDuration(800).setStartDelay(8000);
    call.animate().alpha(0).setDuration(800).setStartDelay(8000);
    chat.animate().alpha(0).setDuration(800).setStartDelay(8000);
    file.animate().alpha(0).setDuration(800).setStartDelay(8000);
    vid.animate().alpha(0).setDuration(800).setStartDelay(8000);
    wifitext.animate().alpha(0).setDuration(800).setStartDelay(8000);

    menu.startAnimation(frombottom);

    // putting timer to start the Activity and kill the splash Screen

    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            openConnectedActivity();
        }
    }, 2000);
}

private void runIfnotConnected(){
    // if id is not connected is will do this

    imagesplash.animate().translationY(-350).setDuration(800).setStartDelay(8000);
    bgapp.animate().translationY(-490).setDuration(800).setStartDelay(8000);
    call.animate().alpha(0).setDuration(800).setStartDelay(8000);
    chat.animate().alpha(0).setDuration(800).setStartDelay(8000);
    file.animate().alpha(0).setDuration(800).setStartDelay(8000);
    vid.animate().alpha(0).setDuration(800).setStartDelay(8000);
    wifitext.animate().alpha(0).setDuration(800).setStartDelay(8000);

    menu.startAnimation(frombottom);

}

}


来源: stackexchange

问:
Dynamically growing a python array when assigning to it
I want to populate an array in python so that I can use id numbers to index into the array. Not all indexes will exist in the array and items will not necessarily be added to the array in order. The largest possible index is not known (or at least I'd prefer not to hard code it). Is there a way to dynamically grow the array when assigning?
I.e I want something like

```<code>arr = []
for x in xs
    arr[x.index] = x
</code>```

but this gives "IndexError: list assignment index out of range". I tried using list.insert() but that does not work if the items are not inserted in order, as it changes the index of items already in the array.

Is there a good way to do this in python, or do I have to settle for initializing the array "big enough"?

答:
```<code>x = []
ch=int(input("How many values you want to add in an array"))
for i in range(ch):
    z=int(input("Enter value for array"))
    x.append(z) #now u r pushing value of Z entered by you at run time
print(x)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to populate an array in python so that I can use id numbers to index into the array. Not all indexes will exist in the array and items will not necessarily be added to the array in order. The largest possible index is not known (or at least I'd prefer not to hard code it). Is there a way to dynamically grow the array when assigning?
I.e I want something like

arr = []
for x in xs
    arr[x.index] = x

but this gives "IndexError: list assignment index out of range". I tried using list.insert() but that does not work if the items are not inserted in order, as it changes the index of items already in the array.

Is there a good way to do this in python, or do I have to settle for initializing the array "big enough"?

ContentLicense: CC BY-SA 4.0


问:
jquery select table columns
I am working on selecting a specific table's cells.

Some cells have a class of "testOff", and I'm attempting to change the table row to a different color, if the class exists.

here's what I have so far:

```<code>$("table#customersTable td.testOff").each(function(){

    $(this).closest("tr").css("background-color","#F6CCDA");

});
</code>```

I must be missing something, since it's not showing the background color for any of the cells.
Does anyone see an error with how I'm selecting?

答:
```<code>$("td.testOff").parent().children().css("background-color","#F6CCDA");
</code>```

as per my earlier question, just in case it's the td cells themselves you need to target to override a previous setting

siblings() as I also mentioned in my comments, would only select the cells on either side of the .testOff - this finds all the children of it's parent tr

Title: jquery select table columns

Body:
I am working on selecting a specific table's cells.

Some cells have a class of "testOff", and I'm attempting to change the table row to a different color, if the class exists.

here's what I have so far:

$("table#customersTable td.testOff").each(function(){

    $(this).closest("tr").css("background-color","#F6CCDA");

});

I must be missing something, since it's not showing the background color for any of the cells.
Does anyone see an error with how I'm selecting?

Body:
$("td.testOff").parent().children().css("background-color","#F6CCDA");

as per my earlier question, just in case it's the td cells themselves you need to target to override a previous setting

siblings() as I also mentioned in my comments, would only select the cells on either side of the .testOff - this finds all the children of it's parent tr


问:
How to handle mouse scroll and key press events on Cytoscape.js canvas with tpology diagram
I have some problems with handling events like scrolling using the mouse wheel or key press. I' ve tried something like this but it won't work:

```<code>this.cy.on('wheel', event => {
        //somecodehere
    });
</code>```

I didn't find wanted events on Cytoscape.js documentation page: http://js.cytoscape.org/#events. But I thought a thing like this should work fine - unfortunately I was wrong. I try to figure out how to handle this event on my canvas.

What do I want to do with this? I want to make tooltip disappear when the user wants to scroll the page. I've already disabled zoom on scrolling - I want to enable zooming only while "CTRL" key is pressed and in this case, I also didn't find wanted event to handle this. Any solutions? Thanks.

答:
Use DOM API.</p>

```<code>document.getElementById("cy").addEventListener("wheel", function(){
   console.log("Wheeeellll");
});
</code>```

Body:
I have some problems with handling events like scrolling using the mouse wheel or key press. I' ve tried something like this but it won't work:

this.cy.on('wheel', event => {
        //somecodehere
    });

I didn't find wanted events on Cytoscape.js documentation page: http://js.cytoscape.org/#events. But I thought a thing like this should work fine - unfortunately I was wrong. I try to figure out how to handle this event on my canvas.

What do I want to do with this? I want to make tooltip disappear when the user wants to scroll the page. I've already disabled zoom on scrolling - I want to enable zooming only while "CTRL" key is pressed and in this case, I also didn't find wanted event to handle this. Any solutions? Thanks.

Body:
Use DOM API.

document.getElementById("cy").addEventListener("wheel", function(){
   console.log("Wheeeellll");
});


问:
Spring session gemfire client - Thread contention - Blacklisting
We have made a retail solution in which session handling is taken care by Spring session .We use gemfire to maintain the session objects and use the client as spring session data gemfire client module. We had initial hookups and it was eventually up and running. But when the load to the containers in which the application increased ,we are facing serious issues in the way application responds.Response time increases too an extent that no requests are processed.

We analysed the thread dumps and could see many threads related to gemfire client are on blocked or waiting state. The jvm parameters,CPU usage and heap memory all seems to be fine even with the load that causes the issue.

We see the below from thread dump analysis :

Thread Contention
Servlet - dispatcher:render
Blocked on org.apache.geode.cache.client.internal.ConnectionImpl@3afbbf9

From gemfire client logs the below are observed:

4/30/19 12:03:21.559 PM   [m[30m2019-04-30 12:03:21,559 [Cache Client
  Updater Thread on XX.XX.XX.XX(XXXXX:62475):1024 port 40404] INFO
  : Redundant subscription endpoint XXXXX:40404 crashed. Scheduling
  recovery. The first blacklisting log occurs as : 4/30/19 12:03:21.631
  PM    [m[34m2019-04-30 12:03:21,630 [queueTimer-DEFAULT] WARN : Cache
  Client Updater Thread on XX.XX.XX.XX(XXXXX:76221):1024 port 40404
  (XXXXX:40404): Caught following exception while attempting to create a
  server-to-client communication socket and will exit:
  org.apache.geode.cache.client.ServerRefusedConnectionException: :40404 refused connection: java.lang.Exception:
  This client is blacklisted by server

After a blacklisting,that app instance becomes dead in all means.it wont be able to take n process any request.

Any help is much appreciated in terms of this blacklisting.

答:
The blacklist or the newer term of denylist means that client was to slow to respond to events.

You can read more about how to manage and prevent slow receivers in the docs:
https://gemfire.docs.pivotal.io/98/geode/managing/monitor_tune/slow_receivers.html

The main take away from those docs is making sure the clients have enough resources and are not being starved of CPU cycles, network, disk or RAM.

If the clients are running in a virtualized environment take a look at steal time or ready time from vshpere perspective for the VM running the client.  If the client is running in a container also make sure it's not being throttled because it went over quota.

Code for denylist:
https://github.com/apache/geode/search?q=denylist&unscoped_q=denylist


问:
Why is Javascript's Splice function not working?

My question is quick. Here is the problem:

```<code>//Gets string from database in "User1|User2|User3" format
var frArray = res[0].friendRequests.split('|');

//frArray should now equal ['User1', 'User2', etc]

//data.friend is a string for the friend we are removing from requests
//let's assume it's User1

console.log(frArray.indexOf(data.friend)); //This prints 0

console.log(frArray); //This prints User1 which is correct

frArray = frArray.splice(frArray.indexOf(data.friend), 1);

console.log(frArray);
//This prints User1 STILL which is not correct it should've removed it
</code>```

I would appreciate any help, I can't figure it out. I've been stuck on this for a while. Thanks

答:
As per the documentation of Array.splice:

The splice() method changes the contents of an array by removing or
  replacing existing elements and/or adding new elements in place.

And it returns:

An array containing the deleted elements. If only one element is
  removed, an array of one element is returned. If no elements are
  removed, an empty array is returned.

So splice mutates the original array and returns the removed elements.

In your code you have: frArray = frArray.splice(frArray.indexOf(data.friend), 1);

Where you are assigning the result of splice to your frArray instead of just executing the splice and then continue to use your original (now mutated array):

```<code>var frArray = res[0].friendRequests.split('|');

frArray.splice(frArray.indexOf(data.friend), 1); // <-- no assignment

console.log(frArray);
</code>```

Body:
My question is quick. Here is the problem:

//Gets string from database in "User1|User2|User3" format
var frArray = res[0].friendRequests.split('|');

//frArray should now equal ['User1', 'User2', etc]

//data.friend is a string for the friend we are removing from requests
//let's assume it's User1

console.log(frArray.indexOf(data.friend)); //This prints 0

console.log(frArray); //This prints User1 which is correct

frArray = frArray.splice(frArray.indexOf(data.friend), 1);

console.log(frArray);
//This prints User1 STILL which is not correct it should've removed it

I would appreciate any help, I can't figure it out. I've been stuck on this for a while. Thanks

Body:
As per the documentation of Array.splice:

The splice() method changes the contents of an array by removing or
  replacing existing elements and/or adding new elements in place.

And it returns:

An array containing the deleted elements. If only one element is
  removed, an array of one element is returned. If no elements are
  removed, an empty array is returned.

So splice mutates the original array and returns the removed elements.

In your code you have: frArray = frArray.splice(frArray.indexOf(data.friend), 1);

Where you are assigning the result of splice to your frArray instead of just executing the splice and then continue to use your original (now mutated array):

var frArray = res[0].friendRequests.split('|');

frArray.splice(frArray.indexOf(data.friend), 1); // <-- no assignment

console.log(frArray);


问:
Why there 'foreach' loop generates an exception?
I wrote a code for string reversing using Stack and StringBuilder classes. And I have noticed that 'foreach' loop in this code generates java.util.ConcurrentModificationException, but usual 'for' loop instead does not. So why?

```<code>public static String reverse(String str)
{
    Stack<Character> stack = new Stack<>();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++)
        stack.push(str.toCharArray()[i]);
    }

    for (Character c: stack) // generates an exception
    {
        sb.append(stack.pop());
    }

    return sb.toString();
}
</code>```

I expected a reversed string, but ConcurrentModificationException has occured.

答:
You are changing the stack (stack.pop()) while iterating through it. Try using a different loop:

```<code>public static String reverse(String str)
{
    Stack<Character> stack = new Stack<>();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++)
        stack.push(str.toCharArray()[i]);
    }

    while(!stack.isEmpty()){
         sb.append(stack.pop());
    }

    return sb.toString();
}
</code>```

Body:
I wrote a code for string reversing using Stack and StringBuilder classes. And I have noticed that 'foreach' loop in this code generates java.util.ConcurrentModificationException, but usual 'for' loop instead does not. So why?

public static String reverse(String str)
{
    Stack<Character> stack = new Stack<>();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++)
        stack.push(str.toCharArray()[i]);
    }

    for (Character c: stack) // generates an exception
    {
        sb.append(stack.pop());
    }

    return sb.toString();
}

I expected a reversed string, but ConcurrentModificationException has occured.

Body:
You are changing the stack (stack.pop()) while iterating through it. Try using a different loop:

public static String reverse(String str)
{
    Stack<Character> stack = new Stack<>();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++)
        stack.push(str.toCharArray()[i]);
    }

    while(!stack.isEmpty()){
         sb.append(stack.pop());
    }

    return sb.toString();
}


问:
Spring mvc, how to bind a domain object that has a collection as its property
I have a domain object called Order, and it has a collection attribute called serviceOrders where a collection of service --- order m:m association relationships are hold.

```<code>public class Order implements Serializable {

 private Long id = null;
 private BigDecimal amountPaid;
 private BigDecimal accountReceivable;
 private User user;
 private Set serviceOrders = new HashSet();
 private Date closed;
 private Date created = new Date();
 private String status;
</code>```

also there is a method for adding the association called addServiceOrder

```<code>public void addServiceOrder(ServiceOrder serviceOrder) {
  if (serviceOrder == null)
   throw new IllegalArgumentException("Can't add a null serviceOrder.");
  this.getServiceOrders().add(serviceOrder);
 }
</code>```

how should I use commandName to set this collection with "path", I think it would only call its get set method of the Command Object. how should I add serviceOrder to this command Object. I have no idea about this problem. any help would be highly appreciated

答:
Ok bear with me on this one but the solution is simple an annoying at the same time. I ran into this a couple of months ago. I am going to show you my solution using the jstl libraries in my view for handling the collections.

```<code><c:forEach items="${Questions}" var="quest" varStatus="itemsIndex">
        <fieldset>
          <legend>${quest.section}</legend>
          <form:form id="group${itemsIndex.index}" modelAttribute="ChoiceList" action="" method="POST" onsubmit="javascript:ajaxSave($(this).serialize()); return false;">
            <a id="Group${quest.id}"></a>
            <c:forEach items="${quest.qisQuestionsCollection}" var="quest2" varStatus="itemsRow">
              <div style="font-weight: bold; margin: 10px 0px">${quest2.shortText}</div>
              ( ${quest2.qisQuestionTypes.description} )<br/>
          ( ${quest2.helpText} )<br/>
              <a id="Question${quest2.id}"></a>
              <c:choose>
                <c:when test="${quest2.qisQuestionTypes.questionType == 'CHOOSEANY'}">
                  <c:forEach items="${quest2.qisChoicesCollection}" var="quest3" varStatus="indexStatus">
                    <c:forEach items="${ChoiceFields}" var="CField">
                      <c:set scope="request" value="${quest3}" var="ChoiceData"/>
                      <c:set scope="request" value="${CField}" var="ChoiceProperty"/>
                      <%
                                answerMap = (HashMap<QisChoice, Answer>) request.getAttribute("AnswerList");
                                choice = (QisChoice) request.getAttribute("ChoiceData");
                                if (answerMap.containsKey(choice.getChoiceID())) {
                                  Answer theAnswer = (Answer) answerMap.get(choice.getChoiceID());
                                  if (theAnswer != null) {
                                    if (theAnswer.getChoiceValue() != null) {
                                      request.setAttribute("itemValue", theAnswer.getChoiceValue());
                                      request.setAttribute("itemSelected", true);
                                    } else {
                                      request.setAttribute("itemSelected", false);
                                      request.setAttribute("itemValue", getReflectedValue(
                                              (QisChoice) request.getAttribute("ChoiceData"),
                                              (AccessorStruct) request.getAttribute("ChoiceProperty")));
                                    }
                                  }
                                } else {
                                  request.setAttribute("itemSelected", false);
                                  request.setAttribute("itemValue", getReflectedValue(
                                          (QisChoice) request.getAttribute("ChoiceData"),
                                          (AccessorStruct) request.getAttribute("ChoiceProperty")));
                                }
                                request.setAttribute("itemValue2", getReflectedValue(
                                        (QisChoice) request.getAttribute("ChoiceData"),
                                        (AccessorStruct) request.getAttribute("ChoiceProperty")));
                      %>
                      <c:choose>
                        <c:when test="${CField.visible == 'HIDDEN'}">
                          <form:hidden value="${itemValue2}" path="question[${itemsRow.index}].choice[${indexStatus.index}].${CField.beanName}" />
                        </c:when>
                        <c:otherwise>
                          <c:choose>
                            <c:when test="${itemSelected}">
                              <form:checkbox value="${itemValue}" label="${quest3.description}" path="question[${itemsRow.index}].choice[${indexStatus.index}].${CField.beanName}" checked="true" /><br/>
                            </c:when>
                            <c:otherwise>
                              <form:checkbox value="${itemValue}" label="${quest3.description}" path="question[${itemsRow.index}].choice[${indexStatus.index}].${CField.beanName}" /><br/>
                            </c:otherwise>
                          </c:choose>

                        </c:otherwise>
                      </c:choose>
                    </c:forEach>
                  </c:forEach>
                </c:when>

            <input type="submit" value="Save Section"
                   class="button-main" />
          </fieldset>
        </form:form>
      </c:forEach>`
</code>```

The Key bit is in this line

```<code><form:checkbox value="${itemValue}" label="${quest3.description}" path="question[${itemsRow.index}].choice[${indexStatus.index}].${CField.beanName}" checked="true" /><br/>
</code>```

To link up the command object with its collection for the postback you have to show the indice of the element as part of the spring path. In my case I have two levels of collections to track

```<code><c:forEach items="${quest.qisQuestionsCollection}" var="quest2" varStatus="itemsRow">
</code>```

varStatus gives you access to a bean object with the index property you can use to your advantage.

In your case you can do just use the index property of the foreach jstl function in the jsp to generate the indice like I did and append it to the array index notation of your command object. The command object must of course follow the same flow as the path collection names. This works for an infinite number of levels but gets more annoying as we go.

This is a large live example so if you need something smaller show me your markup and I will walk you throgh it.

ContentLicense: CC BY-SA 2.5

Body:
I have a domain object called Order, and it has a collection attribute called serviceOrders where a collection of service --- order m:m association relationships are hold.

public class Order implements Serializable {

 private Long id = null;
 private BigDecimal amountPaid;
 private BigDecimal accountReceivable;
 private User user;
 private Set serviceOrders = new HashSet();
 private Date closed;
 private Date created = new Date();
 private String status;

also there is a method for adding the association called addServiceOrder

public void addServiceOrder(ServiceOrder serviceOrder) {
  if (serviceOrder == null)
   throw new IllegalArgumentException("Can't add a null serviceOrder.");
  this.getServiceOrders().add(serviceOrder);
 }

how should I use commandName to set this collection with "path", I think it would only call its get set method of the Command Object. how should I add serviceOrder to this command Object. I have no idea about this problem. any help would be highly appreciated

Body:
Ok bear with me on this one but the solution is simple an annoying at the same time. I ran into this a couple of months ago. I am going to show you my solution using the jstl libraries in my view for handling the collections.

<c:forEach items="${Questions}" var="quest" varStatus="itemsIndex">
        <fieldset>
          <legend>${quest.section}</legend>
          <form:form id="group${itemsIndex.index}" modelAttribute="ChoiceList" action="" method="POST" onsubmit="javascript:ajaxSave($(this).serialize()); return false;">
            <a id="Group${quest.id}"></a>
            <c:forEach items="${quest.qisQuestionsCollection}" var="quest2" varStatus="itemsRow">
              <div style="font-weight: bold; margin: 10px 0px">${quest2.shortText}</div>
              ( ${quest2.qisQuestionTypes.description} )<br/>
          ( ${quest2.helpText} )<br/>
              <a id="Question${quest2.id}"></a>
              <c:choose>
                <c:when test="${quest2.qisQuestionTypes.questionType == 'CHOOSEANY'}">
                  <c:forEach items="${quest2.qisChoicesCollection}" var="quest3" varStatus="indexStatus">
                    <c:forEach items="${ChoiceFields}" var="CField">
                      <c:set scope="request" value="${quest3}" var="ChoiceData"/>
                      <c:set scope="request" value="${CField}" var="ChoiceProperty"/>
                      <%
                                answerMap = (HashMap<QisChoice, Answer>) request.getAttribute("AnswerList");
                                choice = (QisChoice) request.getAttribute("ChoiceData");
                                if (answerMap.containsKey(choice.getChoiceID())) {
                                  Answer theAnswer = (Answer) answerMap.get(choice.getChoiceID());
                                  if (theAnswer != null) {
                                    if (theAnswer.getChoiceValue() != null) {
                                      request.setAttribute("itemValue", theAnswer.getChoiceValue());
                                      request.setAttribute("itemSelected", true);
                                    } else {
                                      request.setAttribute("itemSelected", false);
                                      request.setAttribute("itemValue", getReflectedValue(
                                              (QisChoice) request.getAttribute("ChoiceData"),
                                              (AccessorStruct) request.getAttribute("ChoiceProperty")));
                                    }
                                  }
                                } else {
                                  request.setAttribute("itemSelected", false);
                                  request.setAttribute("itemValue", getReflectedValue(
                                          (QisChoice) request.getAttribute("ChoiceData"),
                                          (AccessorStruct) request.getAttribute("ChoiceProperty")));
                                }
                                request.setAttribute("itemValue2", getReflectedValue(
                                        (QisChoice) request.getAttribute("ChoiceData"),
                                        (AccessorStruct) request.getAttribute("ChoiceProperty")));
                      %>
                      <c:choose>
                        <c:when test="${CField.visible == 'HIDDEN'}">
                          <form:hidden value="${itemValue2}" path="question[${itemsRow.index}].choice[${indexStatus.index}].${CField.beanName}" />
                        </c:when>
                        <c:otherwise>
                          <c:choose>
                            <c:when test="${itemSelected}">
                              <form:checkbox value="${itemValue}" label="${quest3.description}" path="question[${itemsRow.index}].choice[${indexStatus.index}].${CField.beanName}" checked="true" /><br/>
                            </c:when>
                            <c:otherwise>
                              <form:checkbox value="${itemValue}" label="${quest3.description}" path="question[${itemsRow.index}].choice[${indexStatus.index}].${CField.beanName}" /><br/>
                            </c:otherwise>
                          </c:choose>

                        </c:otherwise>
                      </c:choose>
                    </c:forEach>
                  </c:forEach>
                </c:when>

            <input type="submit" value="Save Section"
                   class="button-main" />
          </fieldset>
        </form:form>
      </c:forEach>`

The Key bit is in this line

<form:checkbox value="${itemValue}" label="${quest3.description}" path="question[${itemsRow.index}].choice[${indexStatus.index}].${CField.beanName}" checked="true" /><br/>

To link up the command object with its collection for the postback you have to show the indice of the element as part of the spring path. In my case I have two levels of collections to track

<c:forEach items="${quest.qisQuestionsCollection}" var="quest2" varStatus="itemsRow">

varStatus gives you access to a bean object with the index property you can use to your advantage.

In your case you can do just use the index property of the foreach jstl function in the jsp to generate the indice like I did and append it to the array index notation of your command object. The command object must of course follow the same flow as the path collection names. This works for an infinite number of levels but gets more annoying as we go.

This is a large live example so if you need something smaller show me your markup and I will walk you throgh it.


问:
Add Componets to several pages. Error | Ionic 4
I try add to several pages my Header Components (Ionic g component).

My Header componet have a 4 files: html,scss,spec.ts and ts. When I add this component to minimum 2 pages I get this error:

```<code>Error: Type HeaderComponent is part of the declarations of 2 modules: Tab1PageModule and ProductPageModule! Please consider moving HeaderComponent to a higher module that imports Tab1PageModule and ProductPageModule. You can also create a new NgModule that exports and includes HeaderComponent then import that NgModule in Tab1PageModule and ProductPageModule.
</code>```

Its my component look like this:

```<code>import { HeaderComponent } from './../../partials/header/header.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';

import { IonicModule } from '@ionic/angular';

import { ProductPage } from './product.page';

const routes: Routes = [
  {
    path: '',
    component: ProductPage
  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild(routes)
  ],

  entryComponents:[HeaderComponent],
  declarations: [ProductPage,HeaderComponent]
})
export class ProductPageModule {}

</code>```

I try several ways too add this component but I still stay on the same point. When add NgModule to component then I get error about directives (is not recognized). When add ComoneModule (from Ionic Library) then my componets shows on all pages but Is two ways binding is not working properly (isn't refresh);

I will be very greatful for help

EDIT
I try create shared model (Header.components.module.ts), but When I use shared module i get error about:

```<code>core.js:15724 ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'ngIf' since it isn't a known property of 'ion-buttons'.
</code>```

```<code>import { HeaderComponent } from './header.component';
import { NgModule,CUSTOM_ELEMENTS_SCHEMA  } from '@angular/core';
import { IonicModule } from '@ionic/angular';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@NgModule({

    imports: [CommonModule,
        FormsModule,
        IonicModule,RouterModule],
    declarations: [
        HeaderComponent,

   ],
   exports: [
    HeaderComponent
   ],
   schemas: [
    CUSTOM_ELEMENTS_SCHEMA
  ]
})

export class HeaderComponentsModule {}

</code>```

答:
The easiest method to solve this problem is to create a module.ts file for Headercomponent and add that to the imports array.</p>

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { HeaderComponent } from './header.component';

@NgModule({
  imports: [CommonModule, IonicModule],
  declarations: [HeaderComponent ],
  exports: [HeaderComponent ]
})
export class HeaderComponentModule{}
</code>```

Body:
I try add to several pages my Header Components (Ionic g component).

My Header componet have a 4 files: html,scss,spec.ts and ts. When I add this component to minimum 2 pages I get this error:

Error: Type HeaderComponent is part of the declarations of 2 modules: Tab1PageModule and ProductPageModule! Please consider moving HeaderComponent to a higher module that imports Tab1PageModule and ProductPageModule. You can also create a new NgModule that exports and includes HeaderComponent then import that NgModule in Tab1PageModule and ProductPageModule.

Its my component look like this:

import { HeaderComponent } from './../../partials/header/header.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';

import { IonicModule } from '@ionic/angular';

import { ProductPage } from './product.page';

const routes: Routes = [
  {
    path: '',
    component: ProductPage
  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild(routes)
  ],

  entryComponents:[HeaderComponent],
  declarations: [ProductPage,HeaderComponent]
})
export class ProductPageModule {}

I try several ways too add this component but I still stay on the same point. When add NgModule to component then I get error about directives (is not recognized). When add ComoneModule (from Ionic Library) then my componets shows on all pages but Is two ways binding is not working properly (isn't refresh);

I will be very greatful for help

EDIT
I try create shared model (Header.components.module.ts), but When I use shared module i get error about:

core.js:15724 ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'ngIf' since it isn't a known property of 'ion-buttons'.

import { HeaderComponent } from './header.component';
import { NgModule,CUSTOM_ELEMENTS_SCHEMA  } from '@angular/core';
import { IonicModule } from '@ionic/angular';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@NgModule({

    imports: [CommonModule,
        FormsModule,
        IonicModule,RouterModule],
    declarations: [
        HeaderComponent,

   ],
   exports: [
    HeaderComponent
   ],
   schemas: [
    CUSTOM_ELEMENTS_SCHEMA
  ]
})

export class HeaderComponentsModule {}

Body:
The easiest method to solve this problem is to create a module.ts file for Headercomponent and add that to the imports array.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { HeaderComponent } from './header.component';

@NgModule({
  imports: [CommonModule, IonicModule],
  declarations: [HeaderComponent ],
  exports: [HeaderComponent ]
})
export class HeaderComponentModule{}


问:
Silverlight combo popup not displayed correctly when window resizes
If I create a ComboBox from scratch, when the window is resized, the content is correctly displayed above/below, etc.

Why this doesn't happen when you create your own Combo-derived class? What am I missing?

答:
Controls aren't magical. They need to be told that things happen (call a method on them) or look for them to happen (register for an event).

Find your Application.RootVisual and register for a SizeChanged event. Then resize your control. If it is in browser you may need to create a javascript bridge (hopefully not) that tells your SL object when the browser resizes.


问:
Detect current page of UIPageViewController
I want to detect the current page in order to modify a button's title while the last page is showing and re-modify every time the user swipes back from the last to the second to last page.

Now these are my delegate methods and my array of ViewControllers:

```<code>lazy var VCArr: [UIViewController] = {
    let firstVC = self.storyboard!.instantiateViewController(withIdentifier: "FirstTutorialPage")
    let secondVC = self.storyboard!.instantiateViewController(withIdentifier: "SecondTutorialPage")
    let thirdVC = self.storyboard!.instantiateViewController(withIdentifier: "ThirdTutorialPage")
    let fourthVC = self.storyboard!.instantiateViewController(withIdentifier: "FourthTutorialPage")
    return [firstVC, secondVC, thirdVC, fourthVC]
}()
</code>```

delegate methods

```<code>    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {

    guard let viewControllerIndex = self.VCArr.index(of: viewController) else {
        return nil
    }

    let previousIndex = viewControllerIndex - 1

    guard previousIndex >= 0 else {
        return nil
    }

    guard self.VCArr.count > previousIndex else {
        return nil
    }

    return self.VCArr[previousIndex]
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    guard let viewControllerIndex = self.VCArr.index(of: viewController) else {
        return nil
    }

    let nextIndex = viewControllerIndex + 1

    guard nextIndex < self.VCArr.count else {
        return nil
    }

    guard self.VCArr.count > nextIndex else {
        return nil
    }

    return self.VCArr[nextIndex]
}
</code>```

Can someone help me detect with accuracy the last page shown? I tried some methods but everyone of them showed me the wrong index. Those methods detected the last index while showing the second to last page.

Thanks to all.

答:
Set up the didFinishAnimating pageViewController DataSource function like so.  Store a property of your data source.  In this case I named it orderedViewControllers.  Then as you swipe, the current index will be printed to the console.

```<code>func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    let pageContentViewController = pageViewController.viewControllers![0]
    let index = orderedViewControllers.index(of: pageContentViewController)!
    print(index)
}
</code>```

Body:
I want to detect the current page in order to modify a button's title while the last page is showing and re-modify every time the user swipes back from the last to the second to last page.

Now these are my delegate methods and my array of ViewControllers:

lazy var VCArr: [UIViewController] = {
    let firstVC = self.storyboard!.instantiateViewController(withIdentifier: "FirstTutorialPage")
    let secondVC = self.storyboard!.instantiateViewController(withIdentifier: "SecondTutorialPage")
    let thirdVC = self.storyboard!.instantiateViewController(withIdentifier: "ThirdTutorialPage")
    let fourthVC = self.storyboard!.instantiateViewController(withIdentifier: "FourthTutorialPage")
    return [firstVC, secondVC, thirdVC, fourthVC]
}()

delegate methods

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {

    guard let viewControllerIndex = self.VCArr.index(of: viewController) else {
        return nil
    }

    let previousIndex = viewControllerIndex - 1

    guard previousIndex >= 0 else {
        return nil
    }

    guard self.VCArr.count > previousIndex else {
        return nil
    }

    return self.VCArr[previousIndex]
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    guard let viewControllerIndex = self.VCArr.index(of: viewController) else {
        return nil
    }

    let nextIndex = viewControllerIndex + 1

    guard nextIndex < self.VCArr.count else {
        return nil
    }

    guard self.VCArr.count > nextIndex else {
        return nil
    }

    return self.VCArr[nextIndex]
}

Can someone help me detect with accuracy the last page shown? I tried some methods but everyone of them showed me the wrong index. Those methods detected the last index while showing the second to last page.

Thanks to all.

Body:
Set up the didFinishAnimating pageViewController DataSource function like so.  Store a property of your data source.  In this case I named it orderedViewControllers.  Then as you swipe, the current index will be printed to the console.

func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    let pageContentViewController = pageViewController.viewControllers![0]
    let index = orderedViewControllers.index(of: pageContentViewController)!
    print(index)
}


问:
How to generate an uuid in google sheet?
How to generate an uuid in google sheet (for exemple ccb8a660-91c9-a556-58e0-4fa7-229516872004).

Either with a macro? or a formula?

答:
the created uuid is changed with the time.

I think this problem could not be solved without using the Apps Script.

For example:

```<code>var sheet = SpreadsheetApp.getActiveSheet();
var values = sheet.getRange('A1:A10').getValues();

for (var i = 0; i < values.length; i++) {
  // When a cell is empty, set a uuid to the cell.
  if (!values[i][0]) {
    sheet.getRange('A' + (1 + i)).setValue(Utilities.getUuid());
  }
}
</code>```

Body:
the created uuid is changed with the time.

I think this problem could not be solved without using the Apps Script.

For example:

var sheet = SpreadsheetApp.getActiveSheet();
var values = sheet.getRange('A1:A10').getValues();

for (var i = 0; i < values.length; i++) {
  // When a cell is empty, set a uuid to the cell.
  if (!values[i][0]) {
    sheet.getRange('A' + (1 + i)).setValue(Utilities.getUuid());
  }
}


问:
How to convert string containing AM/PM to datetime in python using %p
I need to convert a string formatted as '2000-01-01 12:00:00 AM' but it doesn't matter if it is AM or PM the result is the same (see example below).

```<code>from datetime import datetime
frmt = '%Y-%d-%m %H:%M:%S %p'
datetime.strptime('2000-01-01 12:00:00 AM', frmt).isoformat()
datetime.strptime('2000-01-01 12:00:00 PM', frmt).isoformat()
</code>```

Output is:

```<code>'2000-01-01T12:00:00'
'2000-01-01T12:00:00'
</code>```

I thought it could be a problem related to no definition if 12AM is midnight or noon but even when executing the same code for other different hours the result is still the same:

```<code>datetime.strptime('2000-01-01 06:00:00 AM', frmt).isoformat()
datetime.strptime('2000-01-01 06:00:00 PM', frmt).isoformat()
</code>```

Output is:

```<code>'2000-01-01T06:00:00'
'2000-01-01T06:00:00'
</code>```

The strftime.org website says the format I am using should work, but it is not. What should I do?

答:
This is why I use arrow.  Just makes all of this easier.  </p>

```<code>import arrow
frmt = 'YYYY-MM-DD HH:mm:ss A'
print(arrow.get('2000-01-01 12:00:00 AM', frmt))
print(arrow.get('2000-01-01 12:00:00 PM', frmt))
#datetime
print(arrow.get('2000-01-01 12:00:00 AM', frmt).datetime)
print(arrow.get('2000-01-01 12:00:00 PM', frmt).datetime)
#isoformat
print(arrow.get('2000-01-01 12:00:00 AM', frmt).isoformat())
print(arrow.get('2000-01-01 12:00:00 PM', frmt).isoformat())
</code>```

Body:
I need to convert a string formatted as '2000-01-01 12:00:00 AM' but it doesn't matter if it is AM or PM the result is the same (see example below).

from datetime import datetime
frmt = '%Y-%d-%m %H:%M:%S %p'
datetime.strptime('2000-01-01 12:00:00 AM', frmt).isoformat()
datetime.strptime('2000-01-01 12:00:00 PM', frmt).isoformat()

Output is:

'2000-01-01T12:00:00'
'2000-01-01T12:00:00'

I thought it could be a problem related to no definition if 12AM is midnight or noon but even when executing the same code for other different hours the result is still the same:

datetime.strptime('2000-01-01 06:00:00 AM', frmt).isoformat()
datetime.strptime('2000-01-01 06:00:00 PM', frmt).isoformat()

Output is:

'2000-01-01T06:00:00'
'2000-01-01T06:00:00'

The strftime.org website says the format I am using should work, but it is not. What should I do?

Body:
This is why I use arrow.  Just makes all of this easier.

import arrow
frmt = 'YYYY-MM-DD HH:mm:ss A'
print(arrow.get('2000-01-01 12:00:00 AM', frmt))
print(arrow.get('2000-01-01 12:00:00 PM', frmt))
#datetime
print(arrow.get('2000-01-01 12:00:00 AM', frmt).datetime)
print(arrow.get('2000-01-01 12:00:00 PM', frmt).datetime)
#isoformat
print(arrow.get('2000-01-01 12:00:00 AM', frmt).isoformat())
print(arrow.get('2000-01-01 12:00:00 PM', frmt).isoformat())


答:
ConcurrentModificationExceptions occur when you try and edit something which you are iterating over. By calling stack.pop() you are removing an entity from the entity over which you are currently looping.

I'd recommend instead that you iterate through the stack until it's empty:

```<code>while (!stack.isEmpty()) {
    sb.append(stack.pop());
}
</code>```

Title: Why there 'foreach' loop generates an exception?

Body:
ConcurrentModificationExceptions occur when you try and edit something which you are iterating over. By calling stack.pop() you are removing an entity from the entity over which you are currently looping.

I'd recommend instead that you iterate through the stack until it's empty:

while (!stack.isEmpty()) {
    sb.append(stack.pop());
}


问:
Variable with multiple roles
I am having trouble getting the right variable based on a Role.

Perhaps I have the answer but I am not sure and could not find it in the documentation and here in the other questions.

TL;DR:

Multiple Roles on a variable use an OR, not an AND?

Intro

In Infrastructure I have multiple roles assigned to a machine:

WebServer

ApplicationServer

ApplA

ApplB

A variable has two values, each value has the role WebServer and ApplA or ApplB.

In Process the same combination of the Roles WebServer and ApplA is used (or WebServer and ApplB).

Problem

The value of the variable of ApplB is used in the step with ApplA.

It seems that this is because it uses an OR between the Roles and not a AND.

Correct?

答:
That's right. If multiple roles are applied in the scope, it means that the variable will have that value for both of those roles individually, not together. You can combine scopes of different types (like DEV and ApplA) but not of the same time.

This section from the docs has a little more information on scope precedence and what happens if there are conflicting values.

In your deployment process, the "Deploy site" steps will run for all targets that have WebServer or ApplA. That might not be what you want.

In this case, you can consider dropping the webserver role for the purposes of scoping the variables and the deployment steps or combine it with your other tags to make them a little more specific. Instead of WebServer, ApplA, and ApplB, you can replace those with ApplA-Web and ApplB-Web for use in your steps and variables.

I hope that helps!

Title: Variable with multiple roles


答:
The for-each loop uses an iterator in the background which checks if there is a next element in "stack" and then sets the value of "Character c" to that next element. But you are not allowed to change the size of "stack" during the foreach. By calling stack.pop() you are violating that rule.
Instead of the for(Characater c : stack) use:</p>

```<code>while(!stack.empty()){
   sb.append(stack.pop());
}
</code>```

Body:
The for-each loop uses an iterator in the background which checks if there is a next element in "stack" and then sets the value of "Character c" to that next element. But you are not allowed to change the size of "stack" during the foreach. By calling stack.pop() you are violating that rule.
Instead of the for(Characater c : stack) use:

while(!stack.empty()){
   sb.append(stack.pop());
}


问:
How can I know a certain file is a video file?
I am trying to figure out if a certain user-uploaded file is a video file.

I first tried ffprobe,

```<code># a png file

Input #0, png_pipe, from '<file>':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: png, rgba(pc), 920x2094 [SAR 4724:4724 DAR 460:1047], 25 tbr, 25 tbn, 25 tbc

# a text file

Input #0, tty, from '<file>':
  Duration: 00:00:00.24, bitrate: 40 kb/s
    Stream #0:0: Video: ansi, pal8, 640x400, 25 fps, 25 tbr, 25 tbn, 25 tbc

# a video file

Input #0, matroska,webm, from '<file>':
  Metadata:
    encoder         : libebml v1.3.5 + libmatroska v1.4.8
    creation_time   : 2017-12-12T20:18:42.000000Z
  <redacted>
</code>```

but it's too hard to figure out what's what. Even image files and text files count as a video.

Should I compare the output matroska,webm, with every codec ffmpeg supports or is there a better way to do this?

答:
Using ffprobe:

```<code>ffprobe -v error -select_streams v:0 -show_entries stream=codec_type -of csv=p=0 input.mkv
</code>```

Outputs either video or no output at all.

The problem is that ffprobe considers images to be video, so you can additionally/alternatively use codec_name to help determine the type:

```<code>ffprobe -v error -select_streams v:0 -show_entries stream=codec_name,codec_type -of default=nw=1 input.png
</code>```

Outputs:

```<code>codec_name=png
codec_type=video
</code>```

Body:
I am trying to figure out if a certain user-uploaded file is a video file.

I first tried ffprobe,

# a png file

Input #0, png_pipe, from '<file>':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: png, rgba(pc), 920x2094 [SAR 4724:4724 DAR 460:1047], 25 tbr, 25 tbn, 25 tbc

# a text file

Input #0, tty, from '<file>':
  Duration: 00:00:00.24, bitrate: 40 kb/s
    Stream #0:0: Video: ansi, pal8, 640x400, 25 fps, 25 tbr, 25 tbn, 25 tbc

# a video file

Input #0, matroska,webm, from '<file>':
  Metadata:
    encoder         : libebml v1.3.5 + libmatroska v1.4.8
    creation_time   : 2017-12-12T20:18:42.000000Z
  <redacted>

but it's too hard to figure out what's what. Even image files and text files count as a video.

Should I compare the output matroska,webm, with every codec ffmpeg supports or is there a better way to do this?

Body:
Using ffprobe:

ffprobe -v error -select_streams v:0 -show_entries stream=codec_type -of csv=p=0 input.mkv

Outputs either video or no output at all.

The problem is that ffprobe considers images to be video, so you can additionally/alternatively use codec_name to help determine the type:

ffprobe -v error -select_streams v:0 -show_entries stream=codec_name,codec_type -of default=nw=1 input.png

Outputs:

codec_name=png
codec_type=video


问:
nifi: how to merge multiple columns in csv file?
nifi version: 1.5

input file:

```<code>col1,col2,col3,col4,col5,col6
a,hr,nat,REF,6,2481
a,hr,nat,TDB,6,1845
b,IT,raj,NAV,6,2678
</code>```

i want to merge the last three columns with : delimiter and separator by / based on col1.

expected output:

```<code>col1,col2,col3,col4
a,hr,nat,REF:6:2481/TDB:6:1845
b,IT,raj,NAV:6:2678
</code>```

i am not able to find the solution because lot of response were based merging two files.
is there a better way to do it?

tia.

答:
I think you'll want a PartitionRecord processor first, with partition field col1, this will split the flow file into multiple flow files where each distinct value of col1 will be in its own flow file. If the first 3 columns are to be used for partitioning, you can add all three columns as user-defined properties for partitioning.

Then whether you use a scripted solution or perhaps QueryRecord (if Calcite supports "group by" concatenation), the memory usage should be less as you are only dealing with a flow file at a time whose rows are already associated by the specified group.

Body:
nifi version: 1.5

input file:

col1,col2,col3,col4,col5,col6
a,hr,nat,REF,6,2481
a,hr,nat,TDB,6,1845
b,IT,raj,NAV,6,2678

i want to merge the last three columns with : delimiter and separator by / based on col1.

expected output:

col1,col2,col3,col4
a,hr,nat,REF:6:2481/TDB:6:1845
b,IT,raj,NAV:6:2678

i am not able to find the solution because lot of response were based merging two files.
is there a better way to do it?

tia.


问:
TFS 2017 build executing powershell failing due to term not recognized error on line 1
I'm pretty new to TFS and I'm still learning how to use it (so hopefully this isn't just a stupid oversight on my end). I'm working an internship this summer at a seasonal developer position, and essentially my end goal is to automate load testing for the company's website. I'm using TFS to achieve this goal; the build I currently have has two tasks only right now: one to start the controller and the testing environment, and one to stop them. My problem is that the build keeps failing before it really even starts, due to a "term not recognized" error on line 1, specifically caused by what appears to be the default working folder not being recognized.

Here are the relevant log files:

```<code>2019-05-30T20:00:02.0942883Z Executing the following powershell script. (workingFolder = D:\RM_agent\_work\11\s)
2019-05-30T20:00:02.0942883Z D:\RM_agent\_work\11\s
2019-05-30T20:00:02.4999117Z ##[error]. : The term 'D:\RM_agent\_work\11\s' is not recognized as the name of a
2019-05-30T20:00:02.4999117Z ##[error]cmdlet, function, script file, or operable program. Check the spelling of the
2019-05-30T20:00:02.4999117Z ##[error]name, or if a path was included, verify that the path is correct and try again.
2019-05-30T20:00:02.4999117Z ##[error]At line:1 char:3
2019-05-30T20:00:02.4999117Z ##[error]+ . 'D:\RM_agent\_work\11\s'
2019-05-30T20:00:02.4999117Z ##[error]+   ~~~~~~~~~~~~~~~~~~~~~~~~
2019-05-30T20:00:02.4999117Z ##[error]    + CategoryInfo          : ObjectNotFound: (D:\RM_agent\_work\11\s:String)
2019-05-30T20:00:02.4999117Z ##[error]   [], CommandNotFoundException
2019-05-30T20:00:02.4999117Z ##[error]    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

I know that the working folder defaults to $(Build.SourcesDirectory), so I'm assuming that D:\RM_agent\_work\11\s is what $(Build.SourcesDirectory) evaluates to. RM_agent is obviously an agent, so /_work/11/s should be the local path where it stores the source code. Why is it unrecognized then?

I tried manually setting the working folder for the scripts through tfs to the folder where the build is stored, but the build still failed and the logs still showed that workingFolder = D:\RM_agent\_work\11\s.

Additionally, the line of code that the build is failing on, Executing the following powershell script. (workingFolder = D:\RM_agent\_work\11\s), is nowhere in the script I am trying to execute, which confuses me. Where is this script coming from?

(I can remove this if it doesn't fit the guidelines/is off topic, but if anyone could point me towards any resources about tfs and/or load testing it would be massively helpful as well)

EDIT: Here is the powershell script for the first task

```<code>########################################
# start environment
########################################

# import modules
Import-Module '\\neenah-san1\TSbuild\Deployment\Tools\PowerShell\Azure\JJK.TS.Azure.psm1' -Force -Prefix 'TS'

# provide azure credentials
$credential = Get-Credential

# login to azure subscription
Login-AzureRmAccount -Credential $credential

# start the controller
Get-AzureRmVM -ResourceGroupName 'TS-LoadTest-TST' | Where-Object {$_.Name -match 'vstc'} | Start-TSAzureVM -Credential $credential

# wait for controller to fully start
Start-Sleep -Seconds 120

# start the agents
Get-AzureRmVM -ResourceGroupName 'TS-LoadTest-TST' | Where-Object {$_.Name -match 'vsta'} | Start-TSAzureVM -Credential $credential

# check status of all servers
Get-AzureRmVM -ResourceGroupName 'TS-LoadTest-TST' -Status | Sort-Object -Property Name | Select-Object -Property Name, PowerState | Format-Table -AutoSize
</code>```

Solution structure:

EDIT 2: [RESOLVED] It's all fixed now, thank you! I went into the repository and mapped the folder my scripts were in directly to $(build.sourcesDirectory). Consequently I was able to change the file path to $(build.sourcesDirectory)\StartControllerAndAgents.ps1 and the build is now able to find the files to run.

答:
You need to specify the path to the script as $(Build.SourcesDirectory)\Path\To\Script. Not the TFVC path which you've configured now $/Project/Path/To/Script.

The exact path depends on the workspace mapping of the build definition.

The same applies to the working directory.

There are a number of variables in Azure Pipelines (the current name for the Build hub in TFS/Azure DevOps) that resolve to different standardized paths on the agent. Almost all tasks take a relative path off of those variables.

Body:
I'm pretty new to TFS and I'm still learning how to use it (so hopefully this isn't just a stupid oversight on my end). I'm working an internship this summer at a seasonal developer position, and essentially my end goal is to automate load testing for the company's website. I'm using TFS to achieve this goal; the build I currently have has two tasks only right now: one to start the controller and the testing environment, and one to stop them. My problem is that the build keeps failing before it really even starts, due to a "term not recognized" error on line 1, specifically caused by what appears to be the default working folder not being recognized.

Here are the relevant log files:

2019-05-30T20:00:02.0942883Z Executing the following powershell script. (workingFolder = D:\RM_agent\_work\11\s)
2019-05-30T20:00:02.0942883Z D:\RM_agent\_work\11\s
2019-05-30T20:00:02.4999117Z ##[error]. : The term 'D:\RM_agent\_work\11\s' is not recognized as the name of a
2019-05-30T20:00:02.4999117Z ##[error]cmdlet, function, script file, or operable program. Check the spelling of the
2019-05-30T20:00:02.4999117Z ##[error]name, or if a path was included, verify that the path is correct and try again.
2019-05-30T20:00:02.4999117Z ##[error]At line:1 char:3
2019-05-30T20:00:02.4999117Z ##[error]+ . 'D:\RM_agent\_work\11\s'
2019-05-30T20:00:02.4999117Z ##[error]+   ~~~~~~~~~~~~~~~~~~~~~~~~
2019-05-30T20:00:02.4999117Z ##[error]    + CategoryInfo          : ObjectNotFound: (D:\RM_agent\_work\11\s:String)
2019-05-30T20:00:02.4999117Z ##[error]   [], CommandNotFoundException
2019-05-30T20:00:02.4999117Z ##[error]    + FullyQualifiedErrorId : CommandNotFoundException

I know that the working folder defaults to $(Build.SourcesDirectory), so I'm assuming that D:\RM_agent\_work\11\s is what $(Build.SourcesDirectory) evaluates to. RM_agent is obviously an agent, so /_work/11/s should be the local path where it stores the source code. Why is it unrecognized then?

I tried manually setting the working folder for the scripts through tfs to the folder where the build is stored, but the build still failed and the logs still showed that workingFolder = D:\RM_agent\_work\11\s.

Additionally, the line of code that the build is failing on, Executing the following powershell script. (workingFolder = D:\RM_agent\_work\11\s), is nowhere in the script I am trying to execute, which confuses me. Where is this script coming from?

(I can remove this if it doesn't fit the guidelines/is off topic, but if anyone could point me towards any resources about tfs and/or load testing it would be massively helpful as well)

EDIT: Here is the powershell script for the first task

########################################
# start environment
########################################

# import modules
Import-Module '\\neenah-san1\TSbuild\Deployment\Tools\PowerShell\Azure\JJK.TS.Azure.psm1' -Force -Prefix 'TS'

# provide azure credentials
$credential = Get-Credential

# login to azure subscription
Login-AzureRmAccount -Credential $credential

# start the controller
Get-AzureRmVM -ResourceGroupName 'TS-LoadTest-TST' | Where-Object {$_.Name -match 'vstc'} | Start-TSAzureVM -Credential $credential

# wait for controller to fully start
Start-Sleep -Seconds 120

# start the agents
Get-AzureRmVM -ResourceGroupName 'TS-LoadTest-TST' | Where-Object {$_.Name -match 'vsta'} | Start-TSAzureVM -Credential $credential

# check status of all servers
Get-AzureRmVM -ResourceGroupName 'TS-LoadTest-TST' -Status | Sort-Object -Property Name | Select-Object -Property Name, PowerState | Format-Table -AutoSize

Solution structure:

EDIT 2: [RESOLVED] It's all fixed now, thank you! I went into the repository and mapped the folder my scripts were in directly to $(build.sourcesDirectory). Consequently I was able to change the file path to $(build.sourcesDirectory)\StartControllerAndAgents.ps1 and the build is now able to find the files to run.


问:
Output = 0 when trying to calculate functions in a header and calling them in a main program
I've been learning cpp for two days now (super beginner) and to train it, I'm trying to solve some fluid mechanics problems, since I have an engineering background. In the code I'm trying to get inputs (cin) of some variables and with them, solve all the equations necessary in a header file (to make the code shorter) and then bring the results to the main file.

So far I've only done 1 case, since the others will be similar, so I'm trying to work out the first case to know how should I go for the next ones.

For the code provided, I only showed 1 function, since the other ones look pretty much the same, with the only difference being the equation written in them.

Main File

```<code>#include <iostream>
#include <math.h>
#include "fenomenos.hpp"

//Determining the case type
int case_determination(int casE){

std::cout << "Inform the case number from 1 to 6\n";
std::cin >> casE;

return casE;
}

void resol_cases(){
int casE;
if (casE == 1){

std::cout << "Inform the pipe diameter";
std::cin >> d;
std::cout << "Inform the flow rate";
std::cin >> Q;

calc_area();
calc_vel();
calc_Re();
calc_f();
calc_h1();
calc_h2();

}
}

int main() {

std::cout << "Area = " << A << " m^2\n";
std::cout << "Velocity = " << v << " m/s\n";
std::cout << "Re = " << Re << " \n";
std::cout << "f = " << f << " \n";
std::cout << "h1 = " << h1 << " m\n";
std::cout << "h2 = " << h2 << " m\n";

}
</code>```

Header File

```<code>//Definicao das variaveis
double d;
double A;
double Q;
double h1;
double h2;
double v;
double Re;
double ke;
double f;
double rho;
double mi;
double g;
double L;
const double PI  = 3.141592653589793238463;
const double e = 2.71828;

//Area calculation

double calc_area(double A){

A = (PI*pow(d,2))/4;

return A;

}
</code>```

答:
Your main function is where you need to call all your functions to get your values. main is the only part of the code that runs on startup, so any other functions that need running need to be called within main. Right now, your main is just printing out the statements. To run the equations, you need to run resol_cases() in your main. Like this:

```<code>int main() {
    resol_cases();
    std::cout << "Area = " << A << " m^2\n";
    std::cout << "Velocity = " << v << " m/s\n";
    std::cout << "Re = " << Re << " \n";
    std::cout << "f = " << f << " \n";
    std::cout << "h1 = " << h1 << " m\n";
    std::cout << "h2 = " << h2 << " m\n";

}
</code>```

These global variables will likely default to zero at the start and are not changed unless you call the functions that change them from the main.

Another note: Inside resol_cases(), you need to get the case, so use this line for declaration of casE:

```<code>void resol_cases(){

    int casE = case_determination();

    …

}
</code>```

This is how you get casE.
Note that the parameter is removed from the signature because the function does not use a value outside of the function to run. This also applies to your area function.

```<code>int case_determination(){
    int casE; // declare internal variables here
    std::cout << "Inform the case number from 1 to 6\n";
    std::cin >> casE;

    return casE;
}
</code>```

Body:
I've been learning cpp for two days now (super beginner) and to train it, I'm trying to solve some fluid mechanics problems, since I have an engineering background. In the code I'm trying to get inputs (cin) of some variables and with them, solve all the equations necessary in a header file (to make the code shorter) and then bring the results to the main file.

So far I've only done 1 case, since the others will be similar, so I'm trying to work out the first case to know how should I go for the next ones.

For the code provided, I only showed 1 function, since the other ones look pretty much the same, with the only difference being the equation written in them.

Main File

#include <iostream>
#include <math.h>
#include "fenomenos.hpp"

//Determining the case type
int case_determination(int casE){

std::cout << "Inform the case number from 1 to 6\n";
std::cin >> casE;

return casE;
}

void resol_cases(){
int casE;
if (casE == 1){

std::cout << "Inform the pipe diameter";
std::cin >> d;
std::cout << "Inform the flow rate";
std::cin >> Q;

calc_area();
calc_vel();
calc_Re();
calc_f();
calc_h1();
calc_h2();

}
}

int main() {

std::cout << "Area = " << A << " m^2\n";
std::cout << "Velocity = " << v << " m/s\n";
std::cout << "Re = " << Re << " \n";
std::cout << "f = " << f << " \n";
std::cout << "h1 = " << h1 << " m\n";
std::cout << "h2 = " << h2 << " m\n";

}

Header File

//Definicao das variaveis
double d;
double A;
double Q;
double h1;
double h2;
double v;
double Re;
double ke;
double f;
double rho;
double mi;
double g;
double L;
const double PI  = 3.141592653589793238463;
const double e = 2.71828;

//Area calculation

double calc_area(double A){

A = (PI*pow(d,2))/4;

return A;

}

Body:
Your main function is where you need to call all your functions to get your values. main is the only part of the code that runs on startup, so any other functions that need running need to be called within main. Right now, your main is just printing out the statements. To run the equations, you need to run resol_cases() in your main. Like this:

int main() {
    resol_cases();
    std::cout << "Area = " << A << " m^2\n";
    std::cout << "Velocity = " << v << " m/s\n";
    std::cout << "Re = " << Re << " \n";
    std::cout << "f = " << f << " \n";
    std::cout << "h1 = " << h1 << " m\n";
    std::cout << "h2 = " << h2 << " m\n";

}

These global variables will likely default to zero at the start and are not changed unless you call the functions that change them from the main.

Another note: Inside resol_cases(), you need to get the case, so use this line for declaration of casE:

void resol_cases(){

    int casE = case_determination();

    …

}

This is how you get casE.
Note that the parameter is removed from the signature because the function does not use a value outside of the function to run. This also applies to your area function.

int case_determination(){
    int casE; // declare internal variables here
    std::cout << "Inform the case number from 1 to 6\n";
    std::cin >> casE;

    return casE;
}


问:
Selecting person and their multiple letter ids?
Trying to use sql to grab all users from a location "E.g. Boston" and grab all their letter ids. For example it should return something similar to this:

```<code>username  | letterID
Sam Smith | 5278665, 674943, 6549343
Jane Lenna| 8759385, 439533
</code>```

In my Persons Table I have: userID, username, location, etc.

In my Letter Table I have: letterID, userID, title, description, etc.

答:
Try the following;</p>

```<code>SELECT
  p.username,
  string_agg(l.letterID, ', ')
FROM
  Persons p
  Join Letter l on l.userID = p.userID
WHERE
  p.location = "Boston"
GROUP BY p.username
</code>```

Body:
Trying to use sql to grab all users from a location "E.g. Boston" and grab all their letter ids. For example it should return something similar to this:

username  | letterID
Sam Smith | 5278665, 674943, 6549343
Jane Lenna| 8759385, 439533

In my Persons Table I have: userID, username, location, etc.

In my Letter Table I have: letterID, userID, title, description, etc.

Body:
Try the following;

SELECT
  p.username,
  string_agg(l.letterID, ', ')
FROM
  Persons p
  Join Letter l on l.userID = p.userID
WHERE
  p.location = "Boston"
GROUP BY p.username


问:
How to automatically add the ordinal number of an entry based on timstamp to a row when non-contiguous new data is added to it in Google Sheets?
How to make Google sheets automatically add the ordinal number of the current row based on the following criteria 'new entry on this particular row?

How to make it work even when the data is not entered on a row contiguous basis (for example 1st entry on row 1 (say cell B1), 2nd entry on row 2 (in B2), 3rd entry on row 3 (B3), but then 4th entry on row 9 (B9), 5th on row 11 (B11), 6th on row (B7))?

And not adding ordinals to intermediary empty rows (for example when  B5/row5, B6/row6, B8/row8, B10/row10 etc. are blanks, don't add ordinals to A5/row5, A6/row6, A8/row8, A10/row10, etc.)?

Here's the expected result:

The Sheet:
Ordinals to non-contiguous rows based on data entry timestamps

So far I've come up with this pull down formula (to be pre-set in A2 and dragged down to A12):

```<code>=IF(B2<>"",MAX($A$2:$A)+1,"")  [in A2]
=IF(B3<>"",MAX($A$2:$A)+1,"")  [in A3]
=IF(B4<>"",MAX($A$2:$A)+1,"")  [in A4]
=IF(B5<>"",MAX($A$2:$A)+1,"")  [in A5]
=IF(B6<>"",MAX($A$2:$A)+1,"")  [in A6]
=IF(B7<>"",MAX($A$2:$A)+1,"")  [in A7]
=IF(B8<>"",MAX($A$2:$A)+1,"")  [in A8]
=IF(B9<>"",MAX($A$2:$A)+1,"")  [in A9]
=IF(B10<>"",MAX($A$2:$A)+1,"")  [in A10]
=IF(B11<>"",MAX($A$2:$A)+1,"")  [in A11]
=IF(B12<>"",MAX($A$2:$A)+1,"")  [in A12]
</code>```

But the result I get when I enter then data succesively  one by one in B2, B3, B4, B7, B9, and B12, is that it updates all previous cells with the new max value so that the succesion isn't achieved.

Here's a gif that shows the live result:

https://i.imgur.com/1I1Dk8f.gifv

How to lock the previous results so that the ordinal count can proceed to the next entry when it occurs consecutively?

I've consulted those post that are close to what I'm looking for:

How do you replace a formula with its result?

using this script:

```<code>function freezeOutput(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SummarySheet");
  var range = sheet.getRange("A1:A10");
  range.copyTo(range, {contentsOnly:true});
}
</code>```

Stop Excel from updating formula after a criteria is matched

using this formula:

```<code>=IF(NOW() < C1,2*A1,A2)
</code>```

Alternatively this VBA code:

```<code>Function EvaluateIf(expression As String, condition As Boolean) As Variant
    Application.Volatile
    Dim myText As String
    Dim myVal As Variant
    If condition Then
        myVal = Application.Evaluate(expression)
    Else
        myText = Application.Caller.Text
        If IsNumeric(myText) Then
            myVal = Val(myText)
        Else
            myVal = myText
        End If
    End If
    EvaluateIf = myVal
End Function

Function FreezeAfter(expression As String, deadline As Date) As Variant
    Application.Volatile
    Dim myText As String
    Dim myVal As Variant
    If Now > deadline Then
        myText = Application.Caller.Text
        If IsNumeric(myText) Then
            myVal = Val(myText)
        Else
            myVal = myText
        End If
    Else
        myVal = Application.Evaluate(expression)
    End If
    FreezeAfter = myVal
End Function
</code>```

How do I copy cell values programatically?

using this script:

```<code>function getRangeValues() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange("A2:B4");
  var values = range.getValues();
  return values;
};
</code>```

With Sheet here:
Copy cell values programmatically (72539)

Lastly:

Add the Current Date to a Sheet When Data Is Added So That The Date Does Not Change(Static) – Google Sheets

using this script:

```<code>/**
* Creates a Date Stamp if a column is edited.
* https://yagisanatode.com/2018/02/21/add-the-current-date-to-a-sheet-when-data-is-added-so-that-the-date-does-not-changestatic-google-sheets/
*/

//CORE VARIABLES
// The column you want to check if something is entered.
var COLUMNTOCHECK = 6;
// Where you want the date time stamp offset from the input location. [row, column]
var DATETIMELOCATION = [0,-5];
// Sheet you are working on
var SHEETNAME = 'Sheet3'

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  //checks that we're on the correct sheet.
  if( sheet.getSheetName() == SHEETNAME ) {
    var selectedCell = ss.getActiveCell();
    //checks the column to ensure it is on the one we want to cause the date to appear.
    if( selectedCell.getColumn() == COLUMNTOCHECK) {
      var dateTimeCell = selectedCell.offset(DATETIMELOCATION[0],DATETIMELOCATION[8]);
      dateTimeCell.setValue(new Date());
      }
  }
}
</code>```

But I don't see how to make it work.

The expected result shoud be simply add ordinal number to corresponding cell in column A upon entering data on corresponding cell in column B.

How do we do that?

答:
Flow:

Use edit trigger to capture events in Col B

Get all of Col A on edit of Col B

Calculate Max of Col A and add 1

SetValue the max to Col A

Snippet:

```<code>function onEdit(e) {
  var rg = e.range,
    row = rg.rowStart,
    col = rg.columnStart,
    sht = rg.getSheet();

  //exit code
  if (col !== 2 || sht.getName() !== 'Sheet1' || row === 1) return;

  //Calculate max value and add 1
  rg.offset(0, -1, 1, 1).setValue(//setvalue in colA
    rg
      .offset(2 - row, -1, sht.getLastRow() - 1, 1) //get all of colA
      .getValues()
      .reduce(function(acc, curr) {//get max of colA
        return Math.max(acc, Number(curr[0]));
      }, 0) + 1
  );
}
</code>```

To Read and Practice:

Array#Reduce

Range#Offset

Event Objects

Body:
How to make Google sheets automatically add the ordinal number of the current row based on the following criteria 'new entry on this particular row?

How to make it work even when the data is not entered on a row contiguous basis (for example 1st entry on row 1 (say cell B1), 2nd entry on row 2 (in B2), 3rd entry on row 3 (B3), but then 4th entry on row 9 (B9), 5th on row 11 (B11), 6th on row (B7))?

And not adding ordinals to intermediary empty rows (for example when  B5/row5, B6/row6, B8/row8, B10/row10 etc. are blanks, don't add ordinals to A5/row5, A6/row6, A8/row8, A10/row10, etc.)?

Here's the expected result:

The Sheet:
Ordinals to non-contiguous rows based on data entry timestamps

So far I've come up with this pull down formula (to be pre-set in A2 and dragged down to A12):

=IF(B2<>"",MAX($A$2:$A)+1,"")  [in A2]
=IF(B3<>"",MAX($A$2:$A)+1,"")  [in A3]
=IF(B4<>"",MAX($A$2:$A)+1,"")  [in A4]
=IF(B5<>"",MAX($A$2:$A)+1,"")  [in A5]
=IF(B6<>"",MAX($A$2:$A)+1,"")  [in A6]
=IF(B7<>"",MAX($A$2:$A)+1,"")  [in A7]
=IF(B8<>"",MAX($A$2:$A)+1,"")  [in A8]
=IF(B9<>"",MAX($A$2:$A)+1,"")  [in A9]
=IF(B10<>"",MAX($A$2:$A)+1,"")  [in A10]
=IF(B11<>"",MAX($A$2:$A)+1,"")  [in A11]
=IF(B12<>"",MAX($A$2:$A)+1,"")  [in A12]

But the result I get when I enter then data succesively  one by one in B2, B3, B4, B7, B9, and B12, is that it updates all previous cells with the new max value so that the succesion isn't achieved.

Here's a gif that shows the live result:

https://i.imgur.com/1I1Dk8f.gifv

How to lock the previous results so that the ordinal count can proceed to the next entry when it occurs consecutively?

I've consulted those post that are close to what I'm looking for:

How do you replace a formula with its result?

using this script:

function freezeOutput(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SummarySheet");
  var range = sheet.getRange("A1:A10");
  range.copyTo(range, {contentsOnly:true});
}

Stop Excel from updating formula after a criteria is matched

using this formula:

=IF(NOW() < C1,2*A1,A2)

Alternatively this VBA code:

Function EvaluateIf(expression As String, condition As Boolean) As Variant
    Application.Volatile
    Dim myText As String
    Dim myVal As Variant
    If condition Then
        myVal = Application.Evaluate(expression)
    Else
        myText = Application.Caller.Text
        If IsNumeric(myText) Then
            myVal = Val(myText)
        Else
            myVal = myText
        End If
    End If
    EvaluateIf = myVal
End Function

Function FreezeAfter(expression As String, deadline As Date) As Variant
    Application.Volatile
    Dim myText As String
    Dim myVal As Variant
    If Now > deadline Then
        myText = Application.Caller.Text
        If IsNumeric(myText) Then
            myVal = Val(myText)
        Else
            myVal = myText
        End If
    Else
        myVal = Application.Evaluate(expression)
    End If
    FreezeAfter = myVal
End Function

How do I copy cell values programatically?

using this script:

function getRangeValues() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange("A2:B4");
  var values = range.getValues();
  return values;
};

With Sheet here:
Copy cell values programmatically (72539)

Lastly:

Add the Current Date to a Sheet When Data Is Added So That The Date Does Not Change(Static) – Google Sheets

using this script:

/**
* Creates a Date Stamp if a column is edited.
* https://yagisanatode.com/2018/02/21/add-the-current-date-to-a-sheet-when-data-is-added-so-that-the-date-does-not-changestatic-google-sheets/
*/

//CORE VARIABLES
// The column you want to check if something is entered.
var COLUMNTOCHECK = 6;
// Where you want the date time stamp offset from the input location. [row, column]
var DATETIMELOCATION = [0,-5];
// Sheet you are working on
var SHEETNAME = 'Sheet3'

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  //checks that we're on the correct sheet.
  if( sheet.getSheetName() == SHEETNAME ) {
    var selectedCell = ss.getActiveCell();
    //checks the column to ensure it is on the one we want to cause the date to appear.
    if( selectedCell.getColumn() == COLUMNTOCHECK) {
      var dateTimeCell = selectedCell.offset(DATETIMELOCATION[0],DATETIMELOCATION[8]);
      dateTimeCell.setValue(new Date());
      }
  }
}

But I don't see how to make it work.

The expected result shoud be simply add ordinal number to corresponding cell in column A upon entering data on corresponding cell in column B.

How do we do that?

Body:
Flow:

Use edit trigger to capture events in Col B

Get all of Col A on edit of Col B

Calculate Max of Col A and add 1

SetValue the max to Col A

Snippet:

function onEdit(e) {
  var rg = e.range,
    row = rg.rowStart,
    col = rg.columnStart,
    sht = rg.getSheet();

  //exit code
  if (col !== 2 || sht.getName() !== 'Sheet1' || row === 1) return;

  //Calculate max value and add 1
  rg.offset(0, -1, 1, 1).setValue(//setvalue in colA
    rg
      .offset(2 - row, -1, sht.getLastRow() - 1, 1) //get all of colA
      .getValues()
      .reduce(function(acc, curr) {//get max of colA
        return Math.max(acc, Number(curr[0]));
      }, 0) + 1
  );
}

To Read and Practice:

Array#Reduce

Range#Offset

Event Objects


答:
pop returns the element at the top of the stack, and then removes that element. You cannot modify a collection while iterating over it with an enhanced for loop, since, as you've seen, you'll get a ConcurrentModificationException.

One approach could be to use a while loop and iterate over the stack until its depleted:

```<code>while (!stack.empty()) {
    sb.append(stack.pop());
}
</code>```

Body:
I wrote a code for string reversing using Stack and StringBuilder classes. And I have noticed that 'foreach' loop in this code generates java.util.ConcurrentModificationException, but usual 'for' loop instead does not. So why?

public static String reverse(String str)
{
    Stack<Character> stack = new Stack<>();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++)
        stack.push(str.toCharArray()[i]);
    }

    for (Character c: stack) // generates an exception
    {
        sb.append(stack.pop());
    }

    return sb.toString();
}

I expected a reversed string, but ConcurrentModificationException has occured.

Body:
pop returns the element at the top of the stack, and then removes that element. You cannot modify a collection while iterating over it with an enhanced for loop, since, as you've seen, you'll get a ConcurrentModificationException.

One approach could be to use a while loop and iterate over the stack until its depleted:

while (!stack.empty()) {
    sb.append(stack.pop());
}


问:
Best practices for multithreaded processing of database records
I have a single process that queries a table for records where PROCESS_IND = 'N', does some processing, and then updates the PROCESS_IND to 'Y'.

I'd like to allow for multiple instances of this process to run, but don't know what the best practices are for avoiding concurrency problems.

Where should I start?

答: Convert the procedure to a single SQL statement and process multiple rows as a single batch. This is how databases are supposed to work.</p>

OwnerDisplayName: Mike S

LastEditorDisplayName: Drew Noakes

OwnerDisplayName: David Aldridge


问:
At what time will MySQL execute events that are scheduled every DAY?
If I create an event in mysql with the interval every day like this:

```<code>CREATE EVENT `event`
ON SCHEDULE EVERY '1' DAY ON COMPLETION PRESERVE
ENABLE COMMENT '' DO
UPDATE table SET something = something + 1;
</code>```

On what time of the day will it execute? I would assume 0AM but the specification does not mention it.

Yes, I am aware that it is possible to specify specific times, however I would like to keep it simple.

答:
Not specifying STARTS is the same as using STARTS
  CURRENT_TIMESTAMP—that is, the action specified for the event begins
  repeating immediately upon creation of the event.

from the MySQL Reference

Body:
If I create an event in mysql with the interval every day like this:

CREATE EVENT `event`
ON SCHEDULE EVERY '1' DAY ON COMPLETION PRESERVE
ENABLE COMMENT '' DO
UPDATE table SET something = something + 1;

On what time of the day will it execute? I would assume 0AM but the specification does not mention it.

Yes, I am aware that it is possible to specify specific times, however I would like to keep it simple.


问:
Log cypher queries
Is there a way to log cypher queries that get generated when we use spring jpa inbuilt queries like findById!? I have a complex inbuilt query whose cypher I need to see</p>

答:
Using Spring Boot 2.1.5, I am able to log Spring Data Neo4j generated Cypher queries just by adding:

```<code>logging.level.org.neo4j.ogm.drivers.bolt.request.BoltRequest=DEBUG
</code>```

to application.properties.

Title: Log cypher queries

Body:
Using Spring Boot 2.1.5, I am able to log Spring Data Neo4j generated Cypher queries just by adding:

logging.level.org.neo4j.ogm.drivers.bolt.request.BoltRequest=DEBUG

to application.properties.


问:
Iterate over functions in Swift
I am feeling a bit stupid... I want to get rid of code duplication and so I need to iterate over some functions (a couple of Darwin geometric ones).
But when I try

```<code>for function in [Darwin.acos, Darwin.cos, Darwin.sin] { print(function(1.0)) }
</code>```

I get the error "Ambiguous use of 'acos'". I also tried Darwin.acos(Double) and got "Ambiguous reference to member 'acos'" and Darwin.acos { $0 } (and similar) without any luck.

Is it possible to do this? Thank you!

答:
You have to specify the type somewhere:

```<code>let functions: [(Double) -> Double] = [Darwin.acos, Darwin.cos, Darwin.sin]
for function in functions { print(function(1.0)) }
</code>```

since the functions are overloaded for different floating point types:

```<code>public func acos(_: Float) -> Float
public func acos(_: Double) -> Double
public func acos(_: Float80) -> Float80
</code>```

Title: Iterate over functions in Swift

Body:
I am feeling a bit stupid... I want to get rid of code duplication and so I need to iterate over some functions (a couple of Darwin geometric ones).
But when I try

for function in [Darwin.acos, Darwin.cos, Darwin.sin] { print(function(1.0)) }

I get the error "Ambiguous use of 'acos'". I also tried Darwin.acos(Double) and got "Ambiguous reference to member 'acos'" and Darwin.acos { $0 } (and similar) without any luck.

Is it possible to do this? Thank you!

Body:
You have to specify the type somewhere:

let functions: [(Double) -> Double] = [Darwin.acos, Darwin.cos, Darwin.sin]
for function in functions { print(function(1.0)) }

since the functions are overloaded for different floating point types:

public func acos(_: Float) -> Float
public func acos(_: Double) -> Double
public func acos(_: Float80) -> Float80


问:
How to set the today's date in datepicker textbox in angularjs
I have two datepicker textbox From date and To Date... I need default in From date this month start date and To date today's day...

How to set default dates in Angularjs Datepicker textbox..?

答:
```<code>$scope.date = new Date().toLocaleDateString()

<input datepicker data-ng-model="date" type="date" />
</code>```


问:
How can I get the code of the function logisticregression() of sklearn.linear_model.LogisticRegression which is used in jupyter notebook?
I am using the function logisticregression() in jupyter notebook. I want to understand how that function works.</p>

答:
You can find the file system location of the package linear_model that owns the class thus:

```<code>>>> from sklearn import linear_model
>>> linear_model
<module 'sklearn.linear_model' from '/Users/awatters/anaconda3/lib/python3.6/site-packages/sklearn/linear_model/__init__.py'>
>>>
</code>```

(The path will be different in your environment, of course.)  Then look in the __init__.py file at the path shown to find

```<code>from .logistic import (LogisticRegression, LogisticRegressionCV,
                   logistic_regression_path)
</code>```

Then open the logistic.py in the same directory in an editor to find

```<code>class LogisticRegression(BaseEstimator, LinearClassifierMixin,
                     SparseCoefMixin):
    ...
</code>```

Sadly the implementation is rather complex and hard to follow, but that's how to find it.

Body:
You can find the file system location of the package linear_model that owns the class thus:

>>> from sklearn import linear_model
>>> linear_model
<module 'sklearn.linear_model' from '/Users/awatters/anaconda3/lib/python3.6/site-packages/sklearn/linear_model/__init__.py'>
>>>

(The path will be different in your environment, of course.)  Then look in the __init__.py file at the path shown to find

from .logistic import (LogisticRegression, LogisticRegressionCV,
                   logistic_regression_path)

Then open the logistic.py in the same directory in an editor to find

class LogisticRegression(BaseEstimator, LinearClassifierMixin,
                     SparseCoefMixin):
    ...

Sadly the implementation is rather complex and hard to follow, but that's how to find it.


问:
Writing to has_many :through associations and callbacks
Consider a "Name" model which has a required "label" attribute and an arbitrary Rails 3 model "Foo" with the following associations:

```<code>has_many :names, :dependent => :destroy
has_many :special_names, :through => :names, :source => :label, :conditions => { 'special_names.label' => 'special' }, :dependent => :destroy
</code>```

Now it's possible to access the "special_names" attribute for reading the association, but writing to it fails because AR cannot infer from the condition that the "label" attribute needs to be set to "special" for all members of the "special names" association.

I attempted to use the "add_before" association callback, but that never gets called with the join model (instead the ":source" and "Foo" are used).

Any ideas on how to handle this in the model (as opposed to: using special logic in the controller to deal with this - that's how I handle it currently)?

Edit: (regarding the answer from Ray Baxter)

The relationship expressed is actually a "has_many :through" association. I'll try again, this time with a (hopefully) better example:

```<code># Label is a shared entity which is used in many contexts
has_many :labels, :through => :user_labels

# UserLabel is the join model which qualifies the usage of a Label
has_many :user_labels, :dependent => :destroy

# special_user_labels is the topic of this question
has_many :special_user_labels, :through => :user_labels, :source => :label, :conditions => { 'user_labels.descriptor' => 'special' }, :dependent => :destroy
</code>```

答:
If my comment above is correct, and you aren't doing a has_many :through, this works:

```<code>has_many :special_names, :class_name => 'Name', :conditions => {:label => 'special'}, :dependent => :destroy
</code>```

so now you can do

```<code>foo = Foo.create
foo.special_name.build
</code>```

and ActiveRecord will correctly instantiate your special_name with the label attribute having the value "special".

Body:
Consider a "Name" model which has a required "label" attribute and an arbitrary Rails 3 model "Foo" with the following associations:

has_many :names, :dependent => :destroy
has_many :special_names, :through => :names, :source => :label, :conditions => { 'special_names.label' => 'special' }, :dependent => :destroy

Now it's possible to access the "special_names" attribute for reading the association, but writing to it fails because AR cannot infer from the condition that the "label" attribute needs to be set to "special" for all members of the "special names" association.

I attempted to use the "add_before" association callback, but that never gets called with the join model (instead the ":source" and "Foo" are used).

Any ideas on how to handle this in the model (as opposed to: using special logic in the controller to deal with this - that's how I handle it currently)?

Edit: (regarding the answer from Ray Baxter)

The relationship expressed is actually a "has_many :through" association. I'll try again, this time with a (hopefully) better example:

# Label is a shared entity which is used in many contexts
has_many :labels, :through => :user_labels

# UserLabel is the join model which qualifies the usage of a Label
has_many :user_labels, :dependent => :destroy

# special_user_labels is the topic of this question
has_many :special_user_labels, :through => :user_labels, :source => :label, :conditions => { 'user_labels.descriptor' => 'special' }, :dependent => :destroy

Body:
If my comment above is correct, and you aren't doing a has_many :through, this works:

has_many :special_names, :class_name => 'Name', :conditions => {:label => 'special'}, :dependent => :destroy

so now you can do

foo = Foo.create
foo.special_name.build

and ActiveRecord will correctly instantiate your special_name with the label attribute having the value "special".