问:
linear search on array of object c++
i have a problem with a function ..
I want the function to have two arguments ..
one will be a array of objects and the second one will be the code given by the user
and into the function to run a linear search and check if the user's code exists and if the code exists will return his position in the array else returns -1...

this is what i have try already:

```<code>int passwdSearch(Eidos pinPro[], int pass)
{
int i=0;
bool found;
found=false;
while(i<N && found==false)
{
    if(pinPro[i].getPasswd()==pass)
    {
        found=true;
        return i;
    }
    else
        return -1;
    i++;

}
</code>```

}

i want the function return the position if password exist else return symbolic number -1

The problem is that the code return position only for the first element of array and for the 4 others element function return -1

答:
Try this code

```<code>int passwdSearch(Eidos pinPro[], int pass)
 {
   int i=0;
   bool found;
   found=false;
   while(i<N && found==false)
   {
      if(pinPro[i].getPasswd()==pass)
      {
        found=true;
        return i;
      }
     else
       i++;
   }
  return -1;
}
</code>```

Title: linear search on array of object c++

Body:
i have a problem with a function ..
I want the function to have two arguments ..
one will be a array of objects and the second one will be the code given by the user
and into the function to run a linear search and check if the user's code exists and if the code exists will return his position in the array else returns -1...

this is what i have try already:

int passwdSearch(Eidos pinPro[], int pass)
{
int i=0;
bool found;
found=false;
while(i<N && found==false)
{
    if(pinPro[i].getPasswd()==pass)
    {
        found=true;
        return i;
    }
    else
        return -1;
    i++;

}

}

i want the function return the position if password exist else return symbolic number -1

The problem is that the code return position only for the first element of array and for the 4 others element function return -1

Body:
Try this code

int passwdSearch(Eidos pinPro[], int pass)
 {
   int i=0;
   bool found;
   found=false;
   while(i<N && found==false)
   {
      if(pinPro[i].getPasswd()==pass)
      {
        found=true;
        return i;
      }
     else
       i++;
   }
  return -1;
}


来源: stackexchange

问:
How to use a variable inside IN operator
I'm trying to write an application in C# that will pass a variable that contains multiple value separated by a comma, to a stored procedure

```<code>string state = "AZ, CA, VA"
</code>```

I want my stored procedure to return all data for each state in the variable

```<code>CREATE PROCEDURE usp_GetStateInfo
@state varchar(2)

SELECT * FROM StateTable WHERE state IN (@state)
</code>```

But when I do the code above I get an error saying 'Incorrect syntax'
What am I doing wrong and how can I fix this?

Thank you

答:
The IN operator accepts an inline list of values, or a select statement. There is no native list type of variable in SQL. And certainly varchar(2) will not work, as you have it.

As you are using C#, it makes sense to loop through a list of states, calling the stored procedure for each element. The procedure would use = instead of IN to filter the states.

If you insist that the procedure accept a string of comma-separated values, then you would have to use SQL commands to split the string and insert each value into a temp table or table variable, to then have a select statement for the INto consume.

In T-SQL, you can do this with STRING_SPLIT() for SQL Server 2016
https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql

```<code>SELECT *
FROM StateTable
WHERE state IN(
    SELECT value
    FROM STRING_SPLIT(@states, ',') )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write an application in C# that will pass a variable that contains multiple value separated by a comma, to a stored procedure

string state = "AZ, CA, VA"

I want my stored procedure to return all data for each state in the variable

CREATE PROCEDURE usp_GetStateInfo
@state varchar(2)

SELECT * FROM StateTable WHERE state IN (@state)

But when I do the code above I get an error saying 'Incorrect syntax'
What am I doing wrong and how can I fix this?

Thank you

Body:
The IN operator accepts an inline list of values, or a select statement. There is no native list type of variable in SQL. And certainly varchar(2) will not work, as you have it.

As you are using C#, it makes sense to loop through a list of states, calling the stored procedure for each element. The procedure would use = instead of IN to filter the states.

If you insist that the procedure accept a string of comma-separated values, then you would have to use SQL commands to split the string and insert each value into a temp table or table variable, to then have a select statement for the INto consume.

In T-SQL, you can do this with STRING_SPLIT() for SQL Server 2016
https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql

SELECT *
FROM StateTable
WHERE state IN(
    SELECT value
    FROM STRING_SPLIT(@states, ',') )


问:
Gulp is not running successfully on my macOS
https://ahmadawais.com/my-advanced-gulp-workflow-for-wordpress-themes/

I am following this tutorials and using the gulfile.js he has offered in the tutorial, but when i am installing the

```<code>npm install
</code>```

i am getting plenty of issues, so i updated the file. but when I instantiate

```<code>glup
</code>```

in my macOS terminal its giving me following errors and declining to run the command successfully.

```<code>[Browsersync] Serving files from: ./
[Browsersync] Watching files...
[23:36:59] gulp-notify: [Gulp notification] Custom scripts task complete
[23:36:59] Finished 'scriptsJs' after 388 ms
[23:36:59] gulp-notify: [Gulp notification] Vendor scripts task complete
[23:36:59] Finished 'vendorsJs' after 405 ms
[23:36:59] Starting 'default'...
[23:36:59] Finished 'default' after 135 ms
buffer.js:161
  throw new TypeError(kFromErrorMsg);
  ^

TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
    at Function.Buffer.from (buffer.js:161:9)
    at new Buffer (buffer.js:131:17)
    at Transform.transform [as _transform] (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/index.js:152:21)
    at Transform._read (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at Transform._write (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at Transform.Writable.write (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at StreamFilter.ondata (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:612:20)
    at emitOne (events.js:115:13)
    at StreamFilter.emit (events.js:210:7)
    at addChunk (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:284:12)
    at readableAddChunk (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:271:11)
    at StreamFilter.Readable.push (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:238:10)
    at StreamFilter.Transform.push (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_transform.js:146:32)
    at StreamFilterCallback (/Users/muzammil/Desktop/Themes/Theme2/node_modules/streamfilter/src/index.js:30:15)
</code>```

答:
For anyone caught by this, I just ran into the same issue with a 4-yr old project I'm revisiting. It looks like the gulp-combine-media-queries module hasn't been updated since Node v4 (or thereabouts).

This fork of that module solved the issue for me:
https://www.npmjs.com/package/gulp-merge-media-queries

Cheers!

Body:
https://ahmadawais.com/my-advanced-gulp-workflow-for-wordpress-themes/

I am following this tutorials and using the gulfile.js he has offered in the tutorial, but when i am installing the

npm install

i am getting plenty of issues, so i updated the file. but when I instantiate

glup

in my macOS terminal its giving me following errors and declining to run the command successfully.

[Browsersync] Serving files from: ./
[Browsersync] Watching files...
[23:36:59] gulp-notify: [Gulp notification] Custom scripts task complete
[23:36:59] Finished 'scriptsJs' after 388 ms
[23:36:59] gulp-notify: [Gulp notification] Vendor scripts task complete
[23:36:59] Finished 'vendorsJs' after 405 ms
[23:36:59] Starting 'default'...
[23:36:59] Finished 'default' after 135 ms
buffer.js:161
  throw new TypeError(kFromErrorMsg);
  ^

TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
    at Function.Buffer.from (buffer.js:161:9)
    at new Buffer (buffer.js:131:17)
    at Transform.transform [as _transform] (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/index.js:152:21)
    at Transform._read (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at Transform._write (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at Transform.Writable.write (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at StreamFilter.ondata (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:612:20)
    at emitOne (events.js:115:13)
    at StreamFilter.emit (events.js:210:7)
    at addChunk (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:284:12)
    at readableAddChunk (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:271:11)
    at StreamFilter.Readable.push (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:238:10)
    at StreamFilter.Transform.push (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_transform.js:146:32)
    at StreamFilterCallback (/Users/muzammil/Desktop/Themes/Theme2/node_modules/streamfilter/src/index.js:30:15)


问:
Get values jQuery form plugin using JSON
I use jQuery plugin called AJAX form for use in my forms and use this with JSON, http://malsup.com/jquery/form/ , actually i want reload the form after get result and send values for reload the form, or get finally these values from the form when submit but the problem i don´t know how get this

The Script in the index.php :

```<code><script>
jQuery(document).ready(function() {
  jQuery('#forma_config').ajaxForm({
    dataType: 'json',
    success: configto
  });
});

function configto(datad) {
  if (datad.datoscreate=="ok") {
    alert("All saved ");
  }
}
</code>```

Form in the index.php :

```<code><form action="send.php" name="formasend" id="form_config">
  <input type="text" name="Phone" value="">
  <input type="hidden" name="idform" value="2">
  <input type="hidden" name="send" value="ok">
  <input type="submit" name="Sending" value="Send Now">
</form>
</code>```

And in send.php I recieive information for process :

```<code><?php
  print '{"datoscreate":"ok"}';
?>
</code>```

The problem it´s I need get value of idform from input hidden for example for reload the same information, and i don´t know how get it for reload right from JSON or using this plugin, if i don´t know this idform , the form don´t reload because idform it´s missing, and don´t load information right

Thank´s in advanced for the help, regards

答:
code seems to be lacking in some things.

```<code>// wrong selector #forma_config
// correct selector #form_config
</code>```

Second you need to send the data. In your code it does not look anything like that.

```<code>jQuery('#form_config').ajaxForm({
    data : jQuery('#form_config').serialize(),
    // dataType: 'json',
    // If you use this feature, it is necessary to specify header json on php.
    success: function(datad) {
       var data = jQuery.parseJSON(datad);
       // paralyzed the data.
       if(data.datoscreate == 'ok') {
          alert("All saved ");
       }
    }
});
</code>```

Finally, the use of PHP's wrong.

```<code>header('Content-Type: application/json');

$json['datoscreate'] = 'ok';

print json_encode($json, JSON_UNESCAPED_UNICODE);
</code>```

I did not try the code. I try to help if you provide feedback.

Body:
code seems to be lacking in some things.

// wrong selector #forma_config
// correct selector #form_config

Second you need to send the data. In your code it does not look anything like that.

jQuery('#form_config').ajaxForm({
    data : jQuery('#form_config').serialize(),
    // dataType: 'json',
    // If you use this feature, it is necessary to specify header json on php.
    success: function(datad) {
       var data = jQuery.parseJSON(datad);
       // paralyzed the data.
       if(data.datoscreate == 'ok') {
          alert("All saved ");
       }
    }
});

Finally, the use of PHP's wrong.

header('Content-Type: application/json');

$json['datoscreate'] = 'ok';

print json_encode($json, JSON_UNESCAPED_UNICODE);

I did not try the code. I try to help if you provide feedback.


问:
Powerful algorithms too complex to implement
What are some algorithms of legitimate utility that are simply too complex to implement?

Let me be clear: I'm not looking for algorithms like the current asymptotic optimal matrix multiplication algorithm, which is reasonable to implement but has a constant that makes it useless in practice. I'm looking for algorithms that could plausibly have practical value, but are so difficult to code that they have never been implemented, only implemented in extremely artificial settings, or only implemented for remarkably special-purpose applications.

Also welcome are near-impossible-to-implement algorithms that have good asymptotics but would likely have poor real performance.

答:
The Piano Mover's Problem of moving a robot through an environment with obstacles can be defined mathematically and solved with algorithms with known asymptotic complexity.

It is amazing that such algorithms exist; however, it is also unfortunate that they are both extremely challenging to implement and not efficient enough for most applications.

While every new thesis on robot motion planning has to mention Canny's Roadmap Algorithm, it is doubtful if it has ever been implemented:

no general implementation of Canny's algorithm appears to exist at present.

ContentLicense: CC BY-SA 2.5


问:
How to force Mobile Vision for Android to read full lines of text
I have implemented Google's Mobile Vision for Android by following a tutorial. I am trying to build an app that will scan a receipt and find the numeric total. However, as I scan different receipts that are printed in different formats, the API will detect TextBlocks in what seems to be an arbitrary way. For example, in one receipt, if several words of text are separated by single spaces, then they are grouped into a single TextBlock. However, if two words of text are separated by lots of spaces, then they are separated as independent TextBlocks, even though they appear on the same "line". What I am trying to do is force the API to recognize each entire line of the receipt as a single entity. Is this possible?</p>

答:
```<code>public ArrayList<T> getAllGraphicsInRow(float rawY) {
    synchronized (mLock) {
        ArrayList<T> row = new ArrayList<>();
        // Get the position of this View so the raw location can be offset relative to the view.
        int[] location = new int[2];
        this.getLocationOnScreen(location);
        for (T graphic : mGraphics) {
            float rawX = this.getWidth();
            for (int i=0; i<rawX; i+=10){
                if (graphic.contains(i - location[0], rawY - location[1])) {
                    if(!row.contains(graphic)) {
                        row.add(graphic);
                    }
                }
            }
        }
        return row;
    }
}
</code>```

This should be in the GraphicOverlay.java file and essentially fetches all the graphics in that row.

```<code>public static boolean almostEqual(double a, double b, double eps){
    return Math.abs(a-b)<(eps);
}

public static boolean pointAlmostEqual(Point a, Point b){
    return almostEqual(a.y,b.y,10);
}
public static boolean cornerPointAlmostEqual(Point[] rect1, Point[] rect2){
    boolean almostEqual=true;
    for (int i=0; i<rect1.length;i++){
            if (!pointAlmostEqual(rect1[i],rect2[i])){
                almostEqual=false;
            }
        }
    return almostEqual;
}
private boolean onTap(float rawX, float rawY) {
    String priceRegex = "(\\d+[,.]\\d\\d)";
    ArrayList<OcrGraphic> graphics = mGraphicOverlay.getAllGraphicsInRow(rawY);
    OcrGraphic currentGraphics = mGraphicOverlay.getGraphicAtLocation(rawX,rawY);
    if (graphics !=null && currentGraphics!=null) {
        List<? extends Text> currentComponents = currentGraphics.getTextBlock().getComponents();
        final Pattern pattern = Pattern.compile(priceRegex);
        final Pattern pattern1 = Pattern.compile(priceRegex);

        TextBlock text = null;
        Log.i("text results", "This many in the row: " + Integer.toString(graphics.size()));

        ArrayList<Text> combinedComponents = new ArrayList<>();
        for (OcrGraphic graphic : graphics) {
            if (!graphic.equals(currentGraphics)) {
                text = graphic.getTextBlock();
                Log.i("text results", text.getValue());
                combinedComponents.addAll(text.getComponents());
            }
        }

        for (Text currentText : currentComponents) { // goes through components in the row
            final Matcher matcher = pattern.matcher(currentText.getValue()); // looks for
            Point[] currentPoint = currentText.getCornerPoints();

            for (Text otherCurrentText : combinedComponents) {//Looks for other components that are in the same row
                final Matcher otherMatcher = pattern1.matcher(otherCurrentText.getValue()); // looks for
                Point[] innerCurrentPoint = otherCurrentText.getCornerPoints();

                if (cornerPointAlmostEqual(currentPoint, innerCurrentPoint)) {
                    if (matcher.find()) { // if you click on the price
                        Log.i("oh yes", "Item: " + otherCurrentText.getValue());
                        Log.i("oh yes", "Value: " + matcher.group(1));
                        itemList.add(otherCurrentText.getValue());
                        priceList.add(Float.valueOf(matcher.group(1)));
                    }
                    if (otherMatcher.find()) { // if you click on the item
                        Log.i("oh yes", "Item: " + currentText.getValue());
                        Log.i("oh yes", "Value: " + otherMatcher.group(1));
                        itemList.add(currentText.getValue());
                        priceList.add(Float.valueOf(otherMatcher.group(1)));
                    }
                    Toast toast = Toast.makeText(this,  " Text Captured!" , Toast.LENGTH_SHORT);
                    toast.show();
                }
            }

        }
        return true;
    }
    return false;
}
</code>```

This should be in OcrCaptureActivity.java and it breaks up the TextBlock into lines and finds the blocks in the same row as the line and checks if the components are all prices, and prints all value accordingly.

The eps value in almostEqual is the tolerance for how tall it checks for graphics in the row.

Body:
public ArrayList<T> getAllGraphicsInRow(float rawY) {
    synchronized (mLock) {
        ArrayList<T> row = new ArrayList<>();
        // Get the position of this View so the raw location can be offset relative to the view.
        int[] location = new int[2];
        this.getLocationOnScreen(location);
        for (T graphic : mGraphics) {
            float rawX = this.getWidth();
            for (int i=0; i<rawX; i+=10){
                if (graphic.contains(i - location[0], rawY - location[1])) {
                    if(!row.contains(graphic)) {
                        row.add(graphic);
                    }
                }
            }
        }
        return row;
    }
}

This should be in the GraphicOverlay.java file and essentially fetches all the graphics in that row.

public static boolean almostEqual(double a, double b, double eps){
    return Math.abs(a-b)<(eps);
}

public static boolean pointAlmostEqual(Point a, Point b){
    return almostEqual(a.y,b.y,10);
}
public static boolean cornerPointAlmostEqual(Point[] rect1, Point[] rect2){
    boolean almostEqual=true;
    for (int i=0; i<rect1.length;i++){
            if (!pointAlmostEqual(rect1[i],rect2[i])){
                almostEqual=false;
            }
        }
    return almostEqual;
}
private boolean onTap(float rawX, float rawY) {
    String priceRegex = "(\\d+[,.]\\d\\d)";
    ArrayList<OcrGraphic> graphics = mGraphicOverlay.getAllGraphicsInRow(rawY);
    OcrGraphic currentGraphics = mGraphicOverlay.getGraphicAtLocation(rawX,rawY);
    if (graphics !=null && currentGraphics!=null) {
        List<? extends Text> currentComponents = currentGraphics.getTextBlock().getComponents();
        final Pattern pattern = Pattern.compile(priceRegex);
        final Pattern pattern1 = Pattern.compile(priceRegex);

        TextBlock text = null;
        Log.i("text results", "This many in the row: " + Integer.toString(graphics.size()));

        ArrayList<Text> combinedComponents = new ArrayList<>();
        for (OcrGraphic graphic : graphics) {
            if (!graphic.equals(currentGraphics)) {
                text = graphic.getTextBlock();
                Log.i("text results", text.getValue());
                combinedComponents.addAll(text.getComponents());
            }
        }

        for (Text currentText : currentComponents) { // goes through components in the row
            final Matcher matcher = pattern.matcher(currentText.getValue()); // looks for
            Point[] currentPoint = currentText.getCornerPoints();

            for (Text otherCurrentText : combinedComponents) {//Looks for other components that are in the same row
                final Matcher otherMatcher = pattern1.matcher(otherCurrentText.getValue()); // looks for
                Point[] innerCurrentPoint = otherCurrentText.getCornerPoints();

                if (cornerPointAlmostEqual(currentPoint, innerCurrentPoint)) {
                    if (matcher.find()) { // if you click on the price
                        Log.i("oh yes", "Item: " + otherCurrentText.getValue());
                        Log.i("oh yes", "Value: " + matcher.group(1));
                        itemList.add(otherCurrentText.getValue());
                        priceList.add(Float.valueOf(matcher.group(1)));
                    }
                    if (otherMatcher.find()) { // if you click on the item
                        Log.i("oh yes", "Item: " + currentText.getValue());
                        Log.i("oh yes", "Value: " + otherMatcher.group(1));
                        itemList.add(currentText.getValue());
                        priceList.add(Float.valueOf(otherMatcher.group(1)));
                    }
                    Toast toast = Toast.makeText(this,  " Text Captured!" , Toast.LENGTH_SHORT);
                    toast.show();
                }
            }

        }
        return true;
    }
    return false;
}

This should be in OcrCaptureActivity.java and it breaks up the TextBlock into lines and finds the blocks in the same row as the line and checks if the components are all prices, and prints all value accordingly.

The eps value in almostEqual is the tolerance for how tall it checks for graphics in the row.


问:
CSS Grab All Class Name Except For Last
I want to grab all the class name ('my-class') and change it's color to red EXCEPT for the last one

Apparently I've been googling and there's no such thing as :last-of-class or whatever. I'm having trouble trying to find a work around without using JS.

div1 and div2 are both dynamic! If div2 doesn't exist, then div1 should have the first p element red and the second not.

Please note I left a 'p' tag at the top because I don't want that being part of my selector. I just need the 'my-class' specifically.

or is there a selector I can write to grab all "p"s inside of my-container which include nested P's

```<code><p>Some text</p>
<div class="my-container">
  <div class="div1">
    <p class="my-class"></p>
    <p class="my-class"></p>
  </div>
  <div class="div2">
    <p class="my-class"></p>
    <p class="my-class"></p>
    <p class="my-class"></p>
    <p class="my-class"></p>   <!-- This tag should not be red-->
  </div>
</div>
</code>```

I can also use sass so feel free to include that in if need be.

答:
I don't know of any SINGLE rule that would do this, but a simple workaround would be to use 2 separate rules in conjunction:

```<code>.my-class {
  color: red;
}

.div-2 .my-class:last-child {
  color: // whatever you want the default to be
}
</code>```

note that the order is important, setting the last child's color should be done after setting everything first

Title: CSS Grab All Class Name Except For Last

Body:
I want to grab all the class name ('my-class') and change it's color to red EXCEPT for the last one

Apparently I've been googling and there's no such thing as :last-of-class or whatever. I'm having trouble trying to find a work around without using JS.

div1 and div2 are both dynamic! If div2 doesn't exist, then div1 should have the first p element red and the second not.

Please note I left a 'p' tag at the top because I don't want that being part of my selector. I just need the 'my-class' specifically.

or is there a selector I can write to grab all "p"s inside of my-container which include nested P's

Some text

I can also use sass so feel free to include that in if need be.

Body:
I don't know of any SINGLE rule that would do this, but a simple workaround would be to use 2 separate rules in conjunction:

.my-class {
  color: red;
}

.div-2 .my-class:last-child {
  color: // whatever you want the default to be
}

note that the order is important, setting the last child's color should be done after setting everything first


问:
How to calculate the transition between a transient and a steady state for a MG1 queue simulation?
I need some help to give an output for the queue simulator I'm building.
Everything is ready, but I can't find a numerical method to discover in which piece of data the transient state ends and the steady state begins from data generated by the simulator.

I've already tried to calculate the variance of T1+T2 through the time and to calculate least-square approximation for the data function. Neither of them seems to be working well.

I have 2 queues FCFS and 1 server. All clients enter the first queue, and after being fully served they enter the second queue. First queue has higher priority than second. The info I get from the process is: T1 and T2 (time on queue + server for each queue), N1 and N2 (Number of clients in each queue).

Are there well-documented methods to do that?
Thanks!

答: This is known as the initial transient problem, and was first identified by Conway back in 1963.  You can get very thorough discussions of a variety of options in any modern simulation text book—search Google, Amazon, or Barnes & Noble for "discrete event simulation" and you'll get lots of hits.  Alternatively, this paper gives a reasonable overview of the variety of methods that have been proposed in the intervening half-century.  I recommend the MSER estimator by Pres White, which combines simplicity with analytical rigor.</p>


问:
How to place an element on top of other
I want to place an element on top of other without modifying the position of the second. I mean:

.container {
 display: flex;
 align-content: baseline;
 padding: 50px;
 width: 50px;
 height: 50px;
 background-color: blue;
}

.base {
  color: black;
}

.top {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="base">
    base
    <div class="top">
      should be on top
    </div>
  </div>
</div></code>```

I want the should be on top div to be placed above the base div, and the base div to still be aligned the way it does. I have tried using relative positioning and giving negative bottom values but it isn't that responsive. This is how i want them to be, except for base should keep the previous position:

    .container {
     display: flex;
     align-content: baseline;
     padding: 50px;
     width: 50px;
     height: 50px;
     background-color: blue;
    }

    .base {
      color: black;
    }

    .top {
      color: red;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="top">
    should be on top
    <div class="base">
      base
    </div>
  </div>
</div></code>```

should be ontop div have to be on top of base, and base where it was before. How can I do this?

This is what I was trying:

    .container {
     display: flex;
     align-content: baseline;
     padding: 50px;
     width: 50px;
     height: 50px;
     background-color: blue;
    }

    .base {
      color: black;
    }

    .top {
      position: relative;
      color: red;
      bottom: 4.8em;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="container">
      <div class="base">
        base
        <div class="top">
          should be on top
        </div>
      </div>
    </div></code>```

That's how I want them to be placed. But if the # of lines of should be ontop div changes then it overflow above of the base div. I think it could be done using js, but I prefer it was only with css. Is there a way to do this?

答:
Looks like I misunderstood the question. I've updated the answer to reflect those changes.

The parent div must have a position of relative and the inside div a position of absolute. So the above div becomes "absolute" relative to base div.

Now you need to specify how much "above" you need the div to be, because there is no other way to remove an element from the flow and position it elsewhere. (unless you're using javascript)

Here's how your code may look like:

.container {
 display: flex;
 align-content: baseline;
 padding: 50px;
 width: 50px;
 height: 50px;
 background-color: blue;
}

.base {
  position: relative;
  color: black;
}

.above {
  position: absolute;
  top: -60px;
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="base">
    base
    <div class="above">
      should be above
    </div>
  </div>
</div></code>```

Title: How to place an element on top of other

Body:
I want to place an element on top of other without modifying the position of the second. I mean:

.container {
 display: flex;
 align-content: baseline;
 padding: 50px;
 width: 50px;
 height: 50px;
 background-color: blue;
}

.base {
  color: black;
}

.top {
  color: red;
}

    base

      should be on top

I want the should be on top div to be placed above the base div, and the base div to still be aligned the way it does. I have tried using relative positioning and giving negative bottom values but it isn't that responsive. This is how i want them to be, except for base should keep the previous position:

    .container {
     display: flex;
     align-content: baseline;
     padding: 50px;
     width: 50px;
     height: 50px;
     background-color: blue;
    }

    .base {
      color: black;
    }

    .top {
      color: red;
    }

    should be on top

      base

should be ontop div have to be on top of base, and base where it was before. How can I do this?

This is what I was trying:

    .container {
     display: flex;
     align-content: baseline;
     padding: 50px;
     width: 50px;
     height: 50px;
     background-color: blue;
    }

    .base {
      color: black;
    }

    .top {
      position: relative;
      color: red;
      bottom: 4.8em;
    }

        base

          should be on top

That's how I want them to be placed. But if the # of lines of should be ontop div changes then it overflow above of the base div. I think it could be done using js, but I prefer it was only with css. Is there a way to do this?

Body:
Looks like I misunderstood the question. I've updated the answer to reflect those changes.

The parent div must have a position of relative and the inside div a position of absolute. So the above div becomes "absolute" relative to base div.

Now you need to specify how much "above" you need the div to be, because there is no other way to remove an element from the flow and position it elsewhere. (unless you're using javascript)

Here's how your code may look like:

.container {
 display: flex;
 align-content: baseline;
 padding: 50px;
 width: 50px;
 height: 50px;
 background-color: blue;
}

.base {
  position: relative;
  color: black;
}

.above {
  position: absolute;
  top: -60px;
  color: red;
}

<div class="container">
  <div class="base">
    base
    <div class="above">
      should be above
    </div>
  </div>
</div>


问:
Update progressbar from worker thread
I'm building a java program that downloads N elements from a server. I'd like to have a working progress bar, that shows "already downloaded elements"/N percentage. Right now, I update progressbar value by passing to the thread a reference to the GUI object, but it makes the code "ugly" ( GUI class creates the thread, that contains a reference to the GUI itself, creating a sort of loop).
Is there a better way to do it?</p>

答: SwingWorker has some advantages in this context, as suggested in this example.

Title: Update progressbar from worker thread


问:
linq lambda multiple group joins
I am trying to get a list of product along with its rating, comments and views. PID is product ID column without foreign key relationship.

Product -

```<code>Id  Name
1   P1
2   P2
</code>```

Rating -

```<code>Id  PID Rating
1   1   5
2   1   4
3   2   3
</code>```

Comments -

```<code>Id  PID Comment
1   1   Good
2   1   Average
3   2   Bad
</code>```

Views -

```<code>Id  PID View
1   1   500
2   1   200
3   2   10
</code>```

My class would look like this –

```<code>Public Class Product{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Rating> Ratings{ get; set; }
    public List<Comments> Comments{ get; set; }
    public List<Views> Views{ get; set; }
}
</code>```

I am trying to get this information using Linq group join, so that I get child collection.

```<code>IEnumerable<Product> _products = _context.Product.GroupJoin(_context.Rating, p=>p.id, r=>r.PID, (Product, Rating) => new Product(){
    //fill fields here
});
</code>```

But how to group other tables as well into single database query.

Thanks

答:
You can try like this;</p>

```<code>        var records = _context.Product
            .GroupJoin(_context.Ratings, p => p.Id, r => r.PID, (p, r) => new { Product = p, Ratings = r})
            .GroupJoin(_context.Comments, p => p.Product.Id, c => c.PID, (p, c) => new { p.Product, p.Ratings, Comments = c})
            .GroupJoin(_context.Views, p => p.Product.Id, v => v.PID, (p, v) => new { p.Product, p.Ratings, p.Comments, Views = v })
            .Select(p => new
            {
                Id = p.Product.Id,
                Name = p.Product.Name,
                Comments = p.Comments,
                Ratings = p.Ratings,
                Views = p.Views
            })
            .ToList().Select(x => new Product
            {
                Id = x.Id,
                Name = x.Name,
                Comments = x.Comments.ToList(),
                Ratings = x.Ratings.ToList(),
                Views = x.Views.ToList()
            }).ToList();
</code>```

Title: linq lambda multiple group joins

Body:
I am trying to get a list of product along with its rating, comments and views. PID is product ID column without foreign key relationship.

Product -

Id  Name
1   P1
2   P2

Rating -

Id  PID Rating
1   1   5
2   1   4
3   2   3

Comments -

Id  PID Comment
1   1   Good
2   1   Average
3   2   Bad

Views -

Id  PID View
1   1   500
2   1   200
3   2   10

My class would look like this –

Public Class Product{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Rating> Ratings{ get; set; }
    public List<Comments> Comments{ get; set; }
    public List<Views> Views{ get; set; }
}

I am trying to get this information using Linq group join, so that I get child collection.

IEnumerable<Product> _products = _context.Product.GroupJoin(_context.Rating, p=>p.id, r=>r.PID, (Product, Rating) => new Product(){
    //fill fields here
});

But how to group other tables as well into single database query.

Thanks

Body:
You can try like this;

        var records = _context.Product
            .GroupJoin(_context.Ratings, p => p.Id, r => r.PID, (p, r) => new { Product = p, Ratings = r})
            .GroupJoin(_context.Comments, p => p.Product.Id, c => c.PID, (p, c) => new { p.Product, p.Ratings, Comments = c})
            .GroupJoin(_context.Views, p => p.Product.Id, v => v.PID, (p, v) => new { p.Product, p.Ratings, p.Comments, Views = v })
            .Select(p => new
            {
                Id = p.Product.Id,
                Name = p.Product.Name,
                Comments = p.Comments,
                Ratings = p.Ratings,
                Views = p.Views
            })
            .ToList().Select(x => new Product
            {
                Id = x.Id,
                Name = x.Name,
                Comments = x.Comments.ToList(),
                Ratings = x.Ratings.ToList(),
                Views = x.Views.ToList()
            }).ToList();


问:
Java int argument not negative
I'm writting a method in Java with 3 argumens, the last one (int step) cannot be 0 or negative. At the moment I have it like this:

```<code>public static int[] createMonotoneIncreasingArray(int start, int end, int step) {
    if (step <= 0) throw new IllegalArgumentException("Step cannot be lower than 1 in a monotone increasing array");

    int[] resultArray = new int[(end - start) / step];

    for (int i = 0; i < resultArray.length; i++) resultArray[i] = i * step + start;

    return resultArray;
}
</code>```

Is there any more elegant way to reject a non positive int in a method and avoid the exception?

答:
Yes there is a way. Instead of passing in an int you can pass in a instance of a class. In this case you could create a class called Step. You would still have to check the correctness of values that step has in Steps constructor. But after doing that you can know that if you have an instance of a Step that its value is greater than 0;

```<code>public class Step {

   private int value;

   public Step(int value) {
      if (value <= 0) throw new IllegalArgumentException("Step cannot be lower than 1");
      this.value = value;
   }

   public int getValue() { return value; }
}

public static int[] createMonotoneIncreasingArray(int start, int end, Step step) {
    int[] resultArray = new int[(end - start) / step.getValue()];
    for (int i = 0; i < resultArray.length; i++) resultArray[i] = i * step.getValue() + start;
    return resultArray;
}
</code>```

This is a fairly common pattern for restricting value of an int. See this question for another example of this pattern Setting a limit to an int value

Title: Java int argument not negative

Body:
I'm writting a method in Java with 3 argumens, the last one (int step) cannot be 0 or negative. At the moment I have it like this:

public static int[] createMonotoneIncreasingArray(int start, int end, int step) {
    if (step <= 0) throw new IllegalArgumentException("Step cannot be lower than 1 in a monotone increasing array");

    int[] resultArray = new int[(end - start) / step];

    for (int i = 0; i < resultArray.length; i++) resultArray[i] = i * step + start;

    return resultArray;
}

Is there any more elegant way to reject a non positive int in a method and avoid the exception?

Body:
Yes there is a way. Instead of passing in an int you can pass in a instance of a class. In this case you could create a class called Step. You would still have to check the correctness of values that step has in Steps constructor. But after doing that you can know that if you have an instance of a Step that its value is greater than 0;

public class Step {

   private int value;

   public Step(int value) {
      if (value <= 0) throw new IllegalArgumentException("Step cannot be lower than 1");
      this.value = value;
   }

   public int getValue() { return value; }
}

public static int[] createMonotoneIncreasingArray(int start, int end, Step step) {
    int[] resultArray = new int[(end - start) / step.getValue()];
    for (int i = 0; i < resultArray.length; i++) resultArray[i] = i * step.getValue() + start;
    return resultArray;
}

This is a fairly common pattern for restricting value of an int. See this question for another example of this pattern Setting a limit to an int value


问:
OSX Installing Rsymphony - linking headers and libs
symphony is correctly installed and tested in terminal. R complains about missing header and libraries when trying to install Rsymphony from source. Any pointers are HIGHLY appreciated. thank you!

symphony installation directory: /Users/timo/Applications/symphony/

R install command:

install.packages("Rsymphony", configure.args="--with-SYMPHONY-include=/Users/timo/Applications/symphony/include/ --with-SYMPHONY-lib=/Users/timo/Applications/symphony/lib",type="source")

results in :

* installing *source* package ‘Rsymphony’
** package ‘Rsymphony’ successfully unpacked and MD5 sums checked
Cannot find SYMPHONY libraries and headers.
See <https://projects.coin-or.org/SYMPHONY>.ERROR: configuration failed for package ‘Rsymphony’* removing ‘/Library/Frameworks/R.framework/Versions/3.2/Resources/library/Rsymphony’* restoring previous‘/Library/Frameworks/R.framework/Versions/3.2/Resources/library/Rsymphony’

答:
SOLUTION:

I have found the solution in this link (...I got RSymphony to install, but it involved some hacking ...)
Installing RSymphony using RStudio on macOS

I had also this issue: ..no checking for COIN-OR package CoinUtils... and it was solved by "export PKG_CONFIG=/usr/local/bin/pkg-config; export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig/"


问:
Why is generic required when all types are already defined?
The exercise was to write my own map() function over Collection (without using any functional primitives, such as reduce()). It should handle a case such as this:

```<code>func square(_ input: Int) -> Int {
            return input * input
        }
let result = input.accumulate(square) // [1,2,3] =>  [1,4,9]
</code>```

My first attempt was:

```<code>extension Collection {
    func accumulate(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}
</code>```

This works fine in a playground, but fails to build against the tests, giving an error:

```<code>Value of type '[Int]' has no member 'accumulate'
</code>```

The solution is to genericize the accumulate method:

```<code>extension Collection {
    func accumulate<T>(_ transform: (Element) -> T) -> [T] {

        var array: [T] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}
</code>```

I recognize that the generic version is less restrictive (doesn't require the transform to return same type), but given that the tests don't require this generality, why does the compiler?

Out of curiousity I tried:

```<code>extension Collection {
    func accumulate<Element>(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}
</code>```

which throws the fascinating build error: '(Self.Element) -> Element' is not convertible to '(Element) -> Element' at the append() statement.

So the compiler (of course) knows that the first Element is Self.Element, but doesn't treat the other Element type as the same. Why?

UPDATE:

Based on the answers, it appears that the rejection of the first version was a compiler bug, fixed in XCode 9.2 (I'm on 9.1).

But still I wondered whether in

```<code>func accumulate(_ transform: (Element) -> Element) -> [Element]
</code>```

it would see two types (Self.Element and Element) or recognize that they're the same.

So I did this test:

```<code>let arr = [1,2,3]
arr.accumulate {
    return String(describing: $0)
}
</code>```

Sure enough, got the expected error: error: cannot convert value of type 'String' to closure result type 'Int'

So the correct answer is: the compiler will treat references to Element as the same, as long as there isn't a generic type that overloads the name.

Oddly, though, this succeeds:

```<code>[1,2,3].accumulate {
    return String(describing: $0)
}
</code>```

PS. Thanks to everyone for your input! The bounty was auto-awarded.

答:
I'm not so sure about your first question. If it works in the playground, but not in your tests, my first guess would be to make the function public. Tests are usually defined in separate modules, and to make something visible in another module, it should be declared public.</p>

```<code>extension Collection {
  public func accumulate //...
}
</code>```

Body:
The exercise was to write my own map() function over Collection (without using any functional primitives, such as reduce()). It should handle a case such as this:

func square(_ input: Int) -> Int {
            return input * input
        }
let result = input.accumulate(square) // [1,2,3] =>  [1,4,9]

My first attempt was:

extension Collection {
    func accumulate(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}

This works fine in a playground, but fails to build against the tests, giving an error:

Value of type '[Int]' has no member 'accumulate'

The solution is to genericize the accumulate method:

extension Collection {
    func accumulate<T>(_ transform: (Element) -> T) -> [T] {

        var array: [T] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}

I recognize that the generic version is less restrictive (doesn't require the transform to return same type), but given that the tests don't require this generality, why does the compiler?

Out of curiousity I tried:

extension Collection {
    func accumulate<Element>(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}

which throws the fascinating build error: '(Self.Element) -> Element' is not convertible to '(Element) -> Element' at the append() statement.

So the compiler (of course) knows that the first Element is Self.Element, but doesn't treat the other Element type as the same. Why?

UPDATE:

Based on the answers, it appears that the rejection of the first version was a compiler bug, fixed in XCode 9.2 (I'm on 9.1).

But still I wondered whether in

func accumulate(_ transform: (Element) -> Element) -> [Element]

it would see two types (Self.Element and Element) or recognize that they're the same.

So I did this test:

let arr = [1,2,3]
arr.accumulate {
    return String(describing: $0)
}

Sure enough, got the expected error: error: cannot convert value of type 'String' to closure result type 'Int'

So the correct answer is: the compiler will treat references to Element as the same, as long as there isn't a generic type that overloads the name.

Oddly, though, this succeeds:

[1,2,3].accumulate {
    return String(describing: $0)
}

PS. Thanks to everyone for your input! The bounty was auto-awarded.

Body:
I'm not so sure about your first question. If it works in the playground, but not in your tests, my first guess would be to make the function public. Tests are usually defined in separate modules, and to make something visible in another module, it should be declared public.

extension Collection {
  public func accumulate //...
}


问:
Is using regex for a request handler in PHP bad?
I am working on a request handler to route every page call through my index page and have SEO friendly urls.

domain.com/account/settings

this would be easy to map to the correct page but some are more complex when there becomes an ID number or a page number in the uri.

So I see some people will use things like preg_match and cycle through an array of patterns ->  uri to get a match which is nice for when paging and id's come into play but from my experience, it seems like running preg_match on an array of say 20 items on every page load is not good for performace.

Please tell me your thought on this?

答:
Here's the thing you should be looking at:  What's the better alternative, not that this one seems bad.  If you have an alternative that seems better, they use it.  If not, use the regex solution until you know you need to speed it up (I'll leave out my usual rant about premature optimization).

I would use the regex handlers personally.  They are more flexible, easier, and easier to maintain than some other alternatives to this problem.  But YMMV...


问:
Do not reset variable in class after refresh
It is possible to keep a variable after a refresh?
Sessions don't work, because it's on the server side.

I mean, I have a class with an array var.
I would like to add a string to the array in another php site (includes "CLASS"), but when I refresh the site, the array is empty.

答:
Everything is run through again, so it gets lost.

Perhaps you want to store it in $_SESSION? Sessions work on the server side.

You could also write data to a file and read it every time.


问:
Excel VBA - Copy table data from website and put into excel?
I am trying to copy a table from a website and put this into excel.
My table can be identified by the elementID "VisibleReportContentctl32".

For some reason, my code produces this error:
'object required'

on this line: Range("A1").Text = dat

Here's my full code:

```<code>Option Explicit
Public Sub GetSSRSData()

    Dim IE            As Object: Set IE = New InternetExplorerMedium
    Dim TR_Elements   As Object
    Dim TR            As Object ' Table Row
    Dim TD_Elements   As Object
    Dim TD            As Object ' Table Data
    Dim RowNumb       As Integer
    Dim Columns       As Integer
    Dim ColumnNumb    As Integer
    Dim x As Integer
    Dim dat As String

    With IE
        .Visible = True
        .Navigate ("http://gbrlon02-sql-17/Reports/Pages/Report.aspx?ItemPath=%2fCutlass+Reports%2fManagement+Reporting%2fForwardOrdersSticksOnly+-+ForecastVariance+(Monthly+Report)")

         Do While IE.Busy Or IE.ReadyState <> 4
             DoEvents
         Loop

         If IsObject(.Document.getElementById("VisibleReportContentctl32_ctl09")) Then
            dat = IE.Document.getElementById("VisibleReportContentctl32_ctl09").innerHTML
            Range("A1").Text = dat
         Else
            MsgBox "doesn't"
         End If
   End With
End Sub
</code>```

please can someone show me where I am going wrong?

答:
That URL doesn't work for me.  Your code should look something like this...

```<code>Option Explicit
Sub gethtmltable()
    Dim objWeb As QueryTable
    Dim sWebTable As String
     'You have to count down the tables on the URL listed in your query
     'This example shows how to retrieve the 2nd table from the web page.
    sWebTable = 2
     'Sets the url to run the query and the destination in the excel file
     'You can change both to suit your needs
    Set objWeb = ActiveSheet.QueryTables.Add( _
    Connection:="URL;http://www.vbaexpress.com/kb/default.php", _
    Destination:=Range("A1"))

    With objWeb

        .WebSelectionType = xlSpecifiedTables
        .WebTables = sWebTable
        .Refresh BackgroundQuery:=False
        .SaveData = True
    End With
    Set objWeb = Nothing
End Sub
</code>```

You just need to identify which specific table you want to import data from.

Body:
I am trying to copy a table from a website and put this into excel.
My table can be identified by the elementID "VisibleReportContentctl32".

For some reason, my code produces this error:
'object required'

on this line: Range("A1").Text = dat

Here's my full code:

Option Explicit
Public Sub GetSSRSData()

    Dim IE            As Object: Set IE = New InternetExplorerMedium
    Dim TR_Elements   As Object
    Dim TR            As Object ' Table Row
    Dim TD_Elements   As Object
    Dim TD            As Object ' Table Data
    Dim RowNumb       As Integer
    Dim Columns       As Integer
    Dim ColumnNumb    As Integer
    Dim x As Integer
    Dim dat As String

    With IE
        .Visible = True
        .Navigate ("http://gbrlon02-sql-17/Reports/Pages/Report.aspx?ItemPath=%2fCutlass+Reports%2fManagement+Reporting%2fForwardOrdersSticksOnly+-+ForecastVariance+(Monthly+Report)")

         Do While IE.Busy Or IE.ReadyState <> 4
             DoEvents
         Loop

         If IsObject(.Document.getElementById("VisibleReportContentctl32_ctl09")) Then
            dat = IE.Document.getElementById("VisibleReportContentctl32_ctl09").innerHTML
            Range("A1").Text = dat
         Else
            MsgBox "doesn't"
         End If
   End With
End Sub

please can someone show me where I am going wrong?

Body:
That URL doesn't work for me.  Your code should look something like this...

Option Explicit
Sub gethtmltable()
    Dim objWeb As QueryTable
    Dim sWebTable As String
     'You have to count down the tables on the URL listed in your query
     'This example shows how to retrieve the 2nd table from the web page.
    sWebTable = 2
     'Sets the url to run the query and the destination in the excel file
     'You can change both to suit your needs
    Set objWeb = ActiveSheet.QueryTables.Add( _
    Connection:="URL;http://www.vbaexpress.com/kb/default.php", _
    Destination:=Range("A1"))

    With objWeb

        .WebSelectionType = xlSpecifiedTables
        .WebTables = sWebTable
        .Refresh BackgroundQuery:=False
        .SaveData = True
    End With
    Set objWeb = Nothing
End Sub

You just need to identify which specific table you want to import data from.


问:
How to deterministically combine ints in a way that it always generates unique values?
I have a set of randomly generated ints, and an evolve(set) function that takes a set, removes two ints and inserts 4 new ints. I want the set never to have repeated ints. That is, no matter how many times I apply evolve(evolve(...evolve(set))), it should never have duplicated values.

What is a simple choice of combine(int x, int y) -> int that guarantees that property with high probability?

Example:

```<code>// Helpers.
var range = length => Array.from({length}, i => i);
var random = () => (Math.random() * Math.pow(2,31) | 0);
var removeRandom = set => set.splice(random() % set.length, 1)[0];
var hasRepeated = set => !set.sort((a,b) => a - b).reduce((a,b) => a && a !== b && b || 0, -1);

// Receives two parent ints, returns 4 derived ints.
// Can't use random() here; it must generate 4 ints
// from simple functions (multiplication, bitwise
// operations, etc.) of `a` and `b`.
function combine(a, b) {
  return [a + b + 0, a + b + 1, a + b + 2, a + b + 3];
};

// Removes two ints from set, inserts 4 ints.
function evolve(set) {
  var a = removeRandom(set);
  var b = removeRandom(set);
  set.push(...combine(a,b));
};

// Random initial set of ints.
var set = range(64).map(random);

// No matter how many times `evolve` is applied,
// the set should never have repeated ints.
for (var i = 0; i < 50000; ++i) {
  evolve(set);
}

// Prints `true` if algorithm is correct
// (no repeated number was generated).
console.log(!hasRepeated(set));
</code>```

Notice that, here, combine(a,b) just adds them together. This is a bad choice; with as few as 50000 calls to evolve, it already fails the test. I could use a linear congruential generator, but I wonder if it can be simpler than that under those conditions. Perhaps some use of XOR?

答:
If you have the space to keep an array with the universe of possible entries, you can just randomize it, then keep track of the indices that bound your set, incrementing the starting index to remove elements and the ending index to add them.

You can either randomize the whole array up front, or as the ending index gets incremented.

Body:
I have a set of randomly generated ints, and an evolve(set) function that takes a set, removes two ints and inserts 4 new ints. I want the set never to have repeated ints. That is, no matter how many times I apply evolve(evolve(...evolve(set))), it should never have duplicated values.

What is a simple choice of combine(int x, int y) -> int that guarantees that property with high probability?

Example:

// Helpers.
var range = length => Array.from({length}, i => i);
var random = () => (Math.random() * Math.pow(2,31) | 0);
var removeRandom = set => set.splice(random() % set.length, 1)[0];
var hasRepeated = set => !set.sort((a,b) => a - b).reduce((a,b) => a && a !== b && b || 0, -1);

// Receives two parent ints, returns 4 derived ints.
// Can't use random() here; it must generate 4 ints
// from simple functions (multiplication, bitwise
// operations, etc.) of `a` and `b`.
function combine(a, b) {
  return [a + b + 0, a + b + 1, a + b + 2, a + b + 3];
};

// Removes two ints from set, inserts 4 ints.
function evolve(set) {
  var a = removeRandom(set);
  var b = removeRandom(set);
  set.push(...combine(a,b));
};

// Random initial set of ints.
var set = range(64).map(random);

// No matter how many times `evolve` is applied,
// the set should never have repeated ints.
for (var i = 0; i < 50000; ++i) {
  evolve(set);
}

// Prints `true` if algorithm is correct
// (no repeated number was generated).
console.log(!hasRepeated(set));

Notice that, here, combine(a,b) just adds them together. This is a bad choice; with as few as 50000 calls to evolve, it already fails the test. I could use a linear congruential generator, but I wonder if it can be simpler than that under those conditions. Perhaps some use of XOR?


问:
Efficient way to mutate rowwise
I have two dataframes: dfUsers and purchases generated using the below code:

```<code>set.seed(1)
library(data.table)

dfUsers <- data.table(user = letters[1:5],
                      startDate = sample(seq.Date(from = as.Date('2016-01-01'), to = Sys.Date(), by = '1 day'), 3)
                      )

dfUsers$endDate <- dfUsers$startDate + sample(30:90,1)

purchases <- data.table(
  user = sample(letters[1:5], 500, replace = TRUE),
  purchaseDate = sample(seq.Date(from = as.Date('2016-01-01'), to = Sys.Date(), by = '1 day'), 500, replace = TRUE),
  amount = runif(50,300, 500)
)
</code>```

For each user I want to add together all the purchases during the period between the startDate and endDate.

My current approach is to use dplyr mutate over a function, but that's terribly slow as both tables grow.

I'm learning R so I'm wondering if there's a more efficient way to approach a problem of this nature?

The function:

```<code>addPurchases <- function(u, startDate, endDate) {
  purchases[user == u & startDate <= purchaseDate & endDate >= purchaseDate, sum(amount)]
}
</code>```

The dplyr chain

```<code>library(dplyr)
dfUsers %>%
  rowwise() %>%
  mutate(totalPurchase = addPurchases(user, startDate, endDate))
</code>```

答:
Solution using data.table - merge two tables and calculate sum by user:

```<code>library(data.table)
# Using OPs data
merge(dfUsers,
      purchases,
      "user")[purchaseDate >= startDate & purchaseDate <= endDate,
              sum(amount),
              user]
#    user       V1
# 1:    a 6929.469
# 2:    b 6563.416
# 3:    c 3607.794
# 4:    d 5591.748
# 5:    e 5727.622
</code>```

Title: Efficient way to mutate rowwise

Body:
I have two dataframes: dfUsers and purchases generated using the below code:

set.seed(1)
library(data.table)

dfUsers <- data.table(user = letters[1:5],
                      startDate = sample(seq.Date(from = as.Date('2016-01-01'), to = Sys.Date(), by = '1 day'), 3)
                      )

dfUsers$endDate <- dfUsers$startDate + sample(30:90,1)

purchases <- data.table(
  user = sample(letters[1:5], 500, replace = TRUE),
  purchaseDate = sample(seq.Date(from = as.Date('2016-01-01'), to = Sys.Date(), by = '1 day'), 500, replace = TRUE),
  amount = runif(50,300, 500)
)

For each user I want to add together all the purchases during the period between the startDate and endDate.

My current approach is to use dplyr mutate over a function, but that's terribly slow as both tables grow.

I'm learning R so I'm wondering if there's a more efficient way to approach a problem of this nature?

The function:

addPurchases <- function(u, startDate, endDate) {
  purchases[user == u & startDate <= purchaseDate & endDate >= purchaseDate, sum(amount)]
}

The dplyr chain

library(dplyr)
dfUsers %>%
  rowwise() %>%
  mutate(totalPurchase = addPurchases(user, startDate, endDate))

Body:
Solution using data.table - merge two tables and calculate sum by user:

library(data.table)
# Using OPs data
merge(dfUsers,
      purchases,
      "user")[purchaseDate >= startDate & purchaseDate <= endDate,
              sum(amount),
              user]
#    user       V1
# 1:    a 6929.469
# 2:    b 6563.416
# 3:    c 3607.794
# 4:    d 5591.748
# 5:    e 5727.622


问:
Overwriting soft delete table column for a model
I'm using laravel 5.4.

I have a model that points to a database table that has the following attributes.

```<code>id       integer
name     varchar
location varchar
deleted  boolean
</code>```

This is an old table and due to it being entwined in a bunch of code we can't change this table.

What I want to do is take advantage of laravels soft delete functionality within a model.  I know that laravel expects the column name to be deleted_at and the data type to be date on the database table.

How do I override this so this so that Laravel will look at the column deleted and check if it's a boolean?

I've tried looking at the classes that my model inherits from but haven't been able to find where the constant and function that handles this is defined. I suspect it might be on the collection but have had no luck.

Ideally I would like to simply redefine the functions in my model.

Thanks.

答:
Look into the Illuminate\Database\Eloquent\SoftDeletes trait and override runSoftDelete() and getDeletedAtColumn methods in the model.

In runSoftDelete() use boolean instead of timestamp and in getDeletedAtColumn() use DELETED instead of DELETED_AT

Another solution is adding global scopes or local scopes to work with soft deleted data.

Body:
I'm using laravel 5.4.

I have a model that points to a database table that has the following attributes.

id       integer
name     varchar
location varchar
deleted  boolean

This is an old table and due to it being entwined in a bunch of code we can't change this table.

What I want to do is take advantage of laravels soft delete functionality within a model.  I know that laravel expects the column name to be deleted_at and the data type to be date on the database table.

How do I override this so this so that Laravel will look at the column deleted and check if it's a boolean?

I've tried looking at the classes that my model inherits from but haven't been able to find where the constant and function that handles this is defined. I suspect it might be on the collection but have had no luck.

Ideally I would like to simply redefine the functions in my model.

Thanks.


问:
What is the fastest sorting algorithm for a small number of integers?
I am wondering what the fastest algorithm would be for this.  I have 8 integers between 0 and 3000 and I need to sort them.  Although there are only 8 integers, this operation will be performed millions of times.</p>

答:
Here is an implementation of an odd-even merge sort network in C99 (sorry for the "wrong" language):

```<code>#define CMP_SWAP(i, j) if (a[i] > a[j])              \
    { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; }

void sort8_network(int *a)
{
    CMP_SWAP(0, 1); CMP_SWAP(2, 3); CMP_SWAP(4, 5); CMP_SWAP(6, 7);
    CMP_SWAP(0, 2); CMP_SWAP(1, 3); CMP_SWAP(4, 6); CMP_SWAP(5, 7);
    CMP_SWAP(1, 2); CMP_SWAP(5, 6); CMP_SWAP(0, 4); CMP_SWAP(1, 5);
    CMP_SWAP(2, 6); CMP_SWAP(3, 7); CMP_SWAP(2, 4); CMP_SWAP(3, 5);
    CMP_SWAP(1, 2); CMP_SWAP(3, 4); CMP_SWAP(5, 6);
}
</code>```

I timed it on my machine against insertion sort

```<code>void sort8_insertion(int *a)
{
    for (int i = 1; i < 8; i++)
    {
        int tmp = a[i];
        int j = i;
        for (; j && tmp < a[j - 1]; --j)
            a[j] = a[j - 1];
        a[j] = tmp;
    }
}
</code>```

For about 10 million sorts (exactly 250 times all the 40320 possible permutations), the sort network took 0.39 seconds while insertion sort took 0.88 seconds.  Seems to me both are fast enough. (The figures inlcude about 0.04 seconds for generating the permutations.)

Body:
Here is an implementation of an odd-even merge sort network in C99 (sorry for the "wrong" language):

#define CMP_SWAP(i, j) if (a[i] > a[j])              \
    { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; }

void sort8_network(int *a)
{
    CMP_SWAP(0, 1); CMP_SWAP(2, 3); CMP_SWAP(4, 5); CMP_SWAP(6, 7);
    CMP_SWAP(0, 2); CMP_SWAP(1, 3); CMP_SWAP(4, 6); CMP_SWAP(5, 7);
    CMP_SWAP(1, 2); CMP_SWAP(5, 6); CMP_SWAP(0, 4); CMP_SWAP(1, 5);
    CMP_SWAP(2, 6); CMP_SWAP(3, 7); CMP_SWAP(2, 4); CMP_SWAP(3, 5);
    CMP_SWAP(1, 2); CMP_SWAP(3, 4); CMP_SWAP(5, 6);
}

I timed it on my machine against insertion sort

void sort8_insertion(int *a)
{
    for (int i = 1; i < 8; i++)
    {
        int tmp = a[i];
        int j = i;
        for (; j && tmp < a[j - 1]; --j)
            a[j] = a[j - 1];
        a[j] = tmp;
    }
}

For about 10 million sorts (exactly 250 times all the 40320 possible permutations), the sort network took 0.39 seconds while insertion sort took 0.88 seconds.  Seems to me both are fast enough. (The figures inlcude about 0.04 seconds for generating the permutations.)


答:
A solution using the dplyr. The idea is to merge data frames by user, filter the data by date, and then summarize the total amount by user.

```<code>library(dplyr)
dfUsers2 <- dfUsers %>%
  full_join(purchases, by = "user") %>%
  filter(purchaseDate >= startDate, purchaseDate <= endDate) %>%
  group_by(user) %>%
  summarise(Total = sum(amount, na.rm = TRUE))
dfUsers2
# # A tibble: 5 x 2
#    user    Total
#   <chr>    <dbl>
# 1     a 6929.469
# 2     b 6563.416
# 3     c 3607.794
# 4     d 5591.748
# 5     e 5727.622
</code>```

Title: Efficient way to mutate rowwise

Body:
A solution using the dplyr. The idea is to merge data frames by user, filter the data by date, and then summarize the total amount by user.

library(dplyr)
dfUsers2 <- dfUsers %>%
  full_join(purchases, by = "user") %>%
  filter(purchaseDate >= startDate, purchaseDate <= endDate) %>%
  group_by(user) %>%
  summarise(Total = sum(amount, na.rm = TRUE))
dfUsers2
# # A tibble: 5 x 2
#    user    Total
#   <chr>    <dbl>
# 1     a 6929.469
# 2     b 6563.416
# 3     c 3607.794
# 4     d 5591.748
# 5     e 5727.622


问:
Getting an Extra Empty line when exporting Excel Range to .txt file
I am trying to copy an Excel range to a .txt file.

The export is successful, with one exception, It adds one "extra" empty line at the end.

I've read and tests many of the solution on SO (and other sites), but still without any success.

My Code (relevant part)

```<code>' === Export to the .txt file ===
Dim TxtFileName As String, lineText As String

TxtFileName = ThisWorkbook.Path & "\Inv_" & Format(Date, "yyyymmdd") & ".txt"

Open TxtFileName For Output As #1
With StockSht
    For i = 1 To LastRow
        For j = 1 To 3
            If j = 3 Then
                lineText = lineText & .Cells(i, j).Value2
            Else ' j = 1 or 2
                lineText = lineText & .Cells(i, j).Value2 & vbTab
            End If
        Next j
        Print #1, lineText
        lineText = ""
    Next i
End With
Close #1
</code>```

My StockSht (worksheet object) and LastRow are defined correctly, and getting their values.

Screen-shot of the end of the exported .txt file

答:
Try using a <code>;</code> on the last print line.   </p>

```<code>' === Export to the .txt file ===
Dim TxtFileName As String, lineText As String

TxtFileName = ThisWorkbook.Path & "\Inv_" & Format(Date, "yyyymmdd") & ".txt"

Open TxtFileName For Output As #1
With StockSht
    For i = 1 To LastRow
        For j = 1 To 3
            If j = 3 Then
                lineText = lineText & .Cells(i, j).Value2
            Else ' j = 1 or 2
                lineText = lineText & .Cells(i, j).Value2 & vbTab
            End If
        Next j
        If i = LastRow Then
            Print #1, lineText;
        Else
            Print #1, lineText
        End if
        lineText = ""
    Next i
End With
Close #1
</code>```

Body:
I am trying to copy an Excel range to a .txt file.

The export is successful, with one exception, It adds one "extra" empty line at the end.

I've read and tests many of the solution on SO (and other sites), but still without any success.

My Code (relevant part)

' === Export to the .txt file ===
Dim TxtFileName As String, lineText As String

TxtFileName = ThisWorkbook.Path & "\Inv_" & Format(Date, "yyyymmdd") & ".txt"

Open TxtFileName For Output As #1
With StockSht
    For i = 1 To LastRow
        For j = 1 To 3
            If j = 3 Then
                lineText = lineText & .Cells(i, j).Value2
            Else ' j = 1 or 2
                lineText = lineText & .Cells(i, j).Value2 & vbTab
            End If
        Next j
        Print #1, lineText
        lineText = ""
    Next i
End With
Close #1

My StockSht (worksheet object) and LastRow are defined correctly, and getting their values.

Screen-shot of the end of the exported .txt file

Body:
Try using a ; on the last print line.

' === Export to the .txt file ===
Dim TxtFileName As String, lineText As String

TxtFileName = ThisWorkbook.Path & "\Inv_" & Format(Date, "yyyymmdd") & ".txt"

Open TxtFileName For Output As #1
With StockSht
    For i = 1 To LastRow
        For j = 1 To 3
            If j = 3 Then
                lineText = lineText & .Cells(i, j).Value2
            Else ' j = 1 or 2
                lineText = lineText & .Cells(i, j).Value2 & vbTab
            End If
        Next j
        If i = LastRow Then
            Print #1, lineText;
        Else
            Print #1, lineText
        End if
        lineText = ""
    Next i
End With
Close #1


问:
Sorting list of filename and folders
Looking for some help with a script I'm trying to create.
I have a script that asks a user to enter some text (from an email) via a textbox using Winforms. This email contains a list of files and folders.
I use some regex to strip out what is not needed from the email and am left with a variable (called $results) that looks like this:

```<code>$results
file1.zip
graphics\folder1
file2.zip
graphics\folder1
file3.zip
graphics\folder2
etc...
</code>```

The idea is that I now need to:

```<code>Extract file1.zip into graphics\folder1
Extract file2.zip into graphics\folder1
Extract file3.zip into graphics\folder2
...and so on.
</code>```

I am trying to now create a custom PSObject so that I can call this list later in the script to deploy the files into the correct paths. I'm having a hard time trying to figure out how I can accomplish this. So far, I have tried:

```<code>$Object = New-Object -TypeName psobject
$Object | Add-Member -MemberType NoteProperty -Name File -Value $results[0]
$Object | Add-Member -MemberType NoteProperty -Name Path -Value $results[1]
$Object
</code>```

Which gives me a result of:

```<code>File       Path
----       ----
file1.zip  graphics\folder1
</code>```

When I try to iterate through each item in the $results variable...

```<code>$Object = New-Object -TypeName psobject
forEach ($i in $results) {
$Object | Add-Member -MemberType NoteProperty -Name File -Value $i[0]
$Object | Add-Member -MemberType NoteProperty -Name Path -Value $i[1]
}
$Object
</code>```

...I get the following error:

```<code>Add-Member : Cannot add a member with the name "File" because a member with that name already exists. To overwrite the member anyway, add the Force parameter to your command.
</code>```

I don't want to over-write, I want to append.
The problem is I am not sure how to tell PowerShell to go through each item in the $results variable and add it so that I am left with:

```<code>File       Path
----       ----
file1.zip  graphics\folder1
file2.zip  graphics\folder1
file3.zip  graphics\folder2
</code>```

Once I have that, the end result is that I can take the results in the PSObject and then extract the files accordingly.

Any idea on what I am doing wrong here?
Maybe I am going about this all wrong?
Any help is greatly appreciated!

答:
```<code>$Object = forEach ($i in $results) {
    [PSCustomObject]@{
        File = $i[0]
        Path = $i[1]
    }
}
$Object
</code>```

Title: Sorting list of filename and folders

Body:
Looking for some help with a script I'm trying to create.
I have a script that asks a user to enter some text (from an email) via a textbox using Winforms. This email contains a list of files and folders.
I use some regex to strip out what is not needed from the email and am left with a variable (called $results) that looks like this:

$results
file1.zip
graphics\folder1
file2.zip
graphics\folder1
file3.zip
graphics\folder2
etc...

The idea is that I now need to:

Extract file1.zip into graphics\folder1
Extract file2.zip into graphics\folder1
Extract file3.zip into graphics\folder2
...and so on.

I am trying to now create a custom PSObject so that I can call this list later in the script to deploy the files into the correct paths. I'm having a hard time trying to figure out how I can accomplish this. So far, I have tried:

$Object = New-Object -TypeName psobject
$Object | Add-Member -MemberType NoteProperty -Name File -Value $results[0]
$Object | Add-Member -MemberType NoteProperty -Name Path -Value $results[1]
$Object

Which gives me a result of:

File       Path
----       ----
file1.zip  graphics\folder1

When I try to iterate through each item in the $results variable...

$Object = New-Object -TypeName psobject
forEach ($i in $results) {
$Object | Add-Member -MemberType NoteProperty -Name File -Value $i[0]
$Object | Add-Member -MemberType NoteProperty -Name Path -Value $i[1]
}
$Object

...I get the following error:

Add-Member : Cannot add a member with the name "File" because a member with that name already exists. To overwrite the member anyway, add the Force parameter to your command.

I don't want to over-write, I want to append.
The problem is I am not sure how to tell PowerShell to go through each item in the $results variable and add it so that I am left with:

File       Path
----       ----
file1.zip  graphics\folder1
file2.zip  graphics\folder1
file3.zip  graphics\folder2

Once I have that, the end result is that I can take the results in the PSObject and then extract the files accordingly.

Any idea on what I am doing wrong here?
Maybe I am going about this all wrong?
Any help is greatly appreciated!


答:
Based on your example, here's what I think you're trying to accomplish:

Setup:

```<code>PS C:\> $Results
file1.zip
graphics\folder1
file2.zip
graphics\folder1
file3.zip
graphics\folder2
</code>```

Logic:

```<code>$Files = @{} #initializes empty hashtable

$tmp = ''
For ($i = 0; $i -le $Results.Count; $i++)
{
    If ($i -eq 0) { $tmp = $Results[$i]; Continue } #initializes tmp value

    If ($i % 2 -eq 0) { $tmp = $Results[$i] }
    Else { $Files["$tmp"] = $Results[$i] }
}
</code>```

Output:

```<code>PS C:\> $Files

Name                           Value
----                           -----
file1.zip                      graphics\folder1
file3.zip                      graphics\folder2
file2.zip                      graphics\folder1
</code>```

Title: Sorting list of filename and folders

Body:
Based on your example, here's what I think you're trying to accomplish:

Setup:

PS C:\> $Results
file1.zip
graphics\folder1
file2.zip
graphics\folder1
file3.zip
graphics\folder2

Logic:

$Files = @{} #initializes empty hashtable

$tmp = ''
For ($i = 0; $i -le $Results.Count; $i++)
{
    If ($i -eq 0) { $tmp = $Results[$i]; Continue } #initializes tmp value

    If ($i % 2 -eq 0) { $tmp = $Results[$i] }
    Else { $Files["$tmp"] = $Results[$i] }
}

Output:

PS C:\> $Files

Name                           Value
----                           -----
file1.zip                      graphics\folder1
file3.zip                      graphics\folder2
file2.zip                      graphics\folder1


问:
Where did the default Useragent of Cobalt come from?
When run the cobalt, I can see the useragent from the log:

```<code>[0101/000230:INFO:application.cc(690)] User Agent: Mozilla/5.0 (DirectFB; Linux x86_64) Cobalt/4.13031-qa (unlike Gecko) Starboard/1
</code>```

So where does it come from? Is there a way to change it?

答:
If your SbSystemGetDeviceType() is true for SystemDeviceTypeIsTv() (in file user_agent_string_factory_starboard.cc), you can customize the UA by implementing some fields of SbSystemGetProperty() + some SbSystemGet() functions.

This is a typical example:

Mozilla/5.0 (1) Cobalt/11.119147-gold (unlike Gecko) Starboard/8, 2_8_6/5 (3, 4, 7)

where,

kSbSystemPropertyPlatformName

kSbSystemPropertyNetworkOperatorName

kSbSystemPropertyManufacturerName

kSbSystemPropertyModelName

kSbSystemPropertyFirmwareVersion

kSbSystemPropertyChipsetModelNumber

SbSystemGetConnectionType()

SbSystemGetDeviceType()

Body:
When run the cobalt, I can see the useragent from the log:

[0101/000230:INFO:application.cc(690)] User Agent: Mozilla/5.0 (DirectFB; Linux x86_64) Cobalt/4.13031-qa (unlike Gecko) Starboard/1

So where does it come from? Is there a way to change it?


问:
How to make error message for this code
```<code>#!/bin/bash

my_array=(red orange green)
value='green'

for i in "${!my_array[@]}"; do
if [[ "${my_array[$i]}" = "${value}" ]]; then
   echo "${i}";
fi
done
</code>```

<p>This code will print the index of a value in an array, How can i improve it to print error message if the Entry was not in the array </p>

答:
You can add a flag variable,
cleared before the loop,
set when the value is found,
and print the error message after the loop if the flag is still empty.

```<code>found=
for i in "${!my_array[@]}"; do
    if [[ "${my_array[$i]}" = "${value}" ]]; then
        echo "${i}"
        found=1
    fi
done

if [ ! "$found" ]; then
    echo Error: no such value in the array: $value
fi
</code>```

Alternatively,
you could use an associative array to keep an index of the values and their positions in the array:

```<code>my_array=(red orange green)

declare -A index
for ((i = 0; i < ${#my_array[@]}; i++)); do
    index[${my_array[$i]}]=$i
done

local value=$1

if [ "${index[$value]}" ]; then
    echo "${index[$value]}"
else
    echo Error: no such value in the array: $value
fi
</code>```

Title: How to make error message for this code

Body:
#!/bin/bash

my_array=(red orange green)
value='green'

for i in "${!my_array[@]}"; do
if [[ "${my_array[$i]}" = "${value}" ]]; then
   echo "${i}";
fi
done

This code will print the index of a value in an array, How can i improve it to print error message if the Entry was not in the array

Body:
You can add a flag variable,
cleared before the loop,
set when the value is found,
and print the error message after the loop if the flag is still empty.

found=
for i in "${!my_array[@]}"; do
    if [[ "${my_array[$i]}" = "${value}" ]]; then
        echo "${i}"
        found=1
    fi
done

if [ ! "$found" ]; then
    echo Error: no such value in the array: $value
fi

Alternatively,
you could use an associative array to keep an index of the values and their positions in the array:

my_array=(red orange green)

declare -A index
for ((i = 0; i < ${#my_array[@]}; i++)); do
    index[${my_array[$i]}]=$i
done

local value=$1

if [ "${index[$value]}" ]; then
    echo "${index[$value]}"
else
    echo Error: no such value in the array: $value
fi


Title: Efficient way to mutate rowwise

Body:
The fast, clean and memory efficient solution is to use non-equi joins.

purchases[dfUsers, on = .(user, purchaseDate >= startDate, purchaseDate <= endDate),
          sum(amount), by = .EACHI]
#   user purchaseDate purchaseDate       V1
#1:    a   2016-07-06   2016-09-29 6929.469
#2:    b   2016-09-20   2016-12-14 6563.416
#3:    c   2017-02-08   2017-05-04 3607.794
#4:    d   2016-07-06   2016-09-29 5591.748
#5:    e   2016-09-20   2016-12-14 5727.622


问:
Connect to cluster through VPC
I have a kubernetes cluster with ec2 nodes, how can I connect to pods in this cluster externally from my local machine or another ec2 instance not in the cluster? I have the VPC ID and the cluster namespace.</p>

答:
AWS announced EKS ( Elastic Kubernetes Service ) as new service few days ago. However it is still in preview the time that I am writing this answer.

Anyway, you can use kops which is built for this purpose ; to make marriage between k8s and AWS .

You will do something like the following:

```<code>kops create cluster --name=k8s.example.com \
   --state=s3://cluster-state \
   --zones=eu-west-1a \
   --node-count=2 \
   --node-size=t2.micro \
   --master-size=t2.micro \
   --dns-zone=k8s.example.com
</code>```

Title: Connect to cluster through VPC

Body:
AWS announced EKS ( Elastic Kubernetes Service ) as new service few days ago. However it is still in preview the time that I am writing this answer.

Anyway, you can use kops which is built for this purpose ; to make marriage between k8s and AWS .

You will do something like the following:

kops create cluster --name=k8s.example.com \
   --state=s3://cluster-state \
   --zones=eu-west-1a \
   --node-count=2 \
   --node-size=t2.micro \
   --master-size=t2.micro \
   --dns-zone=k8s.example.com


问:
Skip tests in Jenkins
I've set up a build on Jenkins for a Maven project, and I would like to build it without running any of the tests.  I've tried entering "clean install -DskipTests" in the goals field, like this:

But it doesn't work.  What am I doing incorrectly?

Note:  I want to skip the tests without touching the pom.  I have a separate build that DOES run the tests.

答:
Just to extend the answer, maven has 2 options for skipping tests:

-DskipTests=true  — The one that was mentioned. With this parameter, maven ignores tests completely.

-Dmaven.test.skip=true — With this option maven compiles the tests but doesn't launch them.

So you may want to use the second option instead as fast code compile validation. E.G.: if you develop some library or module that will be used by some one else you must be sure that you don't brake contract with the client. Tests compilation can help you with this.

Use either of these parameters depending on your needs.

Title: Skip tests in Jenkins


问:
Create a .NET app that works on any .NET version if only basic requirements
I'm using VS2017 on Windows 10 to work on a C# project.  It is a really small console app that does nothing but require administrator privileges and then runs an HTA.

The code references only these .NET assemblies:

```<code>using System;
using System.Diagnostics;
using System.IO;
</code>```

Since all of these exist in .NET since 2.0 and forward, it seems it should be possible to create the app without having to specify anything except .NET 2.0.  But doing this causes the app to display the "must install .NET 2.0 or 3.5" message when running it on a system which has only .NET 4.0 or greater.

Is there a way to create this app so it doesn't specify a .NET version?  I tried deleting the <TargetFrameworkVersion> from the .csproj file but it still builds thinking it is a .NET 4.0 app.

UPDATE

Based upon a suggested answer and this article, I updated the App.config to show it supports both v2 and v4:

```<code><startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v2.0.50727"/>
  <supportedRuntime version="v4.0"/>
</startup>
</code>```

I then built with target set to NET Framework 4.6.1 and ran it on a Win7Pro-64bit system with only NET Framework 2.0/3.5 installed.  It displayed the message "You must first install one of the following versions of .NET Framework" and only listed v4.0.30319.

I then built with target set to NET Framework 2.0 and ran it on a Win10Pro-64bit system with only NET Framework 4.0 installed.  It displayed a message that I had to "NET Framework 3.5" or my app may not work correctly.  I tried the "skip this" option and the app didn't work.

Running on the system according to the target, the app works fine.

Why won't it just use whichever framework is available since it is designated as supporting both?

答:
Inside the App.Config you can specify the version of the runtime you can support.

https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-configure-an-app-to-support-net-framework-4-or-4-5

```<code><configuration>
  <startup>
    <supportedRuntime version="v1.1.4322"/>
    <supportedRuntime version="v2.0.50727"/>
    <supportedRuntime version="v4.0"/>
  </startup>
</configuration>
</code>```

As with anything, you should test that your application actually can run on all of the specified versions.

Body:
I'm using VS2017 on Windows 10 to work on a C# project.  It is a really small console app that does nothing but require administrator privileges and then runs an HTA.

The code references only these .NET assemblies:

using System;
using System.Diagnostics;
using System.IO;

Since all of these exist in .NET since 2.0 and forward, it seems it should be possible to create the app without having to specify anything except .NET 2.0.  But doing this causes the app to display the "must install .NET 2.0 or 3.5" message when running it on a system which has only .NET 4.0 or greater.

Is there a way to create this app so it doesn't specify a .NET version?  I tried deleting the <TargetFrameworkVersion> from the .csproj file but it still builds thinking it is a .NET 4.0 app.

UPDATE

Based upon a suggested answer and this article, I updated the App.config to show it supports both v2 and v4:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v2.0.50727"/>
  <supportedRuntime version="v4.0"/>
</startup>

I then built with target set to NET Framework 4.6.1 and ran it on a Win7Pro-64bit system with only NET Framework 2.0/3.5 installed.  It displayed the message "You must first install one of the following versions of .NET Framework" and only listed v4.0.30319.

I then built with target set to NET Framework 2.0 and ran it on a Win10Pro-64bit system with only NET Framework 4.0 installed.  It displayed a message that I had to "NET Framework 3.5" or my app may not work correctly.  I tried the "skip this" option and the app didn't work.

Running on the system according to the target, the app works fine.

Why won't it just use whichever framework is available since it is designated as supporting both?

Body:
Inside the App.Config you can specify the version of the runtime you can support.

https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-configure-an-app-to-support-net-framework-4-or-4-5

<configuration>
  <startup>
    <supportedRuntime version="v1.1.4322"/>
    <supportedRuntime version="v2.0.50727"/>
    <supportedRuntime version="v4.0"/>
  </startup>
</configuration>

As with anything, you should test that your application actually can run on all of the specified versions.


问:
My Java code is not running
If I am not mistaken, this bit of code should print out all even numbers smaller than or equal to 100. When I run this code, nothing happens. No error message or anything. I'm using Eclipse.</p>

```<code>public class Even {

    public static void main(String args[]) {

        int number = 1;
        int remainder = number % 2;

        while(number <= 100) {
            number++;
            if(remainder == 0) {
                System.out.println(number);
            }
        }

    }

}
</code>```

答: The reminder doesn't change as the assignment is prior to while loop. The statement int remainder = number % 2; has to be inside while loop to see the expected result.</p>

Title: My Java code is not running

Body:
If I am not mistaken, this bit of code should print out all even numbers smaller than or equal to 100. When I run this code, nothing happens. No error message or anything. I'm using Eclipse.

public class Even {

    public static void main(String args[]) {

        int number = 1;
        int remainder = number % 2;

        while(number <= 100) {
            number++;
            if(remainder == 0) {
                System.out.println(number);
            }
        }

    }

}


问:
How do I save an Int array in Swift using NSUserDefaults?
This is an array:

```<code>var myArray = [1]
</code>```

It contains Int values.

This is how I save an array in NSUserDefaults. This code seems to be working fine:

```<code>NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "myArray")
</code>```

This is how I load an array:

```<code>myArray = NSUserDefaults.standardUserDefaults().objectForKey("myArray")
</code>```

The code above, though, retrieves an error. Why?

答:
Swift 4:

```<code>myArray : [Int] = UserDefaults.standard.object(forKey: "myArray") as! [Int]
</code>```

Body:
This is an array:

var myArray = [1]

It contains Int values.

This is how I save an array in NSUserDefaults. This code seems to be working fine:

NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "myArray")

This is how I load an array:

myArray = NSUserDefaults.standardUserDefaults().objectForKey("myArray")

The code above, though, retrieves an error. Why?

Body:
Swift 4:

myArray : [Int] = UserDefaults.standard.object(forKey: "myArray") as! [Int]


问:
How do I remove the first element of a tensor in keras as a layer?
How do I remove the first element of a tensor in keras as a layer?
For example:

```<code>layer = Input(input_shape=(100,),name='input')
layer = Conv1D(97,kernel_size=10,strides=10)(layer)
layer = >something that removes the first element<(layer)
layer = Flaten()(layer)
model = Model(input,layer)
</code>```

This model would have 97*9 outputs. 97 from the Conv layer, and each conv filter would output 10 nodes, but the first of those nodes would be removed by the layer I am looking for. Because the conv layer has shape (batch_size,10,97) I am looking for a way to remove the first element of axis=1.

How would I go about doing this? I tried using the Lambda layer but I can't quite figger out how to make this work.

Edit:
 I'm asking this question because what I want to do is if I have a layer of shape (batch_size, x, y) I want to transform this to the shape (batch_size, 0.5x, 2y) in such a way that if x is for example 10, the elements 0,2,4,6,8 and 1,3,5,7,9 are stacked on top of each other. Right now I'm doing this with Maxpooling1D(pool_size=1, strides=2) to generate 0,2,4,6,8. To generate 1,3,5,7,9 I'd have to remove 1 element from the start in the manner explained above before applying the maxpooling layer. Thank you so much for your time!

答:
Because @NadavB wants to know the answer:

```<code>layer = Input(input_shape=(100,),name='input')
layer = Conv1D(97,kernel_size=10,strides=10)(layer)
layer = Lambda(lambda x : x[:,1:,:])(layer)
layer = Flaten()(layer)
model = Model(input,layer)
</code>```

I hope this helps you out :)

Body:
How do I remove the first element of a tensor in keras as a layer?
For example:

layer = Input(input_shape=(100,),name='input')
layer = Conv1D(97,kernel_size=10,strides=10)(layer)
layer = >something that removes the first element<(layer)
layer = Flaten()(layer)
model = Model(input,layer)

This model would have 97*9 outputs. 97 from the Conv layer, and each conv filter would output 10 nodes, but the first of those nodes would be removed by the layer I am looking for. Because the conv layer has shape (batch_size,10,97) I am looking for a way to remove the first element of axis=1.

How would I go about doing this? I tried using the Lambda layer but I can't quite figger out how to make this work.

Edit:
 I'm asking this question because what I want to do is if I have a layer of shape (batch_size, x, y) I want to transform this to the shape (batch_size, 0.5x, 2y) in such a way that if x is for example 10, the elements 0,2,4,6,8 and 1,3,5,7,9 are stacked on top of each other. Right now I'm doing this with Maxpooling1D(pool_size=1, strides=2) to generate 0,2,4,6,8. To generate 1,3,5,7,9 I'd have to remove 1 element from the start in the manner explained above before applying the maxpooling layer. Thank you so much for your time!

Body:
Because @NadavB wants to know the answer:

layer = Input(input_shape=(100,),name='input')
layer = Conv1D(97,kernel_size=10,strides=10)(layer)
layer = Lambda(lambda x : x[:,1:,:])(layer)
layer = Flaten()(layer)
model = Model(input,layer)

I hope this helps you out :)