问:
Adding class to existing class using dojo when custom sort is applied on enhanced grid view
Created a dojo enhanced Grid, with custom sorting. How to add sort arrows(up/down) to existing classes with code and not using css.

var mygrid = new EnhancedGrid({
    id: "grid",
    store: gridStore,
    structure: gridStructure,
    canSort : function(index){
        alert(index);
    }
}, dojo.byId("mydatagrid"))```
</div>
</div>
</p>

<p>I have tried using create, place, domclass in dojo. But it is working as expected.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code><div hidefocus="hidefocus" role="grid" dojoattachevent="onmouseout:_mouseOut" tabindex="0" aria-multiselectable="true" class="dojoxGrid" id="grid" widgetid="grid" style="width: 680px; height: auto; -moz-user-select: none;" aria-readonly="true" align="left">
 <div class="dojoxGridMasterHeader" dojoattachpoint="viewsHeaderNode" role="presentation" style="display: block; height: 24px;"><div class="dojoxGridHeader" dojoattachpoint="headerNode" role="presentation" style="width: 679px; left: 1px; top: 0px;">
  <div dojoattachpoint="headerNodeContainer" style="width:9000em" role="presentation">
   <div dojoattachpoint="headerContentNode" role="row"><table class="dojoxGridRowTable" role="presentation" cellspacing="0" cellpadding="0" border="0"><tbody><tr><th tabindex="-1" aria-readonly="true" role="columnheader" id="gridHdr0" class="dojoxGridCell dojoDndItem" idx="0" style="width:200px;" dndtype="gridColumn_grid"><div class="dojoxGridSortNode">COLUMNVALUE</div></th><th tabindex="-1" aria-readonly="true" role="columnheader" id="gridHdr1" class="dojoxGridCell dojoDndItem" idx="1" style="width:200px;" dndtype="gridColumn_grid"><div class="dojoxGridSortNode">RULEEXECUTABLENAME</div></th><th tabindex="-1" aria-readonly="true" role="columnheader" id="gridHdr2" class="dojoxGridCell dojoDndItem" idx="2" style="width:200px;" dndtype="gridColumn_grid"><div class="dojoxGridSortNode">SYSTEMTIMESTAMP</div></th></tr></tbody></table></div>
  </div>
 </div></div><table class="dojoxGridFBar" role="presentation" dojoattachevent="onclick:_onClickFilterBar, onmouseenter:_onMouseEnter, onmouseleave:_onMouseLeave, onmousemove:_onMouseMove" id="dojox_grid_enhanced_plugins_filter_FilterBar_0" widgetid="dojox_grid_enhanced_plugins_filter_FilterBar_0" cellspacing="0" border="0"><tbody><tr><td class="dojoxGridFBarBtnTD"><span class="dijit dijitReset dijitInline dijitButton dojoxGridFBarBtn" role="presentation" widgetid="dijit_form_Button_6" title="Define filter" aria-label="Filter the table"><span class="dijitReset dijitInline dijitButtonNode" data-dojo-attach-event="ondijitclick:__onClick" role="presentation"><span class="dijitReset dijitStretch dijitButtonContents" data-dojo-attach-point="titleNode,focusNode" role="button" aria-labelledby="dijit_form_Button_6_label" tabindex="0" id="dijit_form_Button_6" style="-moz-user-select: none;"><span class="dijitReset dijitInline dijitIcon dojoxGridFBarDefFilterBtnIcon" data-dojo-attach-point="iconNode"></span><span class="dijitReset dijitToggleButtonIconChar">●</span><span class="dijitReset dijitInline dijitButtonText" id="dijit_form_Button_6_label" data-dojo-attach-point="containerNode">...</span></span></span><input value="" class="dijitOffScreen" data-dojo-attach-event="onclick:_onClick" tabindex="-1" aria-hidden="true" data-dojo-attach-point="valueNode" type="button"></span></td><td class="dojoxGridFBarInfoTD"><span class="dojoxGridFBarInner"><span class="dojoxGridFBarStatus" dojoattachpoint="statusBarNode">No filter applied</span><span class="dijit dijitReset dijitInline dijitButton dojoxGridFBarClearFilterBtn" role="presentation" widgetid="dijit_form_Button_7" style="display: none;" aria-label="Clear the filter"><span class="dijitReset dijitInline dijitButtonNode" data-dojo-attach-event="ondijitclick:__onClick" role="presentation"><span class="dijitReset dijitStretch dijitButtonContents" data-dojo-attach-point="titleNode,focusNode" role="button" aria-labelledby="dijit_form_Button_7_label" tabindex="0" id="dijit_form_Button_7" style="-moz-user-select: none;"><span class="dijitReset dijitInline dijitIcon dojoxGridFBarClearFilterBtnIcon" data-dojo-attach-point="iconNode"></span><span class="dijitReset dijitToggleButtonIconChar">●</span><span class="dijitReset dijitInline dijitButtonText" id="dijit_form_Button_7_label" data-dojo-attach-point="containerNode">Clear filter</span></span></span><input value="" class="dijitOffScreen" data-dojo-attach-event="onclick:_onClick" tabindex="-1" aria-hidden="true" data-dojo-attach-point="valueNode" type="button"></span><span class="dijit dijitReset dijitInline dijitButton dojoxGridFBarCloseBtn" role="presentation" widgetid="dijit_form_Button_8" style="display: none;"><span class="dijitReset dijitInline dijitButtonNode" data-dojo-attach-event="ondijitclick:__onClick" role="presentation"><span class="dijitReset dijitStretch dijitButtonContents" data-dojo-attach-point="titleNode,focusNode" role="button" aria-labelledby="dijit_form_Button_8_label" tabindex="0" id="dijit_form_Button_8" title="Close filter bar" style="-moz-user-select: none;"><span class="dijitReset dijitInline dijitIcon dojoxGridFBarCloseBtnIcon" data-dojo-attach-point="iconNode"></span><span class="dijitReset dijitToggleButtonIconChar">●</span><span class="dijitReset dijitInline dijitButtonText dijitDisplayNone" id="dijit_form_Button_8_label" data-dojo-attach-point="containerNode">Close filter bar</span></span></span><input value="" class="dijitOffScreen" data-dojo-attach-event="onclick:_onClick" tabindex="-1" aria-hidden="true" data-dojo-attach-point="valueNode" type="button"></span></span></td></tr></tbody></table>
 <div class="dojoxGridMasterView" dojoattachpoint="viewsNode" role="presentation" style="height: 220px;"><div class="dojoxGridView" role="presentation" id="dojox_grid__View_1" widgetid="dojox_grid__View_1" style="width: 679px; left: 1px; top: 0px;">

 <input class="dojoxGridHiddenFocus" dojoattachpoint="hiddenFocusNode" role="presentation" type="checkbox">
 <input class="dojoxGridHiddenFocus" role="presentation" type="checkbox">
 <div class="dojoxGridScrollbox" dojoattachpoint="scrollboxNode" role="presentation">
  <div class="dojoxGridContent" dojoattachpoint="contentNode" hidefocus="hidefocus" role="presentation" style="height: 220px; width: 679px;"><div role="presentation" style="position: absolute; left: 0px; top: 0px;"><div class="dojoxGridRow" role="row" aria-selected="false" style=""><table class="dojoxGridRowTable" role="presentation" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="0" style="width:200px;">Ellen</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="1" style="width:200px;">RuleCheck3</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="2" style="width:200px;">2017-05-09 18:27:11.0</td></tr></tbody></table></div><div class="dojoxGridRow dojoxGridRowOdd" role="row" aria-selected="false" style=""><table class="dojoxGridRowTable" role="presentation" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="0" style="width:200px;">Sundar</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="1" style="width:200px;">RuleCheck3</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="2" style="width:200px;">2017-05-09 18:27:11.0</td></tr></tbody></table></div><div class="dojoxGridRow" role="row" aria-selected="false" style=""><table class="dojoxGridRowTable" role="presentation" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="0" style="width:200px;">Sarah</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="1" style="width:200px;">RuleCheck3</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="2" style="width:200px;">2017-05-09 18:27:11.0</td></tr></tbody></table></div><div class="dojoxGridRow dojoxGridRowOdd" role="row" aria-selected="false" style=""><table class="dojoxGridRowTable" role="presentation" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="0" style="width:200px;">Alana</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="1" style="width:200px;">RuleCheck3</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="2" style="width:200px;">2017-05-09 18:27:11.0</td></tr></tbody></table></div><div class="dojoxGridRow" role="row" aria-selected="false" style=""><table class="dojoxGridRowTable" role="presentation" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="0" style="width:200px;">Martha</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="1" style="width:200px;">RuleCheck3</td><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="2" style="width:200px;">2017-05-09 18:27:11.0</td></tr></tbody></table></div><div class="dojoxGridRow dojoxGridRowOdd" role="row" aria-selected="false" style=""><table class="dojoxGridRowTable" role="presentation" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="0" style="width:200px;">Eleni</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="1" style="width:200px;">RuleCheck3</td><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="2" style="width:200px;">2017-05-09 18:27:11.0</td></tr></tbody></table></div><div class="dojoxGridRow" role="row" aria-selected="false" style=""><table class="dojoxGridRowTable" role="presentation" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="0" style="width:200px;">dtfy</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="1" style="width:200px;">RuleCheck3</td><td tabindex="-1" role="gridcell" class="dojoxGridCell" idx="2" style="width:200px;">2017-05-09 18:27:11.0</td></tr></tbody></table></div><div class="dojoxGridRow dojoxGridRowOdd" role="row" aria-selected="false" style=""><table class="dojoxGridRowTable" role="presentation" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="0" style="width:200px;">dryhy</td><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="1" style="width:200px;">RuleCheck3</td><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="2" style="width:200px;">2017-05-09 18:27:11.0</td></tr></tbody></table></div><div class="dojoxGridRow" role="row" aria-selected="false" style=""><table class="dojoxGridRowTable" role="presentation" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="0" style="width:200px;">David</td><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="1" style="width:200px;">RuleCheck3</td><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="2" style="width:200px;">2017-05-09 18:27:11.0</td></tr></tbody></table></div><div class="dojoxGridRow dojoxGridRowOdd" role="row" aria-selected="false" style=""><table class="dojoxGridRowTable" role="presentation" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="0" style="width:200px;">Laura</td><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="1" style="width:200px;">RuleCheck3</td><td tabindex="-1" role="gridcell" class="dojoxGridCell " idx="2" style="width:200px;">2017-05-09 18:27:11.0</td></tr></tbody></table></div></div></div>
 </div>
</div></div>
 <div class="dojoxGridMasterMessages" style="display: none;" dojoattachpoint="messagesNode"></div>
 <span dojoattachpoint="lastFocusNode" tabindex="0"></span>
</div></code>```

答:
```<code> canSort : function(index){
        alert(index);
    }
</code>```

is used to prevent column(s) from being sorted for ex: if you have three columns on your grid and for some reason, you don't want one of the column to be sorted then you use this function to limit that. If you want to sort the columns please look into plugin dojox.grid.enhanced.plugins.NestedSorting

this is how you can restrict column sorting

```<code>canSort: function(column) { return !(Math.abs(column) === 3); },
</code>```

Here column 3 is restricted for sorting. Hope this helps

Body:
Created a dojo enhanced Grid, with custom sorting. How to add sort arrows(up/down) to existing classes with code and not using css.

var mygrid = new EnhancedGrid({
    id: "grid",
    store: gridStore,
    structure: gridStructure,
    canSort : function(index){
        alert(index);
    }
}, dojo.byId("mydatagrid"))

I have tried using create, place, domclass in dojo. But it is working as expected.

COLUMNVALUE

RULEEXECUTABLENAME

SYSTEMTIMESTAMP

●...<input value="" class="dijitOffScreen" data-dojo-attach-event="onclick:_onClick" tabindex="-1" aria-hidden="true" data-dojo-attach-point="valueNode" type="button">	No filter applied●Clear filter<input value="" class="dijitOffScreen" data-dojo-attach-event="onclick:_onClick" tabindex="-1" aria-hidden="true" data-dojo-attach-point="valueNode" type="button">●Close filter bar<input value="" class="dijitOffScreen" data-dojo-attach-event="onclick:_onClick" tabindex="-1" aria-hidden="true" data-dojo-attach-point="valueNode" type="button">

 <input class="dojoxGridHiddenFocus" dojoattachpoint="hiddenFocusNode" role="presentation" type="checkbox">
 <input class="dojoxGridHiddenFocus" role="presentation" type="checkbox">

Ellen	RuleCheck3	2017-05-09 18:27:11.0

Sundar	RuleCheck3	2017-05-09 18:27:11.0

Sarah	RuleCheck3	2017-05-09 18:27:11.0

Alana	RuleCheck3	2017-05-09 18:27:11.0

Martha	RuleCheck3	2017-05-09 18:27:11.0

Eleni	RuleCheck3	2017-05-09 18:27:11.0

dtfy	RuleCheck3	2017-05-09 18:27:11.0

dryhy	RuleCheck3	2017-05-09 18:27:11.0

David	RuleCheck3	2017-05-09 18:27:11.0

Laura	RuleCheck3	2017-05-09 18:27:11.0

Body:
 canSort : function(index){
        alert(index);
    }

is used to prevent column(s) from being sorted for ex: if you have three columns on your grid and for some reason, you don't want one of the column to be sorted then you use this function to limit that. If you want to sort the columns please look into plugin dojox.grid.enhanced.plugins.NestedSorting

this is how you can restrict column sorting

canSort: function(column) { return !(Math.abs(column) === 3); },

Here column 3 is restricted for sorting. Hope this helps


来源: stackexchange

问:
pass a list by reference in R function
I have a simple recursion function in R that would modify its input arguments. I use eval.parent(substitute()) in order to apply the changes on the arguments, However I get this error:
"invalid (do_set) left-hand side to assignment "
Does anyone know how to fix this error?
Here is my function:</p>

```<code>decompose_clade=function(ind,Small_clades_ind,Remove_tips,Clades){
  Ch=Children(tree,ind)
  if(Ch[1]<length(tree$tip.label)){
    l=Remove_tips
    l=c(l,Ch[1])
    eval.parent(substitute(Remove_tips=l))
    print("tip added=")
    print(Ch[1])
  }else if(length(extract.clade(tree,Ch[1])$tip.label)<4){
    s=Small_clades_ind
    s=c(s,Ch[1])
    eval.parent(substitute(Small_clades_ind=s))
    print("small clade added=")
    print(Ch[1])
  }else if(length(extract.clade(tree,Ch[1])$tip.label)>80){
    decompose_clade(Ch[1],Small_clades_ind,Remove_tips,Clades)
    print("function calls again")
  }else{
   m=Clades
   m=c(m,Ch[1])
    eval.parent(substitute(Clades<-m))
    print("a clade added=")
    print(Ch[1])
  }

}
</code>```

答:
There is no easy way to have pass-by-reference behaviours in R, with only one exception: environment. I'm not sure if environment suits your need, you can give it a try:

```<code>modify_input <- function(x){
    x$z <- 1
}

x <- new.env(parent = emptyenv())
modify_input(x)
x$z
</code>```

As to the usage, environment supports e$z and e[["z"]] and length(e) just like list, but it doesn't support e[[1]] and things like that. You can think of environment as a dictionary and elements in it have no order. If you want to list all the elements in an environment, you can use ls. And there are ways to transform environment to list (as.list) and vise versa (list2env). Hope it can help.

ContentLicense: CC BY-SA 3.0

Title: pass a list by reference in R function

Body:
I have a simple recursion function in R that would modify its input arguments. I use eval.parent(substitute()) in order to apply the changes on the arguments, However I get this error:
"invalid (do_set) left-hand side to assignment "
Does anyone know how to fix this error?
Here is my function:

decompose_clade=function(ind,Small_clades_ind,Remove_tips,Clades){
  Ch=Children(tree,ind)
  if(Ch[1]<length(tree$tip.label)){
    l=Remove_tips
    l=c(l,Ch[1])
    eval.parent(substitute(Remove_tips=l))
    print("tip added=")
    print(Ch[1])
  }else if(length(extract.clade(tree,Ch[1])$tip.label)<4){
    s=Small_clades_ind
    s=c(s,Ch[1])
    eval.parent(substitute(Small_clades_ind=s))
    print("small clade added=")
    print(Ch[1])
  }else if(length(extract.clade(tree,Ch[1])$tip.label)>80){
    decompose_clade(Ch[1],Small_clades_ind,Remove_tips,Clades)
    print("function calls again")
  }else{
   m=Clades
   m=c(m,Ch[1])
    eval.parent(substitute(Clades<-m))
    print("a clade added=")
    print(Ch[1])
  }

}

Body:
There is no easy way to have pass-by-reference behaviours in R, with only one exception: environment. I'm not sure if environment suits your need, you can give it a try:

modify_input <- function(x){
    x$z <- 1
}

x <- new.env(parent = emptyenv())
modify_input(x)
x$z

As to the usage, environment supports e$z and e[["z"]] and length(e) just like list, but it doesn't support e[[1]] and things like that. You can think of environment as a dictionary and elements in it have no order. If you want to list all the elements in an environment, you can use ls. And there are ways to transform environment to list (as.list) and vise versa (list2env). Hope it can help.


问:
For loop for calculating score, how to combine two methods
In my method public static int PointsCalculator() I seem to be unable to use my values from my two other methods in order to compare the values in the two array and give points.

I'm not really sure how to call or initialize the values to begin but tried to do a quick mockup.

My goal is to add one point for every user value in the GetUserGuesses method that is the same as the random values in the RandomBingoNumbers method.

```<code>class UserBingo // Creates a class to store all user related
{
    static int[] RandomNrs;
    static int[] userGuesses;
    static int num = 0;

    public static int[] GetUserGuess() // A method for collecting user guesses and displaying them (SPLIT THEM UP)
    {

        userGuesses = new int[10]; // Creates the array to store 10 user inputs
        for (int i = 0; i < userGuesses.Length; i++)  // For loop itterates until 10 user values are put into the array
        {
            try
            {
                int input = Convert.ToInt32(Console.ReadLine());

                if (input < 1 || input > 25) // Only values between 1-25
                {
                    Console.WriteLine("Only enter a number between 1-25");
                    i--;
                }
                else if (userGuesses.Contains(input)) // Checks for repeated values
                {
                    Console.WriteLine("You have already entered {0}", input);
                    i--;
                }
                else
                {
                    userGuesses[i] = input;  //When they do meet the correct values
                    Console.WriteLine("Thanks for entering the number " + input);
                }

            }
            catch (Exception)
            {

                Console.WriteLine("Only numbers can be entered, ");
                i--;
            }

        }

        for (int i = 0; i < userGuesses.Length; i++) // Loop to display all the input values in the array
        {
            Console.Write(userGuesses[i]);
        }
        return userGuesses;

    }
    public static int[] RandomBingoNumbers() // Method for creating 10 random integers
    {

        RandomNrs = new int[10]; // Creates an array to store 10 integer
        Random rnd = new Random();
        for (int i = 0; i < RandomNrs.Length; i++)
        {
            num = rnd.Next(1, 25);
            if (RandomNrs.Contains(num))
                i--;

            else
                RandomNrs[i] = num;

        }
        return RandomNrs;
    }

    public static int PointsCalculator() //Method for calculating score
    {
        int points = 0; // Integer to hold the amount of correct guesses

        for (int i = 0; i < 10; i++)
        {

            if (RandomNrs[i] == userGuesses[i]) // Check if the 10 user inputs is the same as the 10 randomized numbers
            {
                points++;
            }

        }

        Console.WriteLine("Your Numbers: \n [{0}]", string.Join(", ", userGuesses)); // Display user inputed numbers
        Console.WriteLine("Bingo Numbers: \n [{0}]", string.Join(", ", RandomNrs)); // Display the random bingo numbers
        Console.WriteLine("You got: " + points + "poäng"); // Display the amount of correct guesses
        return points;
    }
}
</code>```

}

答:
Add a using System.Linq;
Lot of mistakes.

```<code> if (GetUserGuess == RandomBingoNumbers
            ) // Check if the 10 user inputs is the same as the 10 randomized numbers
            {
                points++;
            }
</code>```

should be

```<code>if (GetUserGuess().SequenceEqual(RandomBingoNumbers())
             // Check if the 10 user inputs is the same as the 10 randomized numbers
            {
                points++;
            }
</code>```

And so many other mistakes, like the RandomNrs must be a static int[] declared outside the function. etc. etc..
This assignment is wrong RandomNrs[i] = new UserBingoNrs;. I'd suggest you to go over the entire syntax and usage of functions.

UPDATE 1

Instead of this

```<code>int[] RandomNrs = new int[10]; // Creates an array to store 10 integer
int[] userGuesses = new int[10]; // Creates the array to store 10 user inputs
</code>```

you should use

```<code>RandomNrs = new int[10]; // Creates an array to store 10 integer
userGuesses = new int[10]; // Creates the array to store 10 user inputs
</code>```

because RandomNrs and userGuesses  is already defined globally.

and instead of

RandomNrs == userGuesses and RandomNrs != userGuesses

you must use
RandomNrs[i] == userGuesses[i]) and RandomNrs[i]!=userGuesses[i]

```<code>else if (RandomNrs[i] != userGuesses[i]) // If user guesses are not equal to array points
                i--;
</code>```

This will probably cause an infinite loop, instead of i--, do points--;

UPDATE 2

As simple as this

```<code>int num= rnd.Next(1, 25);
while(RandomNrs.Contains(num))
num = rnd.Next(1,25);
</code>```

UPDATE 3

Change your PointsCalculator for loop to this

```<code>for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
if (RandomNrs[i] == userGuesses[j]) // Check if the 10 user inputs is the same as the 10 randomized numbers
{
points++;
 }
}
</code>```

Body:
In my method public static int PointsCalculator() I seem to be unable to use my values from my two other methods in order to compare the values in the two array and give points.

I'm not really sure how to call or initialize the values to begin but tried to do a quick mockup.

My goal is to add one point for every user value in the GetUserGuesses method that is the same as the random values in the RandomBingoNumbers method.

class UserBingo // Creates a class to store all user related
{
    static int[] RandomNrs;
    static int[] userGuesses;
    static int num = 0;

    public static int[] GetUserGuess() // A method for collecting user guesses and displaying them (SPLIT THEM UP)
    {

        userGuesses = new int[10]; // Creates the array to store 10 user inputs
        for (int i = 0; i < userGuesses.Length; i++)  // For loop itterates until 10 user values are put into the array
        {
            try
            {
                int input = Convert.ToInt32(Console.ReadLine());

                if (input < 1 || input > 25) // Only values between 1-25
                {
                    Console.WriteLine("Only enter a number between 1-25");
                    i--;
                }
                else if (userGuesses.Contains(input)) // Checks for repeated values
                {
                    Console.WriteLine("You have already entered {0}", input);
                    i--;
                }
                else
                {
                    userGuesses[i] = input;  //When they do meet the correct values
                    Console.WriteLine("Thanks for entering the number " + input);
                }

            }
            catch (Exception)
            {

                Console.WriteLine("Only numbers can be entered, ");
                i--;
            }

        }

        for (int i = 0; i < userGuesses.Length; i++) // Loop to display all the input values in the array
        {
            Console.Write(userGuesses[i]);
        }
        return userGuesses;

    }
    public static int[] RandomBingoNumbers() // Method for creating 10 random integers
    {

        RandomNrs = new int[10]; // Creates an array to store 10 integer
        Random rnd = new Random();
        for (int i = 0; i < RandomNrs.Length; i++)
        {
            num = rnd.Next(1, 25);
            if (RandomNrs.Contains(num))
                i--;

            else
                RandomNrs[i] = num;

        }
        return RandomNrs;
    }

    public static int PointsCalculator() //Method for calculating score
    {
        int points = 0; // Integer to hold the amount of correct guesses

        for (int i = 0; i < 10; i++)
        {

            if (RandomNrs[i] == userGuesses[i]) // Check if the 10 user inputs is the same as the 10 randomized numbers
            {
                points++;
            }

        }

        Console.WriteLine("Your Numbers: \n [{0}]", string.Join(", ", userGuesses)); // Display user inputed numbers
        Console.WriteLine("Bingo Numbers: \n [{0}]", string.Join(", ", RandomNrs)); // Display the random bingo numbers
        Console.WriteLine("You got: " + points + "poäng"); // Display the amount of correct guesses
        return points;
    }
}

}

Body:
Add a using System.Linq;
Lot of mistakes.

 if (GetUserGuess == RandomBingoNumbers
            ) // Check if the 10 user inputs is the same as the 10 randomized numbers
            {
                points++;
            }

should be

if (GetUserGuess().SequenceEqual(RandomBingoNumbers())
             // Check if the 10 user inputs is the same as the 10 randomized numbers
            {
                points++;
            }

And so many other mistakes, like the RandomNrs must be a static int[] declared outside the function. etc. etc..
This assignment is wrong RandomNrs[i] = new UserBingoNrs;. I'd suggest you to go over the entire syntax and usage of functions.

UPDATE 1

Instead of this

int[] RandomNrs = new int[10]; // Creates an array to store 10 integer
int[] userGuesses = new int[10]; // Creates the array to store 10 user inputs

you should use

RandomNrs = new int[10]; // Creates an array to store 10 integer
userGuesses = new int[10]; // Creates the array to store 10 user inputs

because RandomNrs and userGuesses  is already defined globally.

and instead of

RandomNrs == userGuesses and RandomNrs != userGuesses

you must use
RandomNrs[i] == userGuesses[i]) and RandomNrs[i]!=userGuesses[i]

else if (RandomNrs[i] != userGuesses[i]) // If user guesses are not equal to array points
                i--;

This will probably cause an infinite loop, instead of i--, do points--;

UPDATE 2

As simple as this

int num= rnd.Next(1, 25);
while(RandomNrs.Contains(num))
num = rnd.Next(1,25);

UPDATE 3

Change your PointsCalculator for loop to this

for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
if (RandomNrs[i] == userGuesses[j]) // Check if the 10 user inputs is the same as the 10 randomized numbers
{
points++;
 }
}


问:
Retrieve the expiry time of certificates in PEM format
I have a requirement to inform customers that their certificate is going to expire in some days so renew before that time work TLS encryption to work as expected.

How do I retrieve the expiry time of certificates in PEM format?

答:
```<code> #if FROMFILE
 BIO* bio = BIO_new_file(filename, "rb");
 if (bio == null) goto err;
 #else
 BIO* bio = BIO_new(BIO_s_mem());
 BIO_write(bio, data, dataLen);
 #endif

 X509* x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
 if (x509 == null) goto err;

 #if OPENSSL_11
 ASN1_TIME* notBefore = X509_get0_notBefore(x509);
 #else
 ASN1_TIME* notBefore = x509->validity->notBefore;
 #endif

 // Choose a time representation and convert the ASN1_TIME to it.

 goto cleanup;

 err:
 // Exercise left to the reader.

 cleanup:
 // Don't free notBefore, since it was obtained via a get0 or interior pointer.
 if (x509) X509_free(x509);
 if (bio) BIO_free(bio);
</code>```


问:
Trying to get a sorted array from object values
Basically I'm trying to copy the first answer on this page (Sorting object properties based on value), and sort my object into an array. But I get this error message:

TypeError: Cannot convert undefined or null to object

What is wrong?

  const denom = {
  'ONE HUNDRED': 100.00,
  'TWENTY' : 20.00,
  'TEN' : 10.00,
  'FIVE': 5.00,
  'ONE' : 1.00,
  'QUARTER': 0.25,
  'DIME': 0.10,
  'NICKEL': 0.05,
  'PENNY': 0.01
  };

  const denomSorted = Object.keys(denom[0]).sort((a, b) => denom[0][b] - denom[0][a]);

denomSorted.forEach(x => console.log(x + ': ' + denom[0][x]));```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  </code>```

答:
Cause denom[0] is undefined

```<code>Object.keys(denom[0])
</code>```

will fail. May do Object.keys(denom), and sort after keys:

const denom = {
  'ONE HUNDRED': 100.00,
  'TWENTY' : 20.00,
  'TEN' : 10.00,
  'FIVE': 5.00,
  'ONE' : 1.00,
  'QUARTER': 0.25,
  'DIME': 0.10,
  'NICKEL': 0.05,
  'PENNY': 0.01
  };

  const denomSorted = Object.keys(denom).sort((a, b) => a.localeCompare(b));

denomSorted.forEach(x => console.log(x + ': ' + denom[x]));```
</div>
</div>
</p>

<p>or after values:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    const denom = {
    'ONE HUNDRED': 100.00,
      'TWENTY' : 20.00,
      'TEN' : 10.00,
      'FIVE': 5.00,
      'ONE' : 1.00,
      'QUARTER': 0.25,
      'DIME': 0.10,
      'NICKEL': 0.05,
      'PENNY': 0.01
      };

      const denomSorted = Object.keys(denom).sort((a, b) => denom[a]- denom[b]);

    denomSorted.forEach(x => console.log(x + ': ' + denom[x]));</code>```

Body:
Cause denom[0] is undefined

Object.keys(denom[0])

will fail. May do Object.keys(denom), and sort after keys:

const denom = {
  'ONE HUNDRED': 100.00,
  'TWENTY' : 20.00,
  'TEN' : 10.00,
  'FIVE': 5.00,
  'ONE' : 1.00,
  'QUARTER': 0.25,
  'DIME': 0.10,
  'NICKEL': 0.05,
  'PENNY': 0.01
  };

  const denomSorted = Object.keys(denom).sort((a, b) => a.localeCompare(b));

denomSorted.forEach(x => console.log(x + ': ' + denom[x]));

or after values:

    const denom = {
    'ONE HUNDRED': 100.00,
      'TWENTY' : 20.00,
      'TEN' : 10.00,
      'FIVE': 5.00,
      'ONE' : 1.00,
      'QUARTER': 0.25,
      'DIME': 0.10,
      'NICKEL': 0.05,
      'PENNY': 0.01
      };

      const denomSorted = Object.keys(denom).sort((a, b) => denom[a]- denom[b]);

    denomSorted.forEach(x => console.log(x + ': ' + denom[x]));


问:
Why do I have to subtract for height of UINavigationBar twice to get UIWebView to be correct size?
I am using a UINavigationBar in my app with three different UIViewControllers. The RootViewController hides the navigation bar when its view is on top of the stack by implementing the following in RootViewController.m:

```<code>- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];

[self.navigationController setNavigationBarHidden:TRUE animated:TRUE];}
</code>```

and

```<code>- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];

[self.navigationController setNavigationBarHidden:FALSE animated:TRUE];}
</code>```

When firstViewController is pushed to the top, everything works just fine. In the IB, I told this view that it has a status bar and a navigation bar. All of its subviews (added in the IB) are laid out just as expected on the simulator and on the device.

However, when secondViewContoller is pushed to the top, things get weird. In the IB, I told the view that there was a status bar and a navigation bar just as before. I added a UIWebView to fill the remainder of the screen (verified dimensions of 320 x 416 in the IB) and it all looks correct in the IB. I ran the app on the simulator and my device, and the UIWebView runs behind the navigation bar as if it were 320 x 460.

To fix this problem, I added this code to SecondViewController.m:

```<code>- (void)viewDidLoad {
[super viewDidLoad];

[webView setFrame:CGRectMake(0.0, 44.0, 320.0, 372.0)]; }
</code>```

And now it all looks fine when running on the simulator and the device. But this isn't right! The height really is 416, not 372. Why did I have to subtract the height of the UINavigationBar twice? My hack works, but I think there is something important that I'm missing here that I really need to understand. Any ideas are greatly appreciated.

答:
Not entirely sure why you're having to subtract the height twice, but I can explain why you have to do it at all.

Basically, in viewDidLoad, your view controller and its associated view have no idea where they'll be used. This means that your view currently has no superview. If you set your frame before the view controller is presented modally, added to a navigation stack, or presented in a tab bar, the view is liable to get moved around and resized and all kinds of crazy stuff. The answer to this problem is to perform layout in viewWillAppear: instead:

```<code>- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    webView.frame = self.view.bounds;
}
</code>```

That snippet of code will adjust the web view to fill the area taken by the view controller, and will execute immediately before presenting the view on screen. When it executes, self.view has already been adjusted to account for a navigation bar, tab bar, status bar, etc.

ContentLicense: CC BY-SA 2.5

Body:
I am using a UINavigationBar in my app with three different UIViewControllers. The RootViewController hides the navigation bar when its view is on top of the stack by implementing the following in RootViewController.m:

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];

[self.navigationController setNavigationBarHidden:TRUE animated:TRUE];}

and

- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];

[self.navigationController setNavigationBarHidden:FALSE animated:TRUE];}

When firstViewController is pushed to the top, everything works just fine. In the IB, I told this view that it has a status bar and a navigation bar. All of its subviews (added in the IB) are laid out just as expected on the simulator and on the device.

However, when secondViewContoller is pushed to the top, things get weird. In the IB, I told the view that there was a status bar and a navigation bar just as before. I added a UIWebView to fill the remainder of the screen (verified dimensions of 320 x 416 in the IB) and it all looks correct in the IB. I ran the app on the simulator and my device, and the UIWebView runs behind the navigation bar as if it were 320 x 460.

To fix this problem, I added this code to SecondViewController.m:

- (void)viewDidLoad {
[super viewDidLoad];

[webView setFrame:CGRectMake(0.0, 44.0, 320.0, 372.0)]; }

And now it all looks fine when running on the simulator and the device. But this isn't right! The height really is 416, not 372. Why did I have to subtract the height of the UINavigationBar twice? My hack works, but I think there is something important that I'm missing here that I really need to understand. Any ideas are greatly appreciated.

Body:
Not entirely sure why you're having to subtract the height twice, but I can explain why you have to do it at all.

Basically, in viewDidLoad, your view controller and its associated view have no idea where they'll be used. This means that your view currently has no superview. If you set your frame before the view controller is presented modally, added to a navigation stack, or presented in a tab bar, the view is liable to get moved around and resized and all kinds of crazy stuff. The answer to this problem is to perform layout in viewWillAppear: instead:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    webView.frame = self.view.bounds;
}

That snippet of code will adjust the web view to fill the area taken by the view controller, and will execute immediately before presenting the view on screen. When it executes, self.view has already been adjusted to account for a navigation bar, tab bar, status bar, etc.


问:
Android - why I get failed to bounce to type
Here is my code in mainActivity and I do everything right I saw in tutorial but it doesn't work for me :

```<code>public class MainActivity extends AppCompatActivity {

private TextView ff;
private Firebase mFire;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Firebase.setAndroidContext(this);
    ff = (TextView)findViewById(R.id.f);

    mFire = new Firebase("https://*******.firebaseio.com/");
    mFire.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String dfg= dataSnapshot.getValue(String.class);
            ff.setText(dfg.toString());
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
}
</code>```

}

Here is my logcat:

```<code>07-05 16:25:43.630 26144-26144/com.example.freewaresys.blog E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.freewaresys.blog, PID: 26144
                                                                          com.firebase.client.FirebaseException: Failed to bounce to type
                                                                              at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
                                                                              at com.example.freewaresys.blog.MainActivity$1.onDataChange(MainActivity.java:27)
                                                                              at com.firebase.client.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:45)
                                                                              at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
                                                                              at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
                                                                              at android.os.Handler.handleCallback(Handler.java:808)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:103)
                                                                              at android.os.Looper.loop(Looper.java:193)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5333)
                                                                              at java.lang.reflect.Method.invokeNative(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:515)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
                                                                              at dalvik.system.NativeStart.main(Native Method)
                                                                           Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
                                                                           at [Source: java.io.StringReader@424ba000; line: 1, column: 1]
                                                                              at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:575)
                                                                              at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:46)
                                                                              at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)
                                                                              at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
                                                                              at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
                                                                              at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:181)
                                                                                ... 13 more
07-05 16:25:45.025 26144-26360/com.example.freewaresys.blog E/NativeCrypto: ssl=0x62e30eb0 cert_verify_callback x509_store_ctx=0x63070940 arg=0x0
07-05 16:25:45.026 26144-26360/com.example.freewaresys.blog E/NativeCrypto: ssl=0x62e30eb0 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA
</code>```

答:
```<code>mFire.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot child: dataSnapshot.getChildren()) {
           String str = child.getValue(String.class);
           ff.setText(dfg.toString());
        }

    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});
</code>```

<p>This is because,  you r listening to a value event, the onDataChange method can be called with multiple matching items. So your code should be ready to handle multiple changes. That is , your DataSnapshot object may have multiple children to which change has occured. </p>

Body:
Here is my code in mainActivity and I do everything right I saw in tutorial but it doesn't work for me :

public class MainActivity extends AppCompatActivity {

private TextView ff;
private Firebase mFire;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Firebase.setAndroidContext(this);
    ff = (TextView)findViewById(R.id.f);

    mFire = new Firebase("https://*******.firebaseio.com/");
    mFire.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String dfg= dataSnapshot.getValue(String.class);
            ff.setText(dfg.toString());
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
}

}

Here is my logcat:

07-05 16:25:43.630 26144-26144/com.example.freewaresys.blog E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.freewaresys.blog, PID: 26144
                                                                          com.firebase.client.FirebaseException: Failed to bounce to type
                                                                              at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
                                                                              at com.example.freewaresys.blog.MainActivity$1.onDataChange(MainActivity.java:27)
                                                                              at com.firebase.client.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:45)
                                                                              at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
                                                                              at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
                                                                              at android.os.Handler.handleCallback(Handler.java:808)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:103)
                                                                              at android.os.Looper.loop(Looper.java:193)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5333)
                                                                              at java.lang.reflect.Method.invokeNative(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:515)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
                                                                              at dalvik.system.NativeStart.main(Native Method)
                                                                           Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
                                                                           at [Source: java.io.StringReader@424ba000; line: 1, column: 1]
                                                                              at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:575)
                                                                              at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:46)
                                                                              at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)
                                                                              at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
                                                                              at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
                                                                              at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:181)
                                                                                ... 13 more
07-05 16:25:45.025 26144-26360/com.example.freewaresys.blog E/NativeCrypto: ssl=0x62e30eb0 cert_verify_callback x509_store_ctx=0x63070940 arg=0x0
07-05 16:25:45.026 26144-26360/com.example.freewaresys.blog E/NativeCrypto: ssl=0x62e30eb0 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA

Body:
mFire.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot child: dataSnapshot.getChildren()) {
           String str = child.getValue(String.class);
           ff.setText(dfg.toString());
        }

    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

This is because,  you r listening to a value event, the onDataChange method can be called with multiple matching items. So your code should be ready to handle multiple changes. That is , your DataSnapshot object may have multiple children to which change has occured.


问:
How do I change the border color of words matching a selection in Sublime Text 2?
For example, double clicking on a word selects it, then all matches of that word are also highlighted.

What keys do I change in my theme to change the background, foreground, and/or the border colors for the matching words?

答:
In Sublime Text 3 highlight option changes border color of matching elements

```<code><key>highlight</key>
<string>#ff00ff</string>
</code>```

Body:
In Sublime Text 3 highlight option changes border color of matching elements

<key>highlight</key>
<string>#ff00ff</string>


问:
C# NLua event handler with optional parameters
I want to register many events in lua wrapper, so I could access and do something within lua scripting. Like, for example I've got this:

```<code>addEventHandler('onEngineInit', function()
    print('Init')
end)

addEventHandler('onClientConnect', function(user)
    print(user)
end)
</code>```

The first one event 'onEngineInit' doesn't have any parameters, but other one has some. I'm thinking that I could register these events with this 'addEventHandler' function.

So, in c# the could would look something like this:

```<code>public delegate void EventHandlerMethod(params object[] args);
public delegate void EngineInit();
public delegate void ClientConnect(string name);

private event EngineInit    onEngineInit;
private event ClientConnect onClientConnect;

void Init()
{
    lua.RegisterFunction("addEventHandler", this, GetType().GetMethod("AddEventHandler"));
    lua.DoFile("script.lua");
    OnEngineInit();

    // test
    OnClientConnect("player1");
}

public void AddEventHandler(string eventName, EventHandlerMethod eventHandler)
{
    if (eventName == "onEngineInit")
        onEngineInit = eventHandler;
    else if(eventName == "onClientConnect")
        onClientConnect = eventHandler;
}

public void OnEngineInit()
{
    onEngineInit?.Invoke();
}

public void OnClientConnect(string name)
{
    onClientConnect?.Invoke(name);
}
</code>```

The point of this is to have a single function to register events in lua scripting. Is it possible to do something atleast similar?

答:
It is. You can use RegisterLuaDelegateType to register your delegate.

NLuaBox does this to register events handled on the Lua side: https://github.com/codefoco/NLuaBox/blob/master/Binder/NLuaBoxBinder.cs#L53

Use object.EventName:Add (function() end) to add the handler, like here: https://github.com/codefoco/NLuaBox/blob/master/Resources/source/ScriptListViewController.lua#L103

Body:
I want to register many events in lua wrapper, so I could access and do something within lua scripting. Like, for example I've got this:

addEventHandler('onEngineInit', function()
    print('Init')
end)

addEventHandler('onClientConnect', function(user)
    print(user)
end)

The first one event 'onEngineInit' doesn't have any parameters, but other one has some. I'm thinking that I could register these events with this 'addEventHandler' function.

So, in c# the could would look something like this:

public delegate void EventHandlerMethod(params object[] args);
public delegate void EngineInit();
public delegate void ClientConnect(string name);

private event EngineInit    onEngineInit;
private event ClientConnect onClientConnect;

void Init()
{
    lua.RegisterFunction("addEventHandler", this, GetType().GetMethod("AddEventHandler"));
    lua.DoFile("script.lua");
    OnEngineInit();

    // test
    OnClientConnect("player1");
}

public void AddEventHandler(string eventName, EventHandlerMethod eventHandler)
{
    if (eventName == "onEngineInit")
        onEngineInit = eventHandler;
    else if(eventName == "onClientConnect")
        onClientConnect = eventHandler;
}

public void OnEngineInit()
{
    onEngineInit?.Invoke();
}

public void OnClientConnect(string name)
{
    onClientConnect?.Invoke(name);
}

The point of this is to have a single function to register events in lua scripting. Is it possible to do something atleast similar?


问:
Why can't get exit code of batch file executed with command start?
When I run command Start C:\temp\sub2.bat in a command prompt window, errorlevel set is 4 and this is correct because a file which is indicated in batch does not exist. But when I run through this below, errorlevel returns 0. I have no idea why the exit codes are different.

Can anyone give me an advice for the reason?

```<code>@echo off
Call :Sub1
GOTO :EOF

:Sub1
start C:\temp\sub2.bat
echo %errorLevel%
</code>```

答:
Read the answer on How to call a batch file that is one level up from the current directory? It explains the 4 methods which exist to run a batch file from within a batch file and what are the differences.

You use command start which results in starting a new command process running parallel to the command process already executing your batch file for execution of C:\temp\sub2.bat.

The current command process immediately continues the execution of posted batch file and evaluates the exit code of command start which is 0 on successfully starting the executable or batch file.

You should use the command call to run the batch file as subroutine in your batch file and which makes it possible to evaluate the exit code set by C:\temp\sub2.bat.

```<code>@echo off
call C:\temp\sub2.bat
if errorlevel 1 echo There was an error with exit code %ERRORLEVEL%.
</code>```

It would be also possible to start the other batch file in a new command process and what on its termination for example with exit 4 in current batch file.

```<code>@echo off
start /wait C:\temp\sub2.bat
if errorlevel 1 echo There was an error with exit code %ERRORLEVEL%.
</code>```

In general it is not advisable to use exit without option /B as this results always in exiting the command process independent on calling hierarchy which makes it also impossible to debug a batch file by running it from within a command prompt window.

In case of C:\temp\sub2.bat really contains exit ExitCode without option /B and for some unknown reason the batch file can't be edited, it is really necessary to start C:\temp\sub2.bat in a separate command process and wait for its termination with start /wait.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /?

echo /?

exit /?

if /?

start /?

Read also the Microsoft support article Testing for a Specific Error Level in Batch Files.

See also the Stack Overflow questions:

What are the ERRORLEVEL values set by internal cmd.exe commands?

Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?

Body:
When I run command Start C:\temp\sub2.bat in a command prompt window, errorlevel set is 4 and this is correct because a file which is indicated in batch does not exist. But when I run through this below, errorlevel returns 0. I have no idea why the exit codes are different.

Can anyone give me an advice for the reason?

@echo off
Call :Sub1
GOTO :EOF

:Sub1
start C:\temp\sub2.bat
echo %errorLevel%

Body:
Read the answer on How to call a batch file that is one level up from the current directory? It explains the 4 methods which exist to run a batch file from within a batch file and what are the differences.

You use command start which results in starting a new command process running parallel to the command process already executing your batch file for execution of C:\temp\sub2.bat.

The current command process immediately continues the execution of posted batch file and evaluates the exit code of command start which is 0 on successfully starting the executable or batch file.

You should use the command call to run the batch file as subroutine in your batch file and which makes it possible to evaluate the exit code set by C:\temp\sub2.bat.

@echo off
call C:\temp\sub2.bat
if errorlevel 1 echo There was an error with exit code %ERRORLEVEL%.

It would be also possible to start the other batch file in a new command process and what on its termination for example with exit 4 in current batch file.

@echo off
start /wait C:\temp\sub2.bat
if errorlevel 1 echo There was an error with exit code %ERRORLEVEL%.

In general it is not advisable to use exit without option /B as this results always in exiting the command process independent on calling hierarchy which makes it also impossible to debug a batch file by running it from within a command prompt window.

In case of C:\temp\sub2.bat really contains exit ExitCode without option /B and for some unknown reason the batch file can't be edited, it is really necessary to start C:\temp\sub2.bat in a separate command process and wait for its termination with start /wait.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /?

echo /?

exit /?

if /?

start /?

Read also the Microsoft support article Testing for a Specific Error Level in Batch Files.

See also the Stack Overflow questions:

What are the ERRORLEVEL values set by internal cmd.exe commands?

Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?


问:
How to round a time down to the nearest 15 minutes in Ruby?
Is there an easy way to round a Time down to the nearest 15 minutes?

This is what I'm currently doing.  Is there an easier way to do it?

```<code>t = Time.new
rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)
</code>```

答:
I am not very familiar with the syntax of ruby but you can round down to the nearest 15 minutes using modulo. (i.e. x  - (x modulo 15)). I would guess the syntax would be something like

```<code>t.min - ( t.min % 15)
</code>```

This will make your set of possible values 0, 15, 30, and 45. Assuming 0 <= t.min <= 59.

OwnerDisplayName: Readonly

Body:
Is there an easy way to round a Time down to the nearest 15 minutes?

This is what I'm currently doing.  Is there an easier way to do it?

t = Time.new
rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)

Body:
I am not very familiar with the syntax of ruby but you can round down to the nearest 15 minutes using modulo. (i.e. x  - (x modulo 15)). I would guess the syntax would be something like

t.min - ( t.min % 15)

This will make your set of possible values 0, 15, 30, and 45. Assuming 0 <= t.min <= 59.

OwnerDisplayName: cmsjr

LastEditorDisplayName: cmsjr


问:
In Rails 3, how can I display the value of the error when using validation errors?
I want to display something like:

```<code>  validates :field, :inclusion => { :in => fields, :message => "is not allowed: {self.field}"}
</code>```

But the self is referring to the class itself rather than the instance variable.

答:
If I understood it correctly, you want something like

```<code>class Coffee < ActiveRecord::Base
  validates_inclusion_of :size, :in => %w(small medium large),
    :message => "%{value} is not a valid size"
end
</code>```

Example from the docs

Body:
I want to display something like:

  validates :field, :inclusion => { :in => fields, :message => "is not allowed: {self.field}"}

But the self is referring to the class itself rather than the instance variable.

Body:
If I understood it correctly, you want something like

class Coffee < ActiveRecord::Base
  validates_inclusion_of :size, :in => %w(small medium large),
    :message => "%{value} is not a valid size"
end

Example from the docs


问:
Import csv file using pandas and split the resulting strings
I want to read this csv file in pandas as a DataFrame. Then I would like to split the resulting strings from colons.

I import using:

```<code>df_r = pd.read_csv("report.csv", sep=";|,", engine="python")
</code>```

Then split using:

```<code>for c in df_r:
    if df_r[c].dtype == "object":
        df_r[c] = df_r[c].str.split(':')
</code>```

But I get the following error:

```<code>ValueError: could not convert string to float: '"\x001\x000\x00'
</code>```

Any idea what I am doing wrong?

Edit:

The error actually shows when I try to convert one of the strings to a float

```<code>print(float(df_r["Laptime"].iloc[0][2]))
</code>```

答:
I ran your code and everything works fine. You can try catching the error and print the row that has that strange behaviour and manual inspect that.

Is that the entire dump you are using? I saw that you are assigning the csv to the variable a and using df_r afterwards so I think you are doing something else in between.

If the csv file is complete be aware that the last line is empty and create a row full of NaNs. You want to read the csv with skipfooter=1.

```<code>a = pd.read_csv('report.csv', sep=";|,", engine="python", skipfooter=1)
</code>```

Edit:

You can convert it to float like this:

```<code>print(float(df_r["Laptime"].iloc[0][2].replace(b'\x00',b'')))
</code>```

Body:
I want to read this csv file in pandas as a DataFrame. Then I would like to split the resulting strings from colons.

I import using:

df_r = pd.read_csv("report.csv", sep=";|,", engine="python")

Then split using:

for c in df_r:
    if df_r[c].dtype == "object":
        df_r[c] = df_r[c].str.split(':')

But I get the following error:

ValueError: could not convert string to float: '"\x001\x000\x00'

Any idea what I am doing wrong?

Edit:

The error actually shows when I try to convert one of the strings to a float

print(float(df_r["Laptime"].iloc[0][2]))

Body:
I ran your code and everything works fine. You can try catching the error and print the row that has that strange behaviour and manual inspect that.

Is that the entire dump you are using? I saw that you are assigning the csv to the variable a and using df_r afterwards so I think you are doing something else in between.

If the csv file is complete be aware that the last line is empty and create a row full of NaNs. You want to read the csv with skipfooter=1.

a = pd.read_csv('report.csv', sep=";|,", engine="python", skipfooter=1)

Edit:

You can convert it to float like this:

print(float(df_r["Laptime"].iloc[0][2].replace(b'\x00',b'')))


问:
How do I modify my contourplot to display a region with an huge gradient better?
I'm working on a contourplot with matplotlib and for my data I have a region where I have a strong gradient - Now I have the problem that matplotlib will display the regions with different colors, according to the selected colormap, and distribute the colors linear over the whole spectrum.

Since 90% of my datapoints are within one end of the spectra, and only this small region acts completely differently, my contourplot looks kind of
monochrome, as you can see in the attached picture

Also, I've added some contours to make the differences in the values more visible. Since we have a huge gradient at a specific spot, there area lot of contours and it is super hard to see the underlying colors or the values.

Is there a good way how to handle such "problematic" regions with matplotlib? Maybe to define another colormap there? I've tried to set some manual levels and to "cut out" the specific region, but it would be nice to find a way to display the value of this region

Just to get a feeling: My minimal value to display is around 7, the maximum value is 145 and the average

Here is the important part of my code:

```<code>z = [] # z is a list of values that i've read in before from a file
X = np.arange(0, 61, 1)
Y = np.arange(0, 151, 1)
z = z.reshape((len(Y), len(X)))
blurred = gaussian_filter(z, sigma=2) # applies a gaussian filter to smooth the plot
xx, yy = np.meshgrid(X, Y) # gets the grid for the plot

procent = np.arange(np.min(z), np.max(z), 5) # levels for the contourlines
newlevels = [5,10,15,20,30,40,50, 80, 100, 120, 140] # sets manual levels for the plot, where I've tried to set a stronger focus on the first part of the spectra
plusmin = plt.contourf(xx,yy,z, origin='lower', extend='both', levels=procent,)
levels = np.arange(np.min(z), np.max(z), 3)

CS = plt.contourf(xx, yy, z, levels=newlevels, extend="both", cmap=cm.viridis)
s = plt.contour(xx, yy, blurred, plusmin.levels, colors='white', linewidths=2)
cbar = plt.colorbar(CS, fraction=0.042, pad=0.04)
ax.clabel(s, fontsize=12, inline=1, colors ='white')
</code>```

答:
A solution might be to scale the colormap so that each colors is equally displayed.

Here is a piece of code I use to handle this kind of problem. There is certainly more proper way to do it with matplotlib, but I do not know it.

```<code>import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
import copy

#-----------------------
def repartition(z):
    """compute the repartition function of an array"""
    hist, bin_edges = np.histogram(z.flat[:], bins = 1000)
    x = 0.5 * (bin_edges[1:] + bin_edges[:-1])
    y = np.cumsum(np.array(hist, float))
    y = (y - y[0]) / (y[-1] - y[0])
    return x, y

#-----------------------
def adjustcmap2data(Z, cmap, N = 16384):
    """scale the colormap so that all colors are equally displayed"""
    def cmap2xs(cmap):
        "convert cmap to matrix"
        sd = cmap._segmentdata
        xr = [tup[0] for tup in sd['red']]
        xg = [tup[0] for tup in sd['green']]
        xb = [tup[0] for tup in sd['blue']]
        return tuple([np.array(x) for x in xr, xg, xb])

    def xs2cmap(cmap, xr, xg, xb):
        "convert matrix to cmap"
        sd = cmap._segmentdata
        for k in 'red', 'green', 'blue':
            sd[k] = list(sd[k])
            for i in xrange(len(sd[k])): sd[k][i] = list(sd[k][i])
        for i in xrange(len(sd['red'])):   sd['red'][i]    = (xr[i], sd['red'][i][1], sd['red'][i][2])
        for i in xrange(len(sd['green'])): sd['green'][i]  = (xg[i], sd['green'][i][1], sd['green'][i][2])
        for i in xrange(len(sd['blue'])):  sd['blue'][i]   = (xb[i], sd['blue'][i][1], sd['blue'][i][2])
        for k in 'red', 'green', 'blue':
            sd[k] = tuple(sd[k])
        return colors.LinearSegmentedColormap('mycmap_%010.0f' % (np.random.randn() * 1.e10), sd, N)

    x, y = repartition(Z)
    x = (x - x[0]) / (x[-1] - x[0])
    xr, xg, xb = cmap2xs(cmap)
    xrr = np.interp(xr, xp = y, fp = x)
    xgg = np.interp(xg, xp = y, fp = x)
    xbb = np.interp(xb, xp = y, fp = x)
    for x in xrr, xgg, xbb:
        x[x < 0.] = 0.
        x[x > 1.] = 1.
        x[0], x[-1] = 0.,  1.
        x.sort()
    mycmap = xs2cmap(copy.deepcopy(cmap), xrr, xgg, xbb)
    return mycmap

#---------------------
def fake_data():
    """generate a fake dataset"""
    x = np.linspace(-1., 1., 256)
    y = np.linspace(-1., 1., 256)
    X, Y = np.meshgrid(x, y)
    Z = np.zeros_like(X)
    #create background noise
    for _ in xrange(100):
        x0 = np.random.randn()
        y0 = np.random.randn()
        Z += 0.05 * np.exp(-0.5 * (((X - x0) / 0.1) ** 2. + ((Y - y0) / 0.1) ** 2.))
    #add strong peak
    Z += np.exp(-0.5 * (((X - 0.5) / 0.3) ** 2. + ((Y - 0.5) / 0.02) ** 2.))
    return X, Y, Z

#---------------------
if __name__ == "__main__":
    X, Y, Z = fake_data()
    plt.figure()
    cmap = plt.cm.spectral
    plt.pcolormesh(X, Y, Z, cmap = cmap)
    plt.colorbar()
    plt.contour(X, Y, Z, colors = "w")
    plt.gcf().show()

    plt.figure()
    scaledcmap = adjustcmap2data(Z, cmap = cmap)
    plt.pcolormesh(X, Y, Z, cmap = scaledcmap)
    plt.colorbar()
    plt.gcf().show()

    raw_input('pause')
</code>```

which should give you the following results

1) linear colorbar

2)  scaled colorbar

Body:
I'm working on a contourplot with matplotlib and for my data I have a region where I have a strong gradient - Now I have the problem that matplotlib will display the regions with different colors, according to the selected colormap, and distribute the colors linear over the whole spectrum.

Since 90% of my datapoints are within one end of the spectra, and only this small region acts completely differently, my contourplot looks kind of
monochrome, as you can see in the attached picture

Also, I've added some contours to make the differences in the values more visible. Since we have a huge gradient at a specific spot, there area lot of contours and it is super hard to see the underlying colors or the values.

Is there a good way how to handle such "problematic" regions with matplotlib? Maybe to define another colormap there? I've tried to set some manual levels and to "cut out" the specific region, but it would be nice to find a way to display the value of this region

Just to get a feeling: My minimal value to display is around 7, the maximum value is 145 and the average

Here is the important part of my code:

z = [] # z is a list of values that i've read in before from a file
X = np.arange(0, 61, 1)
Y = np.arange(0, 151, 1)
z = z.reshape((len(Y), len(X)))
blurred = gaussian_filter(z, sigma=2) # applies a gaussian filter to smooth the plot
xx, yy = np.meshgrid(X, Y) # gets the grid for the plot

procent = np.arange(np.min(z), np.max(z), 5) # levels for the contourlines
newlevels = [5,10,15,20,30,40,50, 80, 100, 120, 140] # sets manual levels for the plot, where I've tried to set a stronger focus on the first part of the spectra
plusmin = plt.contourf(xx,yy,z, origin='lower', extend='both', levels=procent,)
levels = np.arange(np.min(z), np.max(z), 3)

CS = plt.contourf(xx, yy, z, levels=newlevels, extend="both", cmap=cm.viridis)
s = plt.contour(xx, yy, blurred, plusmin.levels, colors='white', linewidths=2)
cbar = plt.colorbar(CS, fraction=0.042, pad=0.04)
ax.clabel(s, fontsize=12, inline=1, colors ='white')

Body:
A solution might be to scale the colormap so that each colors is equally displayed.

Here is a piece of code I use to handle this kind of problem. There is certainly more proper way to do it with matplotlib, but I do not know it.

import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
import copy

#-----------------------
def repartition(z):
    """compute the repartition function of an array"""
    hist, bin_edges = np.histogram(z.flat[:], bins = 1000)
    x = 0.5 * (bin_edges[1:] + bin_edges[:-1])
    y = np.cumsum(np.array(hist, float))
    y = (y - y[0]) / (y[-1] - y[0])
    return x, y

#-----------------------
def adjustcmap2data(Z, cmap, N = 16384):
    """scale the colormap so that all colors are equally displayed"""
    def cmap2xs(cmap):
        "convert cmap to matrix"
        sd = cmap._segmentdata
        xr = [tup[0] for tup in sd['red']]
        xg = [tup[0] for tup in sd['green']]
        xb = [tup[0] for tup in sd['blue']]
        return tuple([np.array(x) for x in xr, xg, xb])

    def xs2cmap(cmap, xr, xg, xb):
        "convert matrix to cmap"
        sd = cmap._segmentdata
        for k in 'red', 'green', 'blue':
            sd[k] = list(sd[k])
            for i in xrange(len(sd[k])): sd[k][i] = list(sd[k][i])
        for i in xrange(len(sd['red'])):   sd['red'][i]    = (xr[i], sd['red'][i][1], sd['red'][i][2])
        for i in xrange(len(sd['green'])): sd['green'][i]  = (xg[i], sd['green'][i][1], sd['green'][i][2])
        for i in xrange(len(sd['blue'])):  sd['blue'][i]   = (xb[i], sd['blue'][i][1], sd['blue'][i][2])
        for k in 'red', 'green', 'blue':
            sd[k] = tuple(sd[k])
        return colors.LinearSegmentedColormap('mycmap_%010.0f' % (np.random.randn() * 1.e10), sd, N)

    x, y = repartition(Z)
    x = (x - x[0]) / (x[-1] - x[0])
    xr, xg, xb = cmap2xs(cmap)
    xrr = np.interp(xr, xp = y, fp = x)
    xgg = np.interp(xg, xp = y, fp = x)
    xbb = np.interp(xb, xp = y, fp = x)
    for x in xrr, xgg, xbb:
        x[x < 0.] = 0.
        x[x > 1.] = 1.
        x[0], x[-1] = 0.,  1.
        x.sort()
    mycmap = xs2cmap(copy.deepcopy(cmap), xrr, xgg, xbb)
    return mycmap

#---------------------
def fake_data():
    """generate a fake dataset"""
    x = np.linspace(-1., 1., 256)
    y = np.linspace(-1., 1., 256)
    X, Y = np.meshgrid(x, y)
    Z = np.zeros_like(X)
    #create background noise
    for _ in xrange(100):
        x0 = np.random.randn()
        y0 = np.random.randn()
        Z += 0.05 * np.exp(-0.5 * (((X - x0) / 0.1) ** 2. + ((Y - y0) / 0.1) ** 2.))
    #add strong peak
    Z += np.exp(-0.5 * (((X - 0.5) / 0.3) ** 2. + ((Y - 0.5) / 0.02) ** 2.))
    return X, Y, Z

#---------------------
if __name__ == "__main__":
    X, Y, Z = fake_data()
    plt.figure()
    cmap = plt.cm.spectral
    plt.pcolormesh(X, Y, Z, cmap = cmap)
    plt.colorbar()
    plt.contour(X, Y, Z, colors = "w")
    plt.gcf().show()

    plt.figure()
    scaledcmap = adjustcmap2data(Z, cmap = cmap)
    plt.pcolormesh(X, Y, Z, cmap = scaledcmap)
    plt.colorbar()
    plt.gcf().show()

    raw_input('pause')

which should give you the following results

1) linear colorbar

2)  scaled colorbar


问:
Filter Array of custom objects using NSPredicate in Objective C
I have one array which contains dictionary of custom objects.I want to filter that array for search functionality in UITableView. Here is my code for single object Filtration using NSPredicate.

```<code>self.searchResultForName = [self.multiPracticeDetailsArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    ObjectHolder *obj = (ObjectHolder*)evaluatedObject;
    return [obj.Name hasPrefix:searchText];
}]];
</code>```

Using above code, I can search only for Name , but i want to search for both By Name and ID.Also search will be case insensitive. How can i do this in Objective-C?.Please Suggest any better way to do this.

答:
You can try filtering it like this, assuming your ObjectId property is NSInteger:

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Name =[c] %@ OR ObjectId =[c] %ld", searchText, searchId];
NSArray *filteredArray = [self.multiPracticeDetailsArray filteredArrayUsingPredicate:predicate];
</code>```

Body:
I have one array which contains dictionary of custom objects.I want to filter that array for search functionality in UITableView. Here is my code for single object Filtration using NSPredicate.

self.searchResultForName = [self.multiPracticeDetailsArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    ObjectHolder *obj = (ObjectHolder*)evaluatedObject;
    return [obj.Name hasPrefix:searchText];
}]];

Using above code, I can search only for Name , but i want to search for both By Name and ID.Also search will be case insensitive. How can i do this in Objective-C?.Please Suggest any better way to do this.

Body:
You can try filtering it like this, assuming your ObjectId property is NSInteger:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Name =[c] %@ OR ObjectId =[c] %ld", searchText, searchId];
NSArray *filteredArray = [self.multiPracticeDetailsArray filteredArrayUsingPredicate:predicate];


问:
PHP MySQL insert multiple rows with different IDs
I have the following table:

```<code>id | message_id | recevier_id
 1 |      8     |    2
 2 |      9     |    5
 3 |     14     |    4
</code>```

I am sending data to a PHP file to add to the above table. My data is as follows:

messageid = "2"
receiver id = "5,6,34"

I am trying to add multiple rows with different "receiver id", so the outcome of the above query should result in :

```<code>id | message_id | recevier_id
 1 |      8     |    2
 2 |      9     |    5
 3 |     14     |    4
 4 |      2     |    5
 5 |      2     |    6
 6 |      2     |   34
</code>```

My current MySQL query looks like this:

```<code><?php
$inputvalues = $_POST;
$errors = false;
$result = false;
session_start();
include_once '../../../includes/database.php';
$uid = $_SESSION['usr_id'];
$sendername = $_SESSION['firstnames'].' '.$_SESSION['surname'];

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    foreach ($inputvalues as $key => $value) {
        if(isset($value) && !empty($value)) {
            $inputvalues[$key] = $mysqli->real_escape_string( $value );
        } else {
            $errors[$key] = 'The field '.$key.' is empty';
        }
    }

    if( !$errors ) {
        $mysqli->query("
            INSERT INTO `message_receiver_map` (`message_id`, `receiver_id`) VALUES ('".$messageid."', '".$inputvalues['receiverid']."');
        ");
        $returnResult = "Success";
    }
    mysqli_close($mysqli);
    echo json_encode(['result' => $returnResult, 'errors' => $errors]);
    exit;
?>
</code>```

How can I achieve this?

答:
Assuming 2 field in $_POST exist called

```<code>$_POST['messageid'] = "2"
$_POST['receiver id'] = "5,6,34"
</code>```

Then the creation of the 3 rows can be done like this

Remember that once a query with parameters has been prepared, it can be reused any number of times, with new parameter values each time it is executed.

```<code><?php
    session_start();
    include_once '../../../includes/database.php';

    // this if should probably be in your database.php script
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    if ( isset($_POST['messageid'],$_POST['receiver id']) ){
        // proceed to create the new rows

        //create a query
        $sql = "INSERT INTO `message_receiver_map`
                        (`message_id`, `receiver_id`)
                VALUES (?,?)";

        // prepare the query (send to server and compile it)
        // now this query can be run multiple times with different
        // parameter set each time it is executed
        $stmt = $mysqli->prepare($sql);

        // now for each receiver_id run the query
        $rec_ids = explode($_POST['receiver id']);

        foreach ($rec_ids as $rec_id) {
            // bind the 2 parameters from this iteration to the query
            $stmt->bind_value('ii',
                                $_POST['messageid'],
                                $rec_id);
            // run query with these new params
            $result = $stmt->execute();
        }
    }
}
?>
</code>```

If you are using a INNODB database you could also wrap a transaction around this so the you get all 3 rows created or none at all if an error occurs somewhere while creating the 3 new rows.

Body:
I have the following table:

id | message_id | recevier_id
 1 |      8     |    2
 2 |      9     |    5
 3 |     14     |    4

I am sending data to a PHP file to add to the above table. My data is as follows:

messageid = "2"
receiver id = "5,6,34"

I am trying to add multiple rows with different "receiver id", so the outcome of the above query should result in :

id | message_id | recevier_id
 1 |      8     |    2
 2 |      9     |    5
 3 |     14     |    4
 4 |      2     |    5
 5 |      2     |    6
 6 |      2     |   34

My current MySQL query looks like this:

<?php
$inputvalues = $_POST;
$errors = false;
$result = false;
session_start();
include_once '../../../includes/database.php';
$uid = $_SESSION['usr_id'];
$sendername = $_SESSION['firstnames'].' '.$_SESSION['surname'];

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    foreach ($inputvalues as $key => $value) {
        if(isset($value) && !empty($value)) {
            $inputvalues[$key] = $mysqli->real_escape_string( $value );
        } else {
            $errors[$key] = 'The field '.$key.' is empty';
        }
    }

    if( !$errors ) {
        $mysqli->query("
            INSERT INTO `message_receiver_map` (`message_id`, `receiver_id`) VALUES ('".$messageid."', '".$inputvalues['receiverid']."');
        ");
        $returnResult = "Success";
    }
    mysqli_close($mysqli);
    echo json_encode(['result' => $returnResult, 'errors' => $errors]);
    exit;
?>

How can I achieve this?

Body:
Assuming 2 field in $_POST exist called

$_POST['messageid'] = "2"
$_POST['receiver id'] = "5,6,34"

Then the creation of the 3 rows can be done like this

Remember that once a query with parameters has been prepared, it can be reused any number of times, with new parameter values each time it is executed.

<?php
    session_start();
    include_once '../../../includes/database.php';

    // this if should probably be in your database.php script
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    if ( isset($_POST['messageid'],$_POST['receiver id']) ){
        // proceed to create the new rows

        //create a query
        $sql = "INSERT INTO `message_receiver_map`
                        (`message_id`, `receiver_id`)
                VALUES (?,?)";

        // prepare the query (send to server and compile it)
        // now this query can be run multiple times with different
        // parameter set each time it is executed
        $stmt = $mysqli->prepare($sql);

        // now for each receiver_id run the query
        $rec_ids = explode($_POST['receiver id']);

        foreach ($rec_ids as $rec_id) {
            // bind the 2 parameters from this iteration to the query
            $stmt->bind_value('ii',
                                $_POST['messageid'],
                                $rec_id);
            // run query with these new params
            $result = $stmt->execute();
        }
    }
}
?>

If you are using a INNODB database you could also wrap a transaction around this so the you get all 3 rows created or none at all if an error occurs somewhere while creating the 3 new rows.


问:
Group by SQL query in VBA
I have a query where I would like to consolidate by a Code that has two rows in the initial tab, however I keep getting an error Cannot group on Fields selected with '*'. Any ideas

Option Explicit

Sub get_code()
   OptimizeVBA True: ShDel ("Workings")
   Dim cn As ADODB.Connection
   Set cn = New ADODB.Connection

   With cn
       .Provider = "Microsoft.ACE.OLEDB.12.0"
       .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
        "Extended Properties=""Excel 12.0 Macro;IMEX=1;HDR=YES"";"
       .Open
   End With

   Dim rs As ADODB.Recordset
   Set rs = New ADODB.Recordset

   rs.Open "SELECT * FROM [Holdings$] WHERE [Holdings$].['Code$'] ='%91' GROUP BY ['Code']", cn

   Dim fld As ADODB.Field
   Dim i As Integer

   Sheets.Add.name = "Workings"
   With ThisWorkbook.Worksheets("Workings")
      i = 0
      For Each fld In rs.Fields
         i = i + 1
         .Cells(1, i).Value = fld.name
       Next fld
       .Cells(2, 1).CopyFromRecordset rs
       .UsedRange.Columns.AutoFit
   End With

   rs.Close
   cn.Close
   OptimizeVBA False
End Sub
```

Optimize just optimizes the workbook and SHdel deletes the sheet.

答:
Cannot group on Fields selected with '*'

Pretty explicit: you can't GROUP BY when you do SELECT *. Specify the field list explicitly.

```<code>SELECT [Code$], [Foobar] FROM [Holdings$] WHERE [Holdings$].['Code$'] ='%91' GROUP BY [Code$], [Foobar]
</code>```

Note that all fields in the SELECT clause that aren't aggregates, must appear in the GROUP BY clause.

If there is no need to aggregate anything, you can remove the GROUP BY clause and do SELECT DISTINCT instead.

Title: Group by SQL query in VBA

Body:
I have a query where I would like to consolidate by a Code that has two rows in the initial tab, however I keep getting an error Cannot group on Fields selected with '*'. Any ideas

Option Explicit

Sub get_code()
   OptimizeVBA True: ShDel ("Workings")
   Dim cn As ADODB.Connection
   Set cn = New ADODB.Connection

   With cn
       .Provider = "Microsoft.ACE.OLEDB.12.0"
       .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
        "Extended Properties=""Excel 12.0 Macro;IMEX=1;HDR=YES"";"
       .Open
   End With

   Dim rs As ADODB.Recordset
   Set rs = New ADODB.Recordset

   rs.Open "SELECT * FROM [Holdings$] WHERE [Holdings$].['Code$'] ='%91' GROUP BY ['Code']", cn

   Dim fld As ADODB.Field
   Dim i As Integer

   Sheets.Add.name = "Workings"
   With ThisWorkbook.Worksheets("Workings")
      i = 0
      For Each fld In rs.Fields
         i = i + 1
         .Cells(1, i).Value = fld.name
       Next fld
       .Cells(2, 1).CopyFromRecordset rs
       .UsedRange.Columns.AutoFit
   End With

   rs.Close
   cn.Close
   OptimizeVBA False
End Sub

Optimize just optimizes the workbook and SHdel deletes the sheet.

Body:
Cannot group on Fields selected with '*'

Pretty explicit: you can't GROUP BY when you do SELECT *. Specify the field list explicitly.

SELECT [Code$], [Foobar] FROM [Holdings$] WHERE [Holdings$].['Code$'] ='%91' GROUP BY [Code$], [Foobar]

Note that all fields in the SELECT clause that aren't aggregates, must appear in the GROUP BY clause.

If there is no need to aggregate anything, you can remove the GROUP BY clause and do SELECT DISTINCT instead.


问:
PHP unexpected 'register_nav_menus'
When I try to put inside my functions.php this code:

```<code>register_nav_menus(array(
'primary' => __('Primary Menu'),
'footer' => __('Footer Menu')
));
</code>```

It gives me back the following error:

Parse error: syntax error, unexpected 'register_nav_menus' (T_STRING)

Here's the header part:

```<code><nav class="site-nav">

            <?php

                $args = array(
                    'theme_location' => 'primary'
                );
            ?>

            <?php wp_nav_menu($args); #creates the menu according to my pages section?>
        </nav>
</code>```

and Footer:

```<code><nav class="site-nav">
        <?php
            $args = array(
                'theme_location' => 'footer'
            );
        ?>

        <?php wp_nav_menu($args); ?>
</nav>
</code>```

答:
your function.php like this and you forgot add_action() semicolon
  for that error was throwing.

```<code>add_action('wp_enqueue_scripts','learningWordPress_resources')**;**

// Navigation Menus
register_nav_menus(array(
'primary' => __('Primary Menu'),
'footer' => __('footer Menu'),
));
</code>```

Title: PHP unexpected 'register_nav_menus'

Body:
When I try to put inside my functions.php this code:

register_nav_menus(array(
'primary' => __('Primary Menu'),
'footer' => __('Footer Menu')
));

It gives me back the following error:

Parse error: syntax error, unexpected 'register_nav_menus' (T_STRING)

Here's the header part:

            <?php

                $args = array(
                    'theme_location' => 'primary'
                );
            ?>

            <?php wp_nav_menu($args); #creates the menu according to my pages section?>

and Footer:

        <?php
            $args = array(
                'theme_location' => 'footer'
            );
        ?>

        <?php wp_nav_menu($args); ?>

Body:
your function.php like this and you forgot add_action() semicolon
  for that error was throwing.

add_action('wp_enqueue_scripts','learningWordPress_resources')**;**

// Navigation Menus
register_nav_menus(array(
'primary' => __('Primary Menu'),
'footer' => __('footer Menu'),
));


问:
DateLastModified (ASP) and Excel files + ASP compilation
I'm trying to get the last modified date of an Excel file.
I've been looking around and I stitched up pieces and pieces until I got to this:

```<code><%
 dim fs,f
 set fs=Server.CreateObject("Scripting.FileSystemObject")
 set f=fs.GetFile("c:\test.txt")
 Response.Write("<h3>File last modified on: ")
 Response.Write(f.DateLastModified)
 Response.Write("</h3>")
 set f=nothing
 set fs=nothing
 %>
</code>```

Now, the problems:

1) I read another question here regarding the use of the DateLastModified property with Excel files (the person had the problem that oftentimes the last modified date was before the creation date of the file), so I'm wondering: does DateLastModified return the expected results if the file is an .xlsx?

2) Is there any possibility of compiling ASP online, without having to buy or install anything? I couldn't find anything like that.

答:
if you're getting the proper date returned, then it's working! there are no "special cases" with file types in ASP,

if you're looking for a place online where you can run online asp snippets (similar to jsFiddle for javascript), I haven't come across anything. But to get it setup to run locally, all you need is IIS, as classic asp is included for free as a feature in IIS, all you need to do is switch it on.

Body:
I'm trying to get the last modified date of an Excel file.
I've been looking around and I stitched up pieces and pieces until I got to this:

<%
 dim fs,f
 set fs=Server.CreateObject("Scripting.FileSystemObject")
 set f=fs.GetFile("c:\test.txt")
 Response.Write("
File last modified on: ")
 Response.Write(f.DateLastModified)
 Response.Write("
")
 set f=nothing
 set fs=nothing
 %>

Now, the problems:

1) I read another question here regarding the use of the DateLastModified property with Excel files (the person had the problem that oftentimes the last modified date was before the creation date of the file), so I'm wondering: does DateLastModified return the expected results if the file is an .xlsx?

2) Is there any possibility of compiling ASP online, without having to buy or install anything? I couldn't find anything like that.


问:
Write a program that prints the longest substring of s in which the letters occur in alphabetical order
The code runs fine and the output seems ok. But my print is inside the for loop, this makes me doubt that the coding is correct:

```<code>s = 'azcbobobegghakl'
i = 0
increase = 0
longest = 1
for i in range(len(s) - 1):
        if s[i+1] >= s[i]:
           increase +=1
        else:
            if increase > longest:
               longest = increase
               print ("
Longest substring in alphabetical order is:"+""+s[i-longest:i+1])

            increase =0
</code>```

答:
I would write it like this:</p>

```<code>s = 'abcaakabcdeakk'
i = 0
increase = 0
longest = 1
longest_end = 1
for i in range(len(s)):
        if i < len(s)-1 and s[i+1] >= s[i]:
           increase += 1
        else:
            if increase > longest:
               longest = increase
               longest_end = i
            increase = 0
print ("Longest substring in alphabetical order is:" + s[longest_end-longest:longest_end+1])
</code>```

Body:
The code runs fine and the output seems ok. But my print is inside the for loop, this makes me doubt that the coding is correct:

s = 'azcbobobegghakl'
i = 0
increase = 0
longest = 1
for i in range(len(s) - 1):
        if s[i+1] >= s[i]:
           increase +=1
        else:
            if increase > longest:
               longest = increase
               print ("
Longest substring in alphabetical order is:"+""+s[i-longest:i+1])

            increase =0

Body:
I would write it like this:

s = 'abcaakabcdeakk'
i = 0
increase = 0
longest = 1
longest_end = 1
for i in range(len(s)):
        if i < len(s)-1 and s[i+1] >= s[i]:
           increase += 1
        else:
            if increase > longest:
               longest = increase
               longest_end = i
            increase = 0
print ("Longest substring in alphabetical order is:" + s[longest_end-longest:longest_end+1])


问:
How to change an angular2 html dynamically?
Im trying to find a way to change some html lines of a component dynamically.

```<code><li *ngFor="p in persons" [attr.id]="p.id">
   <span> {{ p.name }} </span>
   <a (click)="getAge(p.id)">Get Age<a/>
</li>
</code>```

If the user clicks on the Get Age link i would like to replace the content inside of the corresponding li tag to something like:

```<code><span> {{ p.OtherProperty }} </span>
<a (click)="OtherMethod(p)">Call OtherMethod<a/>
</code>```

I found that ComponentFactoryResolver to create dynamic components, but i found it too overwhelming for just 2 lines of html. And i tried to change it by hand using jquery but it does not work to create the event bindings:

```<code>getAge(id) {
    //some work
    //remove the corresponding <li> content
    $('#' + id).append('<a (click)="getAnotherValue(p.name)">GetAnotherValue<a/>');
    $('#' + id).append('<span> {{ p.age}} </span>'); //this obviously doesnt work. But thats the ideia.
 }
</code>```

So how can i replace some html tags with angular attributes dynamically?

答:
You could access the person's Object property dynamically like this:

```<code>object[property]; // Where property is a string
// If property equals 'name', the above sentence would equal this:
object.name; // or `object['name'];`
</code>```

So, following your example, you could do this:

```<code>export class App {
  persons = [
    {
     id: 1,
     name: 'John',
     age: 25
    },
    {
     id: 2,
     name: 'Mike',
     age: 30
    }
  ];
  selectedProperty = 'name';

  constructor() {
  }

  getProperty(prop) {
    this.selectedProperty = prop;
  }
}
</code>```

And in your template you could:

```<code><div>
  <li *ngFor="let p of persons" [attr.id]="p.id">
    <span> {{ p[selectedProperty] }} </span>
    <br>
  </li>
  <button (click)="getProperty('age')">Get Age</button>
  <button (click)="getProperty('name')">Get Name</button>
</div>
</code>```

If I understood well, this should do the trick. You can't use ngIf because if you have 60 properties or persons then will be somewhat caothic.

Check the Plunker

Body:
Im trying to find a way to change some html lines of a component dynamically.

    {{ p.name }}
   Get Age

If the user clicks on the Get Age link i would like to replace the content inside of the corresponding li tag to something like:

 {{ p.OtherProperty }}
Call OtherMethod

I found that ComponentFactoryResolver to create dynamic components, but i found it too overwhelming for just 2 lines of html. And i tried to change it by hand using jquery but it does not work to create the event bindings:

getAge(id) {
    //some work
    //remove the corresponding
 content
    $('#' + id).append('GetAnotherValue');
    $('#' + id).append(' {{ p.age}} '); //this obviously doesnt work. But thats the ideia.
 }

So how can i replace some html tags with angular attributes dynamically?

Body:
You could access the person's Object property dynamically like this:

object[property]; // Where property is a string
// If property equals 'name', the above sentence would equal this:
object.name; // or `object['name'];`

So, following your example, you could do this:

export class App {
  persons = [
    {
     id: 1,
     name: 'John',
     age: 25
    },
    {
     id: 2,
     name: 'Mike',
     age: 30
    }
  ];
  selectedProperty = 'name';

  constructor() {
  }

  getProperty(prop) {
    this.selectedProperty = prop;
  }
}

And in your template you could:

<div>
  <li *ngFor="let p of persons" [attr.id]="p.id">
    <span> {{ p[selectedProperty] }} </span>
    <br>
  </li>
  <button (click)="getProperty('age')">Get Age</button>
  <button (click)="getProperty('name')">Get Name</button>
</div>

If I understood well, this should do the trick. You can't use ngIf because if you have 60 properties or persons then will be somewhat caothic.

Check the Plunker