问:
Javascript google heatmap gradient settings for multiple layers
Using google maps javascript api, I want to create two heatmap overlays with different color gradients for each overlay. So far I have been able to create the two overlays, but when I try to apply a different gradient to each one there is no output.

Here is the code:

```<code>  var map, heatmap, heatmap2;
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 11,
        center: {lat: 47.608013, lng: -122.335167},
        mapTypeId:'hybrid'
    });
    heatmap = new google.maps.visualization.HeatmapLayer({
        data: getPoints(),
        map: map
        gradient: getGrad()
    });
    heatmap2 = new google.maps.visualization.HeatmapLayer({
        data:   getPoints1(),
        map:    map
        gradient: getGrad1()
    });
  }
function getGrad () {
return [
    rgba(255,0,0,0),
        // more values here
];
}
function getGrad1 ()    {
return [
    rgba(0,255,255,0),
        //more values here
];
}
</code>```

To clarify, whenever the gradient properties get commented out everything works with the default gradient. The code above produces no output. Any ideas?

答:
The gradient values are supposed to be strings. rgba is a css function, not a js one and so in the developer console you should be seeing several errors stating that the function is not defined.

```<code>function getGrad1 ()    {
    return [
        'rgba(0,255,255,0)',
            //more values here
    ];
}
</code>```

Have a look at the example here: https://developers.google.com/maps/documentation/javascript/examples/layer-heatmap

Body:
Using google maps javascript api, I want to create two heatmap overlays with different color gradients for each overlay. So far I have been able to create the two overlays, but when I try to apply a different gradient to each one there is no output.

Here is the code:

  var map, heatmap, heatmap2;
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 11,
        center: {lat: 47.608013, lng: -122.335167},
        mapTypeId:'hybrid'
    });
    heatmap = new google.maps.visualization.HeatmapLayer({
        data: getPoints(),
        map: map
        gradient: getGrad()
    });
    heatmap2 = new google.maps.visualization.HeatmapLayer({
        data:   getPoints1(),
        map:    map
        gradient: getGrad1()
    });
  }
function getGrad () {
return [
    rgba(255,0,0,0),
        // more values here
];
}
function getGrad1 ()    {
return [
    rgba(0,255,255,0),
        //more values here
];
}

To clarify, whenever the gradient properties get commented out everything works with the default gradient. The code above produces no output. Any ideas?

Body:
The gradient values are supposed to be strings. rgba is a css function, not a js one and so in the developer console you should be seeing several errors stating that the function is not defined.

function getGrad1 ()    {
    return [
        'rgba(0,255,255,0)',
            //more values here
    ];
}

Have a look at the example here: https://developers.google.com/maps/documentation/javascript/examples/layer-heatmap


来源: stackexchange

问:
Store Lists on Redis
I have a list and I would like to cache it into redis. I tried two ways to achieve it by using hashes.

Consider this first approach. I create only one hash and set items as hash values:

```<code>// ..

$apiArray = [..]; // array from parsing an api

if(!$c->keys('lista')){
    foreach (json_decode($apiArray) as $item){
        $c->hset('lista', $item->id, serialize($item));
    }
}

foreach ($c->hgetall('lista') as $key){

    $item = unserialize($key);

    echo '<p>';
    echo '<strong>id</strong>: '.$item->id.'<br>';
    echo '<strong>name</strong>: '.$item->name.'<br>';
    echo '<strong>email</strong>: '.$item->email.'<br>';
    echo '</p>';
}
</code>```

To loop over 10000 items, it takes 0.5 seconds.

And now consider this one. A single hash on every element of the original array:

```<code>if(!$c->keys('lista:*')){
    foreach (json_decode($apiArray) as $item){
        $c->hset('lista:'.$item->id, 'element', serialize($item));
    }
}

foreach ($c->keys('lista:*') as $item) {
    $item = unserialize($c->hget($item, 'element'));

    echo '<p>';
    echo '<strong>id</strong>: '.$item->id.'<br>';
    echo '<strong>name</strong>: '.$item->name.'<br>';
    echo '<strong>email</strong>: '.$item->email.'<br>';
    echo '</p>';
}
</code>```

The loop of 10000 records takes 3 seconds.

This is very surprising to me, because the second one is the approach covered in Redis official documentation, and it also supports the secondary indexing (by using zadd and sadd).

Why is slowest than the first approach? Am I wrong in something?

I think it might happen because I have to call 10000 times the hgetall() method to get items in the loop. Can you cofirm this?

Have I to prefer the first approach?

Thank you guys

M :)

答: It appears that you're interested in caching your entire list, writing and fetching it in bulk every time. In that case, what you can do is to just store the entire thing as JSON in a Redis String to obtain maximal performance.</p>

ContentLicense: CC BY-SA 3.0

Title: Store Lists on Redis

Body:
I have a list and I would like to cache it into redis. I tried two ways to achieve it by using hashes.

Consider this first approach. I create only one hash and set items as hash values:

// ..

$apiArray = [..]; // array from parsing an api

if(!$c->keys('lista')){
    foreach (json_decode($apiArray) as $item){
        $c->hset('lista', $item->id, serialize($item));
    }
}

foreach ($c->hgetall('lista') as $key){

    $item = unserialize($key);

    echo '
';
    echo 'id: '.$item->id.'
';
    echo 'name: '.$item->name.'
';
    echo 'email: '.$item->email.'
';
    echo '
';
}

To loop over 10000 items, it takes 0.5 seconds.

And now consider this one. A single hash on every element of the original array:

if(!$c->keys('lista:*')){
    foreach (json_decode($apiArray) as $item){
        $c->hset('lista:'.$item->id, 'element', serialize($item));
    }
}

foreach ($c->keys('lista:*') as $item) {
    $item = unserialize($c->hget($item, 'element'));

    echo '
';
    echo 'id: '.$item->id.'
';
    echo 'name: '.$item->name.'
';
    echo 'email: '.$item->email.'
';
    echo '
';
}

The loop of 10000 records takes 3 seconds.

This is very surprising to me, because the second one is the approach covered in Redis official documentation, and it also supports the secondary indexing (by using zadd and sadd).

Why is slowest than the first approach? Am I wrong in something?

I think it might happen because I have to call 10000 times the hgetall() method to get items in the loop. Can you cofirm this?

Have I to prefer the first approach?

Thank you guys

M :)


问:
Managing Git Users and Passwords
I've been using Git to keep a repository of a project on a separate server.  Currently to push things to the repository after a commit I do

```<code>git push
</code>```

and then I am asked for the password for the account I used to setup the git repository on the remote server.  Since it's been awhile since I setup the repository, I'm not sure how to either remove that password (bad idea maybe) or change/add user accounts for the git repository.  I'm sure it's something simple but I'm having a hard time googling for it. Is there some argument I'm missing for the push command?

Thanks.

答:
There's likely some duplicates here on SO, but I didn't see them at first search, so here's your quick answer.

You probably want to use SSH public/private keypair authentication. In general, this means running ssh-keygen on your local computer (if you haven't before), and then using ssh-copy-id user@host to copy your public key to the remote. (If you don't have ssh-copy-id, you can just add your public key to .ssh/authorized_keys on the remote; that's all it does.) Be sure to give the public key to the appropriate user (the one with permissions for the git repo).

If you'd like to be more secure, you can give your keypair a passphrase and use something like ssh-agent or keychain to remember it for a session. See Configuring Git over SSH for more information on that.

If you're going to be doing a lot of this, you might want to look into gitolite, which automates a lot of this git admin type stuff. If you're going to keep doing it manually, and give others the ability to use that repo, you might want to make the repo user's shell git-shell, which is essentially a no-login shell which is only able to run the necessary git commands.

ContentLicense: CC BY-SA 2.5

Title: Managing Git Users and Passwords

Body:
I've been using Git to keep a repository of a project on a separate server.  Currently to push things to the repository after a commit I do

git push

and then I am asked for the password for the account I used to setup the git repository on the remote server.  Since it's been awhile since I setup the repository, I'm not sure how to either remove that password (bad idea maybe) or change/add user accounts for the git repository.  I'm sure it's something simple but I'm having a hard time googling for it. Is there some argument I'm missing for the push command?

Thanks.


问:
String.split vs StringUtils.split in Java gives different results
Consider a string like below with delimiter __|__.

```<code>String str = "a_b__|__c_d";
</code>```

str.split("__\\|__") gives 2 splits a_b and c_d
StringUtils.split(str, "__|__") or StringUtils.split(str, "__\\|__") gives 4 splits a, b, c, d which is not desired.

Is there any way to make StringUtils.split() to give same results String.split()?

答:
No, as per documentation, second parameter of StringUtils.split is the list of all characters that are considered splitters.
There is a different function in Apache Commons which does what you want - StringUtils.splitByWholeSeparator. Still, I don't get what's wrong with simple String.split.</p>

Body:
Consider a string like below with delimiter __|__.

String str = "a_b__|__c_d";

str.split("__\\|__") gives 2 splits a_b and c_d
StringUtils.split(str, "__|__") or StringUtils.split(str, "__\\|__") gives 4 splits a, b, c, d which is not desired.

Is there any way to make StringUtils.split() to give same results String.split()?


问:
Show a new select for option selected dynamically jquery
```<code><div class="form-group">
   <label for="options">foo</label>
   <select class="form-control"  name="options" multiple>
     <option value="">-- Choice --</option>
     <option value="opt1">test1</option>
     <option value="opt2">test2</option>
     <option value="opt3">test3</option>
  </select>
</div>
<script type="text/javascript">
  $("#scope_new_system").change(function() {
     var allSelected = new Array();
     $("#scope_new_system option:selected").each(function() {
       allSelected.push(this.value);
     });
  });
</script>
</code>```

I'm trying to dynamically generate a select with different options based on options selected on the multiple select named "options" above. For example if I click on option test 1 then a select element with options shows to select an option. If I select test 2 then another select shows because I now have 2 options selected. Finally if I unclicked test 1 select option goes away and if i do the same with test 2 it also goes away as well and i'm left with nothing selected. Please help!.

答:
You can use this.

var allSelected = [];

$("#scope_new_system").on("change",function() {
    var allSelected = new Array();
    $("#scope_new_system option:selected").each(function(){
        allSelected.push(this.value);

    });
    console.log(allSelected)

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="form-group">
<label for="options">foo</label>
   <select id="scope_new_system" class="form-control"  name="options" multiple>
     <option value="">-- Choice --</option>
      <option value="opt1">test1</option>
      <option value="opt2">test2</option>
      <option value="opt3">test3</option>
  </select>
</div></code>```

Body:
   foo
   <select class="form-control"  name="options" multiple>
     <option value="">-- Choice --</option>
     <option value="opt1">test1</option>
     <option value="opt2">test2</option>
     <option value="opt3">test3</option>
  </select>

I'm trying to dynamically generate a select with different options based on options selected on the multiple select named "options" above. For example if I click on option test 1 then a select element with options shows to select an option. If I select test 2 then another select shows because I now have 2 options selected. Finally if I unclicked test 1 select option goes away and if i do the same with test 2 it also goes away as well and i'm left with nothing selected. Please help!.

Body:
You can use this.

var allSelected = [];

$("#scope_new_system").on("change",function() {
    var allSelected = new Array();
    $("#scope_new_system option:selected").each(function(){
        allSelected.push(this.value);

    });
    console.log(allSelected)

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="form-group">
<label for="options">foo</label>
   <select id="scope_new_system" class="form-control"  name="options" multiple>
     <option value="">-- Choice --</option>
      <option value="opt1">test1</option>
      <option value="opt2">test2</option>
      <option value="opt3">test3</option>
  </select>
</div>


问:
Difference between synchronized(this) and few synchronized methods of class
In Programming Interviews Exposed book (Wrox publications), code for Producer consumer problem uses 'synchronized' keyword for each of produce() and consume() methods inside a class called IntBuffer. Is this different than using synchronized(this) inside each of those methods ? The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion. The methods produce and consume should both entirely be synchronized right ?

Code in the book:

```<code>public class IntBuffer
{
    private int index;
    private int[] buffer = new int[8];

    // Function called by producer thread
    public synchronized void produce(int num) {
        while(index == buffer.length - 1) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        buffer[index++] = num;
        notifyAll();
    }

    // Function called by consumer thread
    public synchronized int consume() {
        while(index == 0) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        int ret = buffer[--index];
        notifyAll();
        return ret;
    }
}
</code>```

答:
Q: Is this different than using synchronized(this) inside each of those methods ?
A : No, it is not different, by using block (synchronize(this) you can synchronize just part of your code, not the whole method.
For example :</p>

```<code>public void m1(){
// some code
synchronized(this){
// thread-safe code
}
</code>```

Body:
In Programming Interviews Exposed book (Wrox publications), code for Producer consumer problem uses 'synchronized' keyword for each of produce() and consume() methods inside a class called IntBuffer. Is this different than using synchronized(this) inside each of those methods ? The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion. The methods produce and consume should both entirely be synchronized right ?

Code in the book:

public class IntBuffer
{
    private int index;
    private int[] buffer = new int[8];

    // Function called by producer thread
    public synchronized void produce(int num) {
        while(index == buffer.length - 1) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        buffer[index++] = num;
        notifyAll();
    }

    // Function called by consumer thread
    public synchronized int consume() {
        while(index == 0) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        int ret = buffer[--index];
        notifyAll();
        return ret;
    }
}

Body:
Q: Is this different than using synchronized(this) inside each of those methods ?
A : No, it is not different, by using block (synchronize(this) you can synchronize just part of your code, not the whole method.
For example :

public void m1(){
// some code
synchronized(this){
// thread-safe code
}


问:
Passing part of an url to another function in React
Is there a way for React to take the back of an url user entered and pass it to a function? for example: www.site.com/foobar will pass the foobar to a function.
Essencially what i'm trying to do is to run a check on foobar being in my database inside the checker function, if not there display 404 page not found.</p>

```<code>const NotFound = () => (<h1>404.. This page is not found!</h1>)

class App extends Component {

  checker : function(e){
    if(foobar exists)
      //load page with data
    else
      // {NotFound}
  }

  render() {
    return (
      <Router history={hashHistory}>
        <Route path='/' component={LoginPage} />
        <Route path='*' component={this.checker()} />
      </Router>
    )
  }
}
</code>```

答:
To expand what I had written in my comment -

```<code>class App extends React.Component {
  render() {
    return (
      <Router history={hashHistory}>
          <Route path='/' component={LoginPage} />
          <Route path='/:token' component={EmailValidation} />
      </Router>
    )
  }
}

class EmailValidation extends React.Component {
  state = { checked: false, valid: false }

  componentDidMount = () => {
    checkToken(this.props.params.token).then((valid) => {
      this.setState({ checked: true, valid })
    })
  }

  render() {
    const { checked, valid } = this.state

    return (
      <div>
        { checked
          ? <div>{ valid ? 'valid' : 'invalid' }</div>
          : <div>Checking token...</div> }
      </div>
    )
  }
}
</code>```

this would be a good use case for an HoC which conditionally renders either the component you want or a 404 page - it would remove the binding between the 404 page and the email validate component (which are only sorta-kinda related)

if you're into using libraries, recompose has a bunch of nice helpers which can accomplish something like this for you.

something else you can do is use react-router's onEnter callback/prop although, iirc, you can't directly access props from that callback.

Body:
Is there a way for React to take the back of an url user entered and pass it to a function? for example: www.site.com/foobar will pass the foobar to a function.
Essencially what i'm trying to do is to run a check on foobar being in my database inside the checker function, if not there display 404 page not found.

const NotFound = () => (
404.. This page is not found!
)

class App extends Component {

  checker : function(e){
    if(foobar exists)
      //load page with data
    else
      // {NotFound}
  }

  render() {
    return (
      <Router history={hashHistory}>
        <Route path='/' component={LoginPage} />
        <Route path='*' component={this.checker()} />
      </Router>
    )
  }
}

Body:
To expand what I had written in my comment -

class App extends React.Component {
  render() {
    return (
      <Router history={hashHistory}>
          <Route path='/' component={LoginPage} />
          <Route path='/:token' component={EmailValidation} />
      </Router>
    )
  }
}

class EmailValidation extends React.Component {
  state = { checked: false, valid: false }

  componentDidMount = () => {
    checkToken(this.props.params.token).then((valid) => {
      this.setState({ checked: true, valid })
    })
  }

  render() {
    const { checked, valid } = this.state

    return (
      <div>
        { checked
          ? <div>{ valid ? 'valid' : 'invalid' }</div>
          : <div>Checking token...</div> }
      </div>
    )
  }
}

this would be a good use case for an HoC which conditionally renders either the component you want or a 404 page - it would remove the binding between the 404 page and the email validate component (which are only sorta-kinda related)

if you're into using libraries, recompose has a bunch of nice helpers which can accomplish something like this for you.

something else you can do is use react-router's onEnter callback/prop although, iirc, you can't directly access props from that callback.


问:
Sitemesh or Tiles
Working on the design of a web-application and since it will be a large application so can not reply on jsp include feature so have to use some other solution and for that we came up with Tiles and Sitemesh.

We are new to both of them so any insight from the community will be much appreciated.For additional information we will use Struts2.x as our mail MVC framework with Spring for the other layer(Business)

Which option is better since the application have to do with lots of content and frequent UI changes

答:
From my personal experience, I would recommend Tiles2: Easy and clean integration with Struts2, allows you to reuse avery single component along various templates, the templates composition can be as complex as you want (supports nesting, pattern inheritance, components referencce, etc), etc. As a negative point, I would mention the XML configuration, which for large project can imply kilometric XML files. Anyway, this can be easily avoided segmenting the config files (i.e a file for general templates, and a separate file for the views if each module), but still, you end up having lots of XML config files...

Another point for the use of Tiles2, is that it's an active project (last release published on June 2010), while Sitemesh project seems a little abandoned (last release on March 2009 as seen here).

Anyway, to check the different points of view (Composite View vs. Decorator pattern), you could take a look here and there, and see which approach will fit better your requirements.

Title: Sitemesh or Tiles


问:
Javascript array push
I am trying to iterate through an array and push the contents from the array to another array if they satisfy some basic condition. Really simple stuff. PLease help me.

Getting list of DBs in MongoDB

```<code>>>var dbs = db.getMongo().getDBNames();

>>dbs
[ "admin", "newdb", "newdb2", "local", "test" ]
</code>```

Get array length:

```<code>var arrayLength = dbs.length;
</code>```

Creating an empty array

```<code>var databases = []
</code>```

Pushing to the databases array content from dbs array if content is not equal to 'admin','local' or 'test'

```<code>for (var i = 0 ; i < arrayLength; i++) {
  if (!(dbs[i] == "admin") || !(dbs[i] == "local") || !(dbs[i] == "test")) {
    databases.push(dbs[i]);
  }
}
</code>```

Expecting only "newdb" and "newdb2" to be in the databases array. But everything is being pushed

```<code>>databases
[ "admin", "newdb", "newdb2", "local", "test" ]
</code>```

What's going on here? Only newdb and newdb2 needs to be in the "databases" array.

答:
Easy stuff. :-)</p>

```<code>var dbs = [ "admin", "newdb", "newdb2", "local", "test" ];
var filterShema = new RegExp(/admin|local|test/);
var databases = dbs.filter(function(db) { return !filterShema.test(db); });

> databases
["newdb", "newdb2"]
</code>```

Title: Javascript array push

Body:
I am trying to iterate through an array and push the contents from the array to another array if they satisfy some basic condition. Really simple stuff. PLease help me.

Getting list of DBs in MongoDB

>>var dbs = db.getMongo().getDBNames();

>>dbs
[ "admin", "newdb", "newdb2", "local", "test" ]

Get array length:

var arrayLength = dbs.length;

Creating an empty array

var databases = []

Pushing to the databases array content from dbs array if content is not equal to 'admin','local' or 'test'

for (var i = 0 ; i < arrayLength; i++) {
  if (!(dbs[i] == "admin") || !(dbs[i] == "local") || !(dbs[i] == "test")) {
    databases.push(dbs[i]);
  }
}

Expecting only "newdb" and "newdb2" to be in the databases array. But everything is being pushed

>databases
[ "admin", "newdb", "newdb2", "local", "test" ]

What's going on here? Only newdb and newdb2 needs to be in the "databases" array.

Body:
Easy stuff. :-)

var dbs = [ "admin", "newdb", "newdb2", "local", "test" ];
var filterShema = new RegExp(/admin|local|test/);
var databases = dbs.filter(function(db) { return !filterShema.test(db); });

> databases
["newdb", "newdb2"]


问:
How to test a virtual method defined in an abstract class?
I need to unit-test a virtual method defined in an abstract class. But the base class is abstract, so I can't create an instance of it. What do you recommend me to do?

This is a follow up to the following question: I am thinking about if it is possible to test via an instance of a subclass of the abstract class. Is it a good way? How can I do it?

答:
I'm not sure what your abstract class looks like, but if you have something like:

```<code>public abstract class SomeClass
{
    public abstract bool SomeMethod();

    public abstract int SomeOtherMethod();

    public virtual int MethodYouWantToTest()
    {
        // Method body
    }
}
</code>```

And then, as @David suggested in the comments:

```<code>public class Test : SomeClass
{
    // You don't care about this method - this is just there to make it compile
    public override bool SomeMethod()
    {
        throw new NotImplementedException();
    }

    // You don't care about this method either
    public override int SomeOtherMethod()
    {
        throw new NotImplementedException();
    }

    // Do nothing to MethodYouWantToTest
}
</code>```

Then you just instantiate Test for your unit test:

```<code>[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        SomeClass test = new Test();
        // Insert whatever value you expect here
        Assert.AreEqual(10, test.MethodYouWantToTest());
    }
}
</code>```

Body:
I'm not sure what your abstract class looks like, but if you have something like:

public abstract class SomeClass
{
    public abstract bool SomeMethod();

    public abstract int SomeOtherMethod();

    public virtual int MethodYouWantToTest()
    {
        // Method body
    }
}

And then, as @David suggested in the comments:

public class Test : SomeClass
{
    // You don't care about this method - this is just there to make it compile
    public override bool SomeMethod()
    {
        throw new NotImplementedException();
    }

    // You don't care about this method either
    public override int SomeOtherMethod()
    {
        throw new NotImplementedException();
    }

    // Do nothing to MethodYouWantToTest
}

Then you just instantiate Test for your unit test:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        SomeClass test = new Test();
        // Insert whatever value you expect here
        Assert.AreEqual(10, test.MethodYouWantToTest());
    }
}


答:
Are you looking for ROLLUP?

```<code>SELECT SUM(ep_price)
FROM orders
WHERE date_shipped BETWEEN '2017-04-01' and '2017-04-30'
GROUP BY order_number WITH ROLLUP;
</code>```

This will return on the last row the sum of all groups.

Title: MYSQL SUM & GRAND TOTAL

Body:
I am trying to get a GRAND TOTAL for the following mysql query. But am not having any luck, I am not so good at mysql yet.

SELECT SUM(ep_price)
FROM orders
WHERE date_shipped BETWEEN '2017-04-01' and '2017-04-30'
GROUP BY order_number

Query:

Result:

'152989', '93670.39999999998'
'157669', '159.5'
'165955', '45195'
'166054', '5030'
'166410', '29700'
'167023', '4530'
'167110', '9647.2'
'167152', '56620'
'167477', '46087.14'
'167483', '1690'
'167545', '3295'
'167563', '9144.550000000001'
'167566', '35036.67999999999'
'167736', '2015'
'167853', '1277.5'
'167971', '3695'
'167982', '5690.4'
'168063', '4316.4'
'168101', '3400'
'168330', '4686.9'
'168435', '725'
'168454', '4002.5'
'168455', '6372'
'168477', '1941'
'168590', '3625.5'
'168593', '18560.4'
'168704', '238'
'168706', '119'
'168870', '3340'
'168962', '2800'
'169019', '2050'
'169203', '1940'
'169207', '7500.51'
'169209', '3888.4'
'169212', '10006.5'
'169214', '5580'
'169230', '2742.5'
'169235', '33490.2'
'169371', '12400'
'169413', '671.6'
'169529', '2345'
'169642', '17480'
'169689', '1500'
'169731', '1602.9'
'169835', '567'
'169893', '535.2'
'169895', '431'
'170015', '143.2'
'170031', '431.8'
'170050', '233.7'
'170093', '3465'
'170157', '3070'
'170159', '6040'
'170176', '746.5'
'170260', '3195'
'170318', '4081.06'
'170323', '5400'
'170324', '2865'
'170418', '1815'
'170419', '3984'
'170451', '29775.2'
'170483', '184.7'
'170484', '996.4'
'170486', '1363.8'
'170549', '9975.75'
'170566', '5350'
'170599', '5978.5'
'170600', '5480.42'
'170603', '1309.95'
'170612', '9979.7'
'170619', '2194'
'170620', '32490'
'170661', '4075'
'170721', '1910'
'170735', '4950'
'170756', '19450'
'170758', '9250'
'170763', '285.8'
'170821', '1875'
'170849', '4950'
'170859', '3212.84'
'170865', '132.6'
'170991', '583.1'
'170992', '155.2'
'171108', '181.6'
'171111', '180.9'
'171113', '1481.1'
'171120', '332.8'
'171135', '3869.3199999999997'
'171200', '1175'
'171204', '288.1'
'171205', '261.5'
'171206', '256.6'
'171208', '221.6'
'171209', '815'
'171217', '14903.6'
'171262', '3910'
'171269', '545'
'171272', '273.1'
'171303', '976.25'
'171305', '3600'
'171309', '195.2'
'171310', '16959.13'
'171354', '1215'
'171382', '4500'
'171386', '86.9'
'171407', '511.5'
'171410', '2744.4'
'171412', '5634'
'171416', '5287.5'
'171417', '2063.3999999999996'
'171423', '150.2'
'171513', '4370.4'
'171566', '2747'
'171567', '134.7'
'171670', '2067'
'171676', '348.8'
'171677', '437.5'
'171717', '198'
'171728', '165.5'
'171767', '17430'
'171771', '865.8000000000001'
'171774', '3627.5'
'171831', '13987.5'
'171834', '142.4'
'171836', '1108.2'
'171837', '5199'
'171956', '254.9'
'171958', '1286.8'
'171962', '5586.4'
'171963', '4128.9'
'172067', '1690'
'172068', '5705'
'172069', '893.75'
'172074', '3795'
'172174', '1242'
'172214', '1411.2'
'172215', '568.8'
'172217', '1848.2'
'172219', '1985'
'172220', '22436'
'172244', '166.1'
'172245', '325.9'
'172246', '2395'
'172329', '1885.5'
'172333', '197.8'
'172338', '297.2'
'172341', '1126.5'
'172342', '138.3'
'172352', '388.3'
'172355', '160'
'172382', '244.2'
'172442', '3628.71'
'172448', '1050'
'172452', '213.2'
'172466', '292.6'
'172467', '180'
'172469', '407.1'
'172515', '965'
'172539', '3812.5'
'172602', '1649'
'172631', '514'
'172632', '552.8'
'172834', '250.7'
'172835', '360'
'172836', '0'
'172840', '0'
'172844', '815'
'172846', '2970'
'172902', '4635'
'172997', '143.9'
'172998', '174.7'
'173132', '210'
'173255', '290'
'173260', '565.9'
'173277', '115'
'173545', '672.1'
'173546', '225'
'173562', '215'
'173606', '445.6'
'173611', '228.4'
'173646', '238.61'
'173690', '755'
'173694', '15400'
'173706', '0'
'174028', '855'

So how can I add all of these order_numbers together in a grand total?

I will have multiple entries with the same order_number and ep_price but the distinction is the job_number. That's why I am using the GROUP BY order_number.

Thank you for your help.

Body:
Are you looking for ROLLUP?

SELECT SUM(ep_price)
FROM orders
WHERE date_shipped BETWEEN '2017-04-01' and '2017-04-30'
GROUP BY order_number WITH ROLLUP;

This will return on the last row the sum of all groups.


问:
How to Run 1.7 Javascript
Is there a way to run scripts on a 1.7 javascript engine. The why?
I'm working with a language that is basically a forked version of 1.7 javascript but its inside of a server side box that is very slow and difficult to debug. </p>

答:
An old JavaScript engine running in a server? That might be Rhino, which you can download here, and execute locally. This page says Rhino 1.7R1 implements JavaScript 1.7. Below I used oldest version I found, 1.7R4:

```<code>$ java -jar js.jar
Rhino 1.7 release 4 2012 06 18
js> JSON
[object JSON]
js> JSON.stringify({x:42})
{"x":42}
js> parseInt('00012')
10
js>
</code>```

This one has support for JSON so it's not too old, but it has this quirk from old JS engines where parseInt does not ignore leading zeroes :)

Edit:
What is Demandware:

Demandware Script is based on ECMAScript 3 with added (optional) type specification from the ECMAScript 4 proposal. On top of that the Mozilla's Javascript 1.7 extensions can be used in Demandware script.

I smell Rhino (was developed by Mozilla).

Developing with Demandware:

the way it works is that Demandware  Script is compiled into Java classes using the Rhino engine

I see Rhino :)

They have most certainly exposed functions that won't be available to you when using Rhino alone, but if you want to iterate quickly on custom code that does not depend on those Demandware functions (you could mock the ins & outs), then Rhino could be a good way to test your scripts.

Title: How to Run 1.7 Javascript

Body:
An old JavaScript engine running in a server? That might be Rhino, which you can download here, and execute locally. This page says Rhino 1.7R1 implements JavaScript 1.7. Below I used oldest version I found, 1.7R4:

$ java -jar js.jar
Rhino 1.7 release 4 2012 06 18
js> JSON
[object JSON]
js> JSON.stringify({x:42})
{"x":42}
js> parseInt('00012')
10
js>

This one has support for JSON so it's not too old, but it has this quirk from old JS engines where parseInt does not ignore leading zeroes :)

Edit:
What is Demandware:

Demandware Script is based on ECMAScript 3 with added (optional) type specification from the ECMAScript 4 proposal. On top of that the Mozilla's Javascript 1.7 extensions can be used in Demandware script.

I smell Rhino (was developed by Mozilla).

Developing with Demandware:

the way it works is that Demandware  Script is compiled into Java classes using the Rhino engine

I see Rhino :)

They have most certainly exposed functions that won't be available to you when using Rhino alone, but if you want to iterate quickly on custom code that does not depend on those Demandware functions (you could mock the ins & outs), then Rhino could be a good way to test your scripts.


问:
How should I handle importing third-party libraries within my setup.py script?
I'm developing a Python application and in the process of branching off a release. I've got a PyPI server set up on a company server and I've copied a source distribution of my package onto it.

I checked that the package was being hosted on the server and then tried installing it on my local development machine. I ended up with this output:

$ pip3 install --trusted-host 172.16.1.92 -i http://172.16.1.92:5001/simple/ <my-package>
Collecting <my-package>
  Downloading http://172.16.1.92:5001/packages/<my-package>-0.2.0.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\setup.py", line 9, in <module>
        import appdirs
    ModuleNotFoundError: No module named 'appdirs'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\
```

<p>The reason is that I'm trying to import a third-party library <code>appdirs</code> in my <code>setup.py</code>, which is necessary for me to compute the <code>data_files</code> argument to <code>setup()</code>:</p>

<pre class="lang-py prettyprint-override"><code>try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import os
from collections import defaultdict

import appdirs
from <my-package>.version import __version__ as <my-package>_version

APP_NAME = '<my-app>'
APP_AUTHOR = '<company>'
SYSTEM_COMPONENT_PLUGIN_DIR = os.path.join(appdirs.user_data_dir(APP_NAME, APP_AUTHOR), 'components')

# ...

setup(
    # ...
    data_files=component_files,
)
</code>```

However, I don't have appdirs installed on my local dev machine and I don't expect the end users to have it either.

Is it acceptable to rely on third-party libraries like this in setup.py, and if so what is the recommended approach to using them? Is there a way I can ensure appdirs gets installed before it's imported in setup.py, or should I just document that appdirs is a required package to install my package?

答:
You could use pip to install the package programmatically if the import fails:

```<code>try:
    import appdirs
except ImportError:
    import pip
    pip.main(['install', 'appdirs'])
    import appdirs
</code>```

In some circumstances you may need to use importlib or __import__ to import the package after pip.main or referesh the PATH variable. It could also be worthwhile to include a verification if the user really wants to install that package before installing it.

I used a lot of the examples from "Installing python module within code" and I haven't personally tried used this in setup.py files but it looks like it could be a solution for your question.

Body:
I'm developing a Python application and in the process of branching off a release. I've got a PyPI server set up on a company server and I've copied a source distribution of my package onto it.

I checked that the package was being hosted on the server and then tried installing it on my local development machine. I ended up with this output:

$ pip3 install --trusted-host 172.16.1.92 -i http://172.16.1.92:5001/simple/ <my-package>
Collecting <my-package>
  Downloading http://172.16.1.92:5001/packages/<my-package>-0.2.0.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\setup.py", line 9, in <module>
        import appdirs
    ModuleNotFoundError: No module named 'appdirs'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\

The reason is that I'm trying to import a third-party library appdirs in my setup.py, which is necessary for me to compute the data_files argument to setup():

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import os
from collections import defaultdict

import appdirs
from <my-package>.version import __version__ as <my-package>_version

APP_NAME = '<my-app>'
APP_AUTHOR = '<company>'
SYSTEM_COMPONENT_PLUGIN_DIR = os.path.join(appdirs.user_data_dir(APP_NAME, APP_AUTHOR), 'components')

# ...

setup(
    # ...
    data_files=component_files,
)

However, I don't have appdirs installed on my local dev machine and I don't expect the end users to have it either.

Is it acceptable to rely on third-party libraries like this in setup.py, and if so what is the recommended approach to using them? Is there a way I can ensure appdirs gets installed before it's imported in setup.py, or should I just document that appdirs is a required package to install my package?

Body:
You could use pip to install the package programmatically if the import fails:

try:
    import appdirs
except ImportError:
    import pip
    pip.main(['install', 'appdirs'])
    import appdirs

In some circumstances you may need to use importlib or __import__ to import the package after pip.main or referesh the PATH variable. It could also be worthwhile to include a verification if the user really wants to install that package before installing it.

I used a lot of the examples from "Installing python module within code" and I haven't personally tried used this in setup.py files but it looks like it could be a solution for your question.


问:
How to prevent an action from running if json payload is too large
I want to limit the size of the json payload that is http posted to my action.

How can I limit the size to 1 MB?

If the limit is exceeded, can I return a custom JSON response?

答:
When using body parsers, you can specify the maxLength: cf api

```<code>val maxSize = 1024 * 1024 // 1 MB
def jsonAction = Action(parse.json(maxSize)) { request =>
  val json = request.body
  ...
}
</code>```

If you want to send a custom http error, you can extend the default http error handler. See the documentation

```<code>override def onOtherClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = {
  if (statusCode == Status.REQUEST_ENTITY_TOO_LARGE) {
    Future.successful(Results.EntityTooLarge(Json.obj("error" -> "too large")))
  } else {
    super.onOtherClientError(request, statusCode, message)
  }
}
</code>```

Body:
When using body parsers, you can specify the maxLength: cf api

val maxSize = 1024 * 1024 // 1 MB
def jsonAction = Action(parse.json(maxSize)) { request =>
  val json = request.body
  ...
}

If you want to send a custom http error, you can extend the default http error handler. See the documentation

override def onOtherClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = {
  if (statusCode == Status.REQUEST_ENTITY_TOO_LARGE) {
    Future.successful(Results.EntityTooLarge(Json.obj("error" -> "too large")))
  } else {
    super.onOtherClientError(request, statusCode, message)
  }
}


问:
How to find records that don't have a value in SQL Server 2014?
I have a table 'FinTrans' that has data that looks like this:

```<code>---------------------------------
|AcctID     |TransCode |TransAmt|
---------------------------------
|1234567    |TOLL      |    4:30|
---------------------------------
|1234567    |PYMT      |    5:30|
---------------------------------
|1234567    |RFND      |    1:00|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |RFND      |    4:30|
---------------------------------
|3456789    |TOLL      |    4:30|
---------------------------------
</code>```

And I have an 'Account' Table that gives the account number for each AcctID.

I need to  find Account Numbers that don't have 'PYMT' as the TransCode.

I have tried the following code but clearly that didn't work.

```<code>SELECT DISTINCT(A.AccountNumber)
      ,TransCode
      ,SUM(TransAmt)

  FROM FinTrans F
  INNER JOIN Account A ON F.AcctID = A.AccountID

  WHERE TransCode = 'TOLL'
    AND TransCode != 'PYMT'

  GROUP BY A.AccountNumber, TransCode
</code>```

答:
I think this is the normal way to do NOT HAVING:

```<code>SELECT AccountNumber
FROM Account AS a
WHERE NOT EXISTS (
      SELECT NULL FROM FinTrans AS f
      WHERE a.AccountID = f.AcctID AND
            f.TransCode = "PYMT")
</code>```

Trying to interpret your example instead, I believe you are looking for

```<code>SELECT a.AccountNumber, f.TransCode, SUM(f.TransAmt)
FROM FinTrans AS f
INNER JOIN Account AS a ON f.AcctID = a.AccountID
WHERE f.AcctID IN (SELECT f.AcctID FROM FinTrans AS F GROUP BY f.AcctID
                   HAVING SUM(CASE WHEN f.TransCode = 'PYMT' THEN 1 ELSE 0 END) = 0)
      AND f.TransCode = 'TOLL'
GROUP BY f.AcctID
</code>```

Another option using the first method of filtering the groups would be

```<code>SELECT a.AccountNumber, f.TransCode, SUM(f.TransAmt)
FROM FinTrans AS f
INNER JOIN Account AS a ON f.AcctID = a.AccountID
WHERE f.AcctID IN (SELECT AcctID FROM FinTrans AS f
                   WHERE NOT EXISTS (SELECT NULL FROM FinTrans AS f2
                                     WHERE f.AcctID = f2.AcctID AND f2.TransCode = "PYMT"))
                         AND f.TransCode = 'TOLL'
GROUP BY f.AcctID;
</code>```

Body:
I have a table 'FinTrans' that has data that looks like this:

---------------------------------
|AcctID     |TransCode |TransAmt|
---------------------------------
|1234567    |TOLL      |    4:30|
---------------------------------
|1234567    |PYMT      |    5:30|
---------------------------------
|1234567    |RFND      |    1:00|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |RFND      |    4:30|
---------------------------------
|3456789    |TOLL      |    4:30|
---------------------------------

And I have an 'Account' Table that gives the account number for each AcctID.

I need to  find Account Numbers that don't have 'PYMT' as the TransCode.

I have tried the following code but clearly that didn't work.

SELECT DISTINCT(A.AccountNumber)
      ,TransCode
      ,SUM(TransAmt)

  FROM FinTrans F
  INNER JOIN Account A ON F.AcctID = A.AccountID

  WHERE TransCode = 'TOLL'
    AND TransCode != 'PYMT'

  GROUP BY A.AccountNumber, TransCode

Body:
I think this is the normal way to do NOT HAVING:

SELECT AccountNumber
FROM Account AS a
WHERE NOT EXISTS (
      SELECT NULL FROM FinTrans AS f
      WHERE a.AccountID = f.AcctID AND
            f.TransCode = "PYMT")

Trying to interpret your example instead, I believe you are looking for

SELECT a.AccountNumber, f.TransCode, SUM(f.TransAmt)
FROM FinTrans AS f
INNER JOIN Account AS a ON f.AcctID = a.AccountID
WHERE f.AcctID IN (SELECT f.AcctID FROM FinTrans AS F GROUP BY f.AcctID
                   HAVING SUM(CASE WHEN f.TransCode = 'PYMT' THEN 1 ELSE 0 END) = 0)
      AND f.TransCode = 'TOLL'
GROUP BY f.AcctID

Another option using the first method of filtering the groups would be

SELECT a.AccountNumber, f.TransCode, SUM(f.TransAmt)
FROM FinTrans AS f
INNER JOIN Account AS a ON f.AcctID = a.AccountID
WHERE f.AcctID IN (SELECT AcctID FROM FinTrans AS f
                   WHERE NOT EXISTS (SELECT NULL FROM FinTrans AS f2
                                     WHERE f.AcctID = f2.AcctID AND f2.TransCode = "PYMT"))
                         AND f.TransCode = 'TOLL'
GROUP BY f.AcctID;


答:
I did not see it mentioned, but I suggest looking into Array.prototype.filter. This creates the second array for you, and also manages the iteration over the values of the first array. I would also avoid a big set of conditions, and just rely on Array.prototype.includes to do the work for you.

```<code>var dbs = ["admin", "newdb", "newdb2", "local", "test"];
var unwantedValues = ["admin", "local", "test"];
var databases = dbs.filter(function(value) {
  return !unwantedValues.includes(value);
});
</code>```

Edit, you could also think of this as creating a complement, like in math.

```<code>// Create this as a utility function in your code
// Return a new array object that contains all values from arrayA
// that are not in arrayB
function complement(arrayA, arrayB) {
  return arrayA.filter(function(value) {
    return !arrayB.includes(value);
  });
}

// Then call it
var databases = complement(dbs, unwantedValuesArray);
</code>```

Title: Javascript array push

Body:
I did not see it mentioned, but I suggest looking into Array.prototype.filter. This creates the second array for you, and also manages the iteration over the values of the first array. I would also avoid a big set of conditions, and just rely on Array.prototype.includes to do the work for you.

var dbs = ["admin", "newdb", "newdb2", "local", "test"];
var unwantedValues = ["admin", "local", "test"];
var databases = dbs.filter(function(value) {
  return !unwantedValues.includes(value);
});

Edit, you could also think of this as creating a complement, like in math.

// Create this as a utility function in your code
// Return a new array object that contains all values from arrayA
// that are not in arrayB
function complement(arrayA, arrayB) {
  return arrayA.filter(function(value) {
    return !arrayB.includes(value);
  });
}

// Then call it
var databases = complement(dbs, unwantedValuesArray);


答:
String.split() has some very surprising semantics, and it's rarely what you want. You should prefer StringUtils (or Guava's Splitter, discussed in the previous link).

Your specific issue is that String.split() takes a regular expression, while StringUtils.split() uses each character as a separate token. You should use StringUtils.splitByWholeSeparator() to split on the contents of the full string.

```<code>StringUtils.splitByWholeSeparator(str, "__|__");
</code>```

Title: String.split vs StringUtils.split in Java gives different results

Body:
Consider a string like below with delimiter __|__.

String str = "a_b__|__c_d";

str.split("__\\|__") gives 2 splits a_b and c_d
StringUtils.split(str, "__|__") or StringUtils.split(str, "__\\|__") gives 4 splits a, b, c, d which is not desired.

Is there any way to make StringUtils.split() to give same results String.split()?

Body:
String.split() has some very surprising semantics, and it's rarely what you want. You should prefer StringUtils (or Guava's Splitter, discussed in the previous link).

Your specific issue is that String.split() takes a regular expression, while StringUtils.split() uses each character as a separate token. You should use StringUtils.splitByWholeSeparator() to split on the contents of the full string.

StringUtils.splitByWholeSeparator(str, "__|__");


问:
How to upload two images into two fields using codeigniter
I want to upload two or more pictures using one form in separate fields into database using Codeigniter.

but here only one is uploading .. can anyone please  help me with it..

My controller

```

class Products extends CI_Controller {

       public function __construct()
        {
                // Call the CI_Model constructor
                parent::__construct();

                $this->load->model('Product_model');

        }

    public function save()
            {
                    $config['upload_path']          = './uploads/';
                    $config['allowed_types']        = 'jpg|png';
                    $config['max_size']             = 5024;
                    $config['encrypt_name']         =TRUE;

                    $this->load->library('upload', $config);

                    if ( ! $this->upload->do_upload('userfile'))
                    {
                            $error = array('error' => $this->upload->display_errors());

                            echo var_dump($error ); die;
                    }
                    else
                    {

                        $file_data = array('upload_data' => $this->upload->data());

                    if($this->Product_model->addProducts($file_data))
                    {

                        $this->load->view('success_view');
                    }
                    else
                    {

                        $this->load->view('failure_view');
                    }
                }

```

Here is My model

```

    public function addProducts($file_data)
            {
                    $data=array(
                            'pr_name'=>$_POST['pr_name'],

                            'pr_code'=>$_POST['pr_code'],

                            'photo_file'=>$file_data['upload_data']['file_name'],
                            'photo_file2'=>$file_data['upload_data']['file_name'],

                            );

                    return $this->db->insert('products', $data);
            }

```

Here is my View

```<code>    <div class="container">

<div class="row">
    <div class="col-md-6">
        <form class="form-horizontal" method="post" enctype="multipart/form-data" action="<?php echo site_url('Products/save');?>">
          <div class="form-group">
            <label for="exampleInputEmail1">Product Name</label>
            <input type="text" name="pr_name" class="form-control" id="exampleInputEmail1" placeholder="Product Name">
          </div>
          <div class="form-group">
            <label for="exampleInputPassword1">Product Model</label>
            <input type="text" name="pr_code" class="form-control" id="exampleInputPassword1" placeholder="Product Model">
          </div>

          <div class="form-group">
            <label for="exampleInputFile">Product Image 1</label>
            <input type="file" name="userfile" id="exampleInputFile" >

          </div>

          <div class="form-group">
            <label for="exampleInputFile">Product Image 2</label>
            <input type="file" name="userfile2" id="exampleInputFile" >

          </div>

          <button type="submit" class="btn btn-default">Submit</button>
        </form>
    </div>
</div>
</code>```

My Database

```<code>CREATE TABLE `products` (
  `pr_id` int(5) NOT NULL,
  `pr_name` varchar(200) NOT NULL,
  `pr_code` varchar(200) NOT NULL,
  `photo_file` varchar(255) NOT NULL,
  `photo_file2` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

Please help me to upload into separate database fields as two individual file

答:
Use this function and enjoy ;)</p>

```<code>public function save() {
  $data = array();

  $config['upload_path'] = './uploads/';
  $config['allowed_types'] = 'jpg|png';
  $config['max_size'] = 5024;
  $config['encrypt_name'] = true;

  $this->load->library('upload', $config);

  $data['pr_name'] = $this->input->post('pr_name');
  $data['pr_code'] = $this->input->post('pr_code');

  if (!$this->upload->do_upload('userfile')) {
    $error = array('error' => $this->upload->display_errors());
  } else {
    $fileData = $this->upload->data();
    $data['userfile'] = $fileData['file_name'];
  }

  if (!$this->upload->do_upload('userfile2')) {
    $error = array('error' => $this->upload->display_errors());
  } else {
    $fileData = $this->upload->data();
    $data['userfile2'] = $fileData['file_name'];
  }
  // Verify the data using print_r($data); die;
  $result = $this->Product_model->addProducts($data);
  if ($result) {
    $this->load->view('success_view');
  } else {
    $this->load->view('failure_view');
  }
}
</code>```

Body:
I want to upload two or more pictures using one form in separate fields into database using Codeigniter.

but here only one is uploading .. can anyone please  help me with it..

My controller

class Products extends CI_Controller {

       public function __construct()
        {
                // Call the CI_Model constructor
                parent::__construct();

                $this->load->model('Product_model');

        }

    public function save()
            {
                    $config['upload_path']          = './uploads/';
                    $config['allowed_types']        = 'jpg|png';
                    $config['max_size']             = 5024;
                    $config['encrypt_name']         =TRUE;

                    $this->load->library('upload', $config);

                    if ( ! $this->upload->do_upload('userfile'))
                    {
                            $error = array('error' => $this->upload->display_errors());

                            echo var_dump($error ); die;
                    }
                    else
                    {

                        $file_data = array('upload_data' => $this->upload->data());

                    if($this->Product_model->addProducts($file_data))
                    {

                        $this->load->view('success_view');
                    }
                    else
                    {

                        $this->load->view('failure_view');
                    }
                }

Here is My model

    public function addProducts($file_data)
            {
                    $data=array(
                            'pr_name'=>$_POST['pr_name'],

                            'pr_code'=>$_POST['pr_code'],

                            'photo_file'=>$file_data['upload_data']['file_name'],
                            'photo_file2'=>$file_data['upload_data']['file_name'],

                            );

                    return $this->db->insert('products', $data);
            }

Here is my View

        <form class="form-horizontal" method="post" enctype="multipart/form-data" action="<?php echo site_url('Products/save');?>">

            Product Name
            <input type="text" name="pr_name" class="form-control" id="exampleInputEmail1" placeholder="Product Name">

            Product Model
            <input type="text" name="pr_code" class="form-control" id="exampleInputPassword1" placeholder="Product Model">

            Product Image 1
            <input type="file" name="userfile" id="exampleInputFile" >

            Product Image 2
            <input type="file" name="userfile2" id="exampleInputFile" >

          <button type="submit" class="btn btn-default">Submit</button>
        </form>

My Database

CREATE TABLE `products` (
  `pr_id` int(5) NOT NULL,
  `pr_name` varchar(200) NOT NULL,
  `pr_code` varchar(200) NOT NULL,
  `photo_file` varchar(255) NOT NULL,
  `photo_file2` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Please help me to upload into separate database fields as two individual file

Body:
Use this function and enjoy ;)

public function save() {
  $data = array();

  $config['upload_path'] = './uploads/';
  $config['allowed_types'] = 'jpg|png';
  $config['max_size'] = 5024;
  $config['encrypt_name'] = true;

  $this->load->library('upload', $config);

  $data['pr_name'] = $this->input->post('pr_name');
  $data['pr_code'] = $this->input->post('pr_code');

  if (!$this->upload->do_upload('userfile')) {
    $error = array('error' => $this->upload->display_errors());
  } else {
    $fileData = $this->upload->data();
    $data['userfile'] = $fileData['file_name'];
  }

  if (!$this->upload->do_upload('userfile2')) {
    $error = array('error' => $this->upload->display_errors());
  } else {
    $fileData = $this->upload->data();
    $data['userfile2'] = $fileData['file_name'];
  }
  // Verify the data using print_r($data); die;
  $result = $this->Product_model->addProducts($data);
  if ($result) {
    $this->load->view('success_view');
  } else {
    $this->load->view('failure_view');
  }
}


答:
There's no rule that says a unit test can't define its own classes.  This is a fairly common practice (at least for me anyway).

Consider the structure of a standard unit test:

```<code>public void TestMethod()
{
    // arrange
    // act
    // assert
}
</code>```

That "arrange" step can include any reasonable actions (without side-effects outside of the test) which set up what you're trying to test.  This can just as easily include creating an instance of a class whose sole purpose is to run the test.  For example, something like this:

```<code>private class TestSubClass : YourAbstractBase { }

public void TestMethod()
{
    // arrange
    var testObj = new TestSubClass();

    // act
    var result = testObj.YourVirtualMethod();

    // assert
    Assert.AreEqual(123, result);
}
</code>```

Title: How to test a virtual method defined in an abstract class?

Body:
I need to unit-test a virtual method defined in an abstract class. But the base class is abstract, so I can't create an instance of it. What do you recommend me to do?

This is a follow up to the following question: I am thinking about if it is possible to test via an instance of a subclass of the abstract class. Is it a good way? How can I do it?

Body:
There's no rule that says a unit test can't define its own classes.  This is a fairly common practice (at least for me anyway).

Consider the structure of a standard unit test:

public void TestMethod()
{
    // arrange
    // act
    // assert
}

That "arrange" step can include any reasonable actions (without side-effects outside of the test) which set up what you're trying to test.  This can just as easily include creating an instance of a class whose sole purpose is to run the test.  For example, something like this:

private class TestSubClass : YourAbstractBase { }

public void TestMethod()
{
    // arrange
    var testObj = new TestSubClass();

    // act
    var result = testObj.YourVirtualMethod();

    // assert
    Assert.AreEqual(123, result);
}


问:
Data validation for data type in each cell using EPplus
I have to ensure that each cell in an excel column contains values of the same data type.

In this sheet the first row contains the column header, therefore the data starts in row 2.

The First column should contain only integer values and the second column should contain strings. How to make sure that all values in the column have the same type or how to use tryparse in this validation?

This is the code which render the data in excel

```<code>for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
   var P = new VPODSettlement();
   P .POs = Convert.ToInt32(settlement.Cells[rowIterator,1].Value);
   P .Am_title = settlement.Cells[rowIterator, 2].Value.toString();
   Ps .Add(P);
}
</code>```

答: There is worksheet.DataValidations class which offers various data validation methods. Applying Excel Datavalidation over a column will not only ensure correct data to be written, will also prevent the excel file from being wrongfully edited by the user or another program.

Body:
I have to ensure that each cell in an excel column contains values of the same data type.

In this sheet the first row contains the column header, therefore the data starts in row 2.

The First column should contain only integer values and the second column should contain strings. How to make sure that all values in the column have the same type or how to use tryparse in this validation?

This is the code which render the data in excel

for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
   var P = new VPODSettlement();
   P .POs = Convert.ToInt32(settlement.Cells[rowIterator,1].Value);
   P .Am_title = settlement.Cells[rowIterator, 2].Value.toString();
   Ps .Add(P);
}


问:
String functions in JPA in toplink (OAS 10.1.3.n)
I am trying the following query:

```<code>SELECT DISTINCT SUBSTRING(c.name, 1, 1) FROM Country c
</code>```

againest toplink that is bundled with Oracle Application Server 10.1.3.3 but I got an error saying:

SUBSTRING token not recognized

The question is, doesn't toplink 10.1.3.n support string functions? (I am sure it is JPA1.0, ain't it?
According to the v1.0 specs, SUBSTRING should be supported, so why toplink 10.1.3.n doesn't include it?

Thanks.

答:
Having functions within the select clause of a JPQL query was not supported by JPA 1.0.  Upgrading to TopLink 11.1.1.3.0 will provide JPA 2.0 functionality and support for functions in the JPQL select clause.

You can always issue native SQL or use a TopLink ReportQuery in TopLink 10.1.3.3

Body:
I am trying the following query:

SELECT DISTINCT SUBSTRING(c.name, 1, 1) FROM Country c

againest toplink that is bundled with Oracle Application Server 10.1.3.3 but I got an error saying:

SUBSTRING token not recognized

The question is, doesn't toplink 10.1.3.n support string functions? (I am sure it is JPA1.0, ain't it?
According to the v1.0 specs, SUBSTRING should be supported, so why toplink 10.1.3.n doesn't include it?

Thanks.


问:
Can I target ES6 with Typescript if I am using babel-polyfill?
I am writing a Typescript / React / Redux application that takes advantage of modern ES6+ features like generators and object spread.

I am currently setting my tsconfig.json target to ES5 and also including babel-polyfill in my application.

Since ES6 is faster than ES5 in most browsers, I would prefer to target ES6 from my Typescript config.  However, I am concerned that I will not be able to support as many browsers.

Does babel-polyfill provide the same level of ES5 support as transpiling to an ES5 target?

答:
Does babel-polyfill provide the same level of ES5 support as transpiling to an ES5 target?

No.

babel-polyfill adds missing ES6 runtime classes and methods. For example, if the browser running your script does not have Promise or Array.prototype.includes, it adds implementations for those into the global scope so that they exist when your code attempts to use them.

It cannot add missing support for ES6 syntax to the browser. If your JavaScript code contains ES6 syntax (e.g. class, ..., or yield), then an ES5 browser will fail to parse your code. No amount of additional JavaScript code at runtime can change how the browser parses your code, so the polyfill doesn't help there.

Bottom-line: if you want to use ES6 syntax and still support ES5 browsers, you must transform your code to ES5 (either by targeting ES5 from TypeScript, or by transforming using Babel).


问:
Google Drive API Auth
I currently have an application that works as follows:

A user clicks a button and authenticates with google in a popup.

The application performs actions on the users google drive account.

Results are shown to the user.

The entire process is client side and written in Javascript.

I want to modify the application so that it works like so:

A user clicks on a button. No popup appears.

The application performs actions on a google drive account that I control and is the same for all users.

Results are shown to the user.

Is this possible? Do I need to set up a service account to do this? Will I need to write this in something other than javascript? I don't understand much of the OAuth stuff that is required by google and some guidance would be much appreciated.

Further notes:

The users that will be using this are limited and can be given permissions if necessary, but I don't want to them have to log in.

答:
You can use either a service account or a regular account. In both cases the JS client will have a stored credential, so be aware of the security implications of this. Using a regular account is probably the more secure since OAuth will validate that the code is being run from a registered origin. However this is marginal. The credential is in the wild and so you should expect the worst. For the steps involved in using a regular account, and some sample JS code to do it, see How do I authorise an app (web or installed) without user intervention? (canonical ?)

Think really hard about the security implications because I suspect that once you do, you'll change your mind about doing this,

Title: Google Drive API Auth


问:
Webscraping an angularjs site
I am attempting to webscrape an angularjs site using beautifulsoup. The site is an angularjs site and completely generated from javascript.

The site is: https://sports.bovada.lv/baseball/mlb/pitcher-props-market-group

I thought I could just use the phantomjs webdriver strategy.
Here is what I have:

```<code>PHANTOMJS_PATH = './phantomjs.exe'
bovadaURL = 'https://sports.bovada.lv/baseball/mlb/pitcher-props-market-group'
driver = webdriver.PhantomJS(PHANTOMJS_PATH)
driver.get(bovadaURL)
driver.set_window_position(0, 0)
driver.set_window_size(100000, 200000)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(15) # wait to load
# now print the response
print(driver.page_source)
</code>```

However, not getting the output desired.. this outputs:

```<code><html><head></head><body></body></html>
</code>```

Any ideas on where to go from here? Running out of ideas..

答:
Have you tried requests? i just tried a quick and dirty script and it got more than  tags.

```<code>#!/usr/bin/python3

import requests, bs4

res = requests.get('https://sports.bovada.lv/baseball/mlb/pitcher-props-market-group')
soup = bs4.BeautifulSoup(res.text,'html.parser')

print(res.text)
</code>```

inserted the print statement to test the response and this is the output:

```<code><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"... more
<!--[if IE]><![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="x-dns-prefetch-control" content="on">... more
<meta name="theme-color" content="#ffffff">
<link href="https://sports.bovada.lv/base... more
etc... much longer html stuff
</code>```

and as for bs4, seems to work smoothly as well, if i just do something fast like looking for all the links (they use <link> tags) then this:

```<code>#!/usr/bin/python3

import requests, bs4

res = requests.get('https://sports.bovada.lv/baseball/mlb/pitcher-props-market-group')

soup = bs4.BeautifulSoup(res.text,'html.parser')
links = soup.find_all('link')

for link in links:
    print(link.attrs['href'])
</code>```

produces the following output:

```<code>>python test.py
//cdn13-a.imagestore.lv
//cdn13-b.imagestore.lv
//cdn13-c.imagestore.lv
https://cdn13-a.imagestore.lv/sites/site10/themes/websites_bovada_theme/favicon.ico
https://cdn13-a.imagestore.lv/static/site10/favicons/apple-icon-57x57.png
https://cdn13-b.imagestore.lv/static/site10/favicons/apple-icon-60x60.png
https://cdn13-b.imagestore.lv/static/site10/favicons/apple-icon-72x72.png
https://cdn13-c.imagestore.lv/static/site10/favicons/apple-icon-76x76.png
https://cdn13-b.imagestore.lv/static/site10/favicons/apple-icon-114x114.png
etc...
</code>```

does that help?

EDIT:
so as before you cant use a headless browser. so you need to use something regular like firefox. But first (if you havent done so already) you need to get the geckodriver, find it here:

https://github.com/mozilla/geckodriver/releases

you need to add this to your PATH.
once thats done you should be able to run selenium on that site and go through bs4 again as usual.

Title: Webscraping an angularjs site

Body:
I am attempting to webscrape an angularjs site using beautifulsoup. The site is an angularjs site and completely generated from javascript.

The site is: https://sports.bovada.lv/baseball/mlb/pitcher-props-market-group

I thought I could just use the phantomjs webdriver strategy.
Here is what I have:

PHANTOMJS_PATH = './phantomjs.exe'
bovadaURL = 'https://sports.bovada.lv/baseball/mlb/pitcher-props-market-group'
driver = webdriver.PhantomJS(PHANTOMJS_PATH)
driver.get(bovadaURL)
driver.set_window_position(0, 0)
driver.set_window_size(100000, 200000)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(15) # wait to load
# now print the response
print(driver.page_source)

However, not getting the output desired.. this outputs:

Any ideas on where to go from here? Running out of ideas..

Body:
Have you tried requests? i just tried a quick and dirty script and it got more than <html><head><body> tags.

#!/usr/bin/python3

import requests, bs4

res = requests.get('https://sports.bovada.lv/baseball/mlb/pitcher-props-market-group')
soup = bs4.BeautifulSoup(res.text,'html.parser')

print(res.text)

inserted the print statement to test the response and this is the output:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"... more
<!--[if IE]><![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="x-dns-prefetch-control" content="on">... more
<meta name="theme-color" content="#ffffff">
<link href="https://sports.bovada.lv/base... more
etc... much longer html stuff

and as for bs4, seems to work smoothly as well, if i just do something fast like looking for all the links (they use <link> tags) then this:

#!/usr/bin/python3

import requests, bs4

res = requests.get('https://sports.bovada.lv/baseball/mlb/pitcher-props-market-group')

soup = bs4.BeautifulSoup(res.text,'html.parser')
links = soup.find_all('link')

for link in links:
    print(link.attrs['href'])

produces the following output:

>python test.py
//cdn13-a.imagestore.lv
//cdn13-b.imagestore.lv
//cdn13-c.imagestore.lv
https://cdn13-a.imagestore.lv/sites/site10/themes/websites_bovada_theme/favicon.ico
https://cdn13-a.imagestore.lv/static/site10/favicons/apple-icon-57x57.png
https://cdn13-b.imagestore.lv/static/site10/favicons/apple-icon-60x60.png
https://cdn13-b.imagestore.lv/static/site10/favicons/apple-icon-72x72.png
https://cdn13-c.imagestore.lv/static/site10/favicons/apple-icon-76x76.png
https://cdn13-b.imagestore.lv/static/site10/favicons/apple-icon-114x114.png
etc...

does that help?

EDIT:
so as before you cant use a headless browser. so you need to use something regular like firefox. But first (if you havent done so already) you need to get the geckodriver, find it here:

https://github.com/mozilla/geckodriver/releases

you need to add this to your PATH.
once thats done you should be able to run selenium on that site and go through bs4 again as usual.


答:
In short, no, babel-polyfill doesn't provide the same level of ES5 support as transpiling. The documentation states that it includes a custom regenerator runtime as well as core-js.

You can check out core-js to see that it contains the polyfills you need. However, the object-spread syntax cannot be polyfilled, only transpiled.

Title: Can I target ES6 with Typescript if I am using babel-polyfill?

Body:
I am writing a Typescript / React / Redux application that takes advantage of modern ES6+ features like generators and object spread.

I am currently setting my tsconfig.json target to ES5 and also including babel-polyfill in my application.

Since ES6 is faster than ES5 in most browsers, I would prefer to target ES6 from my Typescript config.  However, I am concerned that I will not be able to support as many browsers.

Does babel-polyfill provide the same level of ES5 support as transpiling to an ES5 target?


问:
Swift NSTextField text disappears
This questions MIGHT exist on a 6 year old post in objective-c. I haven't found a recent answer or question that works, or one that is written in Swift.

I'm using storyboards and I have subclassed NSTextField. For some reason when I click into the field, the placeholder shows and when I enter text and click out, the text disappears. The text is actually there, because when I click back in, the entered text persists. It seems that it's some type of rendering issue that a layer is covering up the text value? Very strange. I'm using NSTrackingArea and also adding CALayer.

Here's a screenshot of what happens:

Here's my code:

```<code>class NowTextField: NSTextField {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // required nonsense
        let textFieldLayer = CALayer()
        let textFieldRect = NSRect(x: 0, y: 0, width: 120, height: 32)
        let textFieldTrackingArea = NSTrackingArea.init(rect: textFieldRect, options: [NSTrackingAreaOptions.activeInActiveApp, NSTrackingAreaOptions.mouseEnteredAndExited], owner: self, userInfo: nil)
        self.wantsLayer = true
        self.layer = textFieldLayer
        self.addTrackingArea(textFieldTrackingArea)

        // styling
        self.textColor = NSColor.darkGray
        self.layer?.cornerRadius = 4
        self.layer?.backgroundColor = NSColor.white.cgColor
        self.layer?.borderColor = NSColor.lightGray.cgColor
        self.layer?.borderWidth = 2
        self.drawsBackground = false
    }

    override func mouseEntered(with event: NSEvent) {
        self.textColor = NSColor.darkGray
        self.layer?.cornerRadius = 4
        self.layer?.backgroundColor = NSColor.white.cgColor
        self.layer?.borderColor = NSColor.highlightBlue.cgColor
        self.layer?.borderWidth = 2
        self.drawsBackground = false
    }

    override func mouseExited(with event: NSEvent) {
        self.textColor = NSColor.darkGray
        self.layer?.cornerRadius = 4
        self.layer?.backgroundColor = NSColor.white.cgColor
        self.layer?.borderColor = NSColor.lightGray.cgColor
        self.layer?.borderWidth = 2
        self.drawsBackground = false
    }
}
</code>```

答:
I found the answer. I deleted let textFieldLayer = CALayer() as well as self.layer = textFieldLayer as these seemed to be adding an unnecessary layer on top of the text field. Here's my full code for the working version:

```<code>class NowTextField: NSTextField {

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)

    // required nonsense
    let textFieldRect = NSRect(x: 0, y: 0, width: 120, height: 32)
    let textFieldTrackingArea = NSTrackingArea.init(rect: textFieldRect, options: [NSTrackingAreaOptions.activeInActiveApp, NSTrackingAreaOptions.mouseEnteredAndExited], owner: self, userInfo: nil)
    self.wantsLayer = true
    self.addTrackingArea(textFieldTrackingArea)

    // styling
    self.textColor = NSColor.darkGray
    self.layer?.cornerRadius = 4
    self.layer?.backgroundColor = NSColor.white.cgColor
    self.layer?.borderColor = NSColor.lightGray.cgColor
    self.layer?.borderWidth = 2
    self.drawsBackground = false
}

override func mouseEntered(with event: NSEvent) {
    self.textColor = NSColor.darkGray
    self.layer?.cornerRadius = 4
    self.layer?.backgroundColor = NSColor.white.cgColor
    self.layer?.borderColor = NSColor.highlightBlue.cgColor
    self.layer?.borderWidth = 2
    self.drawsBackground = false
}

override func mouseExited(with event: NSEvent) {
    self.textColor = NSColor.darkGray
    self.layer?.cornerRadius = 4
    self.layer?.backgroundColor = NSColor.white.cgColor
    self.layer?.borderColor = NSColor.lightGray.cgColor
    self.layer?.borderWidth = 2
    self.drawsBackground = false
}
</code>```

}

Title: Swift NSTextField text disappears

Body:
This questions MIGHT exist on a 6 year old post in objective-c. I haven't found a recent answer or question that works, or one that is written in Swift.

I'm using storyboards and I have subclassed NSTextField. For some reason when I click into the field, the placeholder shows and when I enter text and click out, the text disappears. The text is actually there, because when I click back in, the entered text persists. It seems that it's some type of rendering issue that a layer is covering up the text value? Very strange. I'm using NSTrackingArea and also adding CALayer.

Here's a screenshot of what happens:

Here's my code:

class NowTextField: NSTextField {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // required nonsense
        let textFieldLayer = CALayer()
        let textFieldRect = NSRect(x: 0, y: 0, width: 120, height: 32)
        let textFieldTrackingArea = NSTrackingArea.init(rect: textFieldRect, options: [NSTrackingAreaOptions.activeInActiveApp, NSTrackingAreaOptions.mouseEnteredAndExited], owner: self, userInfo: nil)
        self.wantsLayer = true
        self.layer = textFieldLayer
        self.addTrackingArea(textFieldTrackingArea)

        // styling
        self.textColor = NSColor.darkGray
        self.layer?.cornerRadius = 4
        self.layer?.backgroundColor = NSColor.white.cgColor
        self.layer?.borderColor = NSColor.lightGray.cgColor
        self.layer?.borderWidth = 2
        self.drawsBackground = false
    }

    override func mouseEntered(with event: NSEvent) {
        self.textColor = NSColor.darkGray
        self.layer?.cornerRadius = 4
        self.layer?.backgroundColor = NSColor.white.cgColor
        self.layer?.borderColor = NSColor.highlightBlue.cgColor
        self.layer?.borderWidth = 2
        self.drawsBackground = false
    }

    override func mouseExited(with event: NSEvent) {
        self.textColor = NSColor.darkGray
        self.layer?.cornerRadius = 4
        self.layer?.backgroundColor = NSColor.white.cgColor
        self.layer?.borderColor = NSColor.lightGray.cgColor
        self.layer?.borderWidth = 2
        self.drawsBackground = false
    }
}

Body:
I found the answer. I deleted let textFieldLayer = CALayer() as well as self.layer = textFieldLayer as these seemed to be adding an unnecessary layer on top of the text field. Here's my full code for the working version:

class NowTextField: NSTextField {

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)

    // required nonsense
    let textFieldRect = NSRect(x: 0, y: 0, width: 120, height: 32)
    let textFieldTrackingArea = NSTrackingArea.init(rect: textFieldRect, options: [NSTrackingAreaOptions.activeInActiveApp, NSTrackingAreaOptions.mouseEnteredAndExited], owner: self, userInfo: nil)
    self.wantsLayer = true
    self.addTrackingArea(textFieldTrackingArea)

    // styling
    self.textColor = NSColor.darkGray
    self.layer?.cornerRadius = 4
    self.layer?.backgroundColor = NSColor.white.cgColor
    self.layer?.borderColor = NSColor.lightGray.cgColor
    self.layer?.borderWidth = 2
    self.drawsBackground = false
}

override func mouseEntered(with event: NSEvent) {
    self.textColor = NSColor.darkGray
    self.layer?.cornerRadius = 4
    self.layer?.backgroundColor = NSColor.white.cgColor
    self.layer?.borderColor = NSColor.highlightBlue.cgColor
    self.layer?.borderWidth = 2
    self.drawsBackground = false
}

override func mouseExited(with event: NSEvent) {
    self.textColor = NSColor.darkGray
    self.layer?.cornerRadius = 4
    self.layer?.backgroundColor = NSColor.white.cgColor
    self.layer?.borderColor = NSColor.lightGray.cgColor
    self.layer?.borderWidth = 2
    self.drawsBackground = false
}

}


问:
Get index in a list based on a condition - C#
To get the first number which is positive from a list of numbers, I can write:

```<code>var FirstPostiveNumber = Values.Where(x => x > 0).FirstOrDefault();
</code>```

how do I also get the index number at which above condition is true?

答:
You can use the Select() override that passes in the index:

```<code>var FirstPositiveNumber = Values
    .Select((x, i) => new { Value = x, Index = i })
    .FirstOrDefault(a => a.Value > 0);

Console.WriteLine("Value is: {0}", FirstPositiveNumber.Value);
Console.WriteLine("Index is: {0}", FirstPositiveNumber.Index);
</code>```

Body:
To get the first number which is positive from a list of numbers, I can write:

var FirstPostiveNumber = Values.Where(x => x > 0).FirstOrDefault();

how do I also get the index number at which above condition is true?

Body:
You can use the Select() override that passes in the index:

var FirstPositiveNumber = Values
    .Select((x, i) => new { Value = x, Index = i })
    .FirstOrDefault(a => a.Value > 0);

Console.WriteLine("Value is: {0}", FirstPositiveNumber.Value);
Console.WriteLine("Index is: {0}", FirstPositiveNumber.Index);


问:
Override read only object within a jasmine unit test
Anyone know how to override properties and functions in a read only objects like window or [htmlelement].style?

Example function to need to test:

```<code>public static getCSSTransitionEvent(element: HTMLElement): string {
    let transitions = {
        'transition': 'transitionend',
        'OTransition': 'oTransitionEnd',
        'MozTransition': 'transitionend',
        'WebkitTransition': 'webkitTransitionEnd'
    };

    for (let transition in transitions) {
        if (element.style[transition] !== undefined ) {
            return transitions[transition];
        }
    }
    return;
}
</code>```

How can I override the transition property in element.style to tests that the function returns undefined at the bottom?

Another example, how do I test this if statement

```<code>function isCryptoAvailable() {
    if (typeof (window.crypto) !== 'undefined' && typeof (window.crypto.getRandomValues) !== 'undefined') {
        return true
    }
    else {
        return false
    }
}
</code>```

答:
This is done with property descriptors. Read-only properties have writable descriptor property set to false. As long as they are configurable, they can be redefined with Object.defineProperty like:

```<code> const cryptoDescriptor = Object.getOwnPropertyDescriptor(window, 'crypto');

 afterEach(() => {
   if (origCryptoDescriptor) {
     delete window.crypto;
     Object.defineProperty(window, 'crypto', cryptoDescriptor);
   }
 });

 it('...', () => {
   expect(origCryptoDescriptor).toBeTruthy();
   expect(origCryptoDescriptor.configurable).toBeTruthy();

   const cryptoMock = ...;
   delete window.crypto;
   window.crypto = cryptoMock;
   ...
 });
</code>```

The descriptor should be restored in afterEach because it will be executed even if test fails. And test will fail if a property is non-configurable. This is possible in some browsers, so a test should be excluded from suite in browsers that are known to fail it.

The same concerns a function that involves non-globals like HTMLElement object, but if it is possible to mock this object entirely instead of mocking its properties, this is the preferable strategy.

Body:
Anyone know how to override properties and functions in a read only objects like window or [htmlelement].style?

Example function to need to test:

public static getCSSTransitionEvent(element: HTMLElement): string {
    let transitions = {
        'transition': 'transitionend',
        'OTransition': 'oTransitionEnd',
        'MozTransition': 'transitionend',
        'WebkitTransition': 'webkitTransitionEnd'
    };

    for (let transition in transitions) {
        if (element.style[transition] !== undefined ) {
            return transitions[transition];
        }
    }
    return;
}

How can I override the transition property in element.style to tests that the function returns undefined at the bottom?

Another example, how do I test this if statement

function isCryptoAvailable() {
    if (typeof (window.crypto) !== 'undefined' && typeof (window.crypto.getRandomValues) !== 'undefined') {
        return true
    }
    else {
        return false
    }
}

Body:
This is done with property descriptors. Read-only properties have writable descriptor property set to false. As long as they are configurable, they can be redefined with Object.defineProperty like:

 const cryptoDescriptor = Object.getOwnPropertyDescriptor(window, 'crypto');

 afterEach(() => {
   if (origCryptoDescriptor) {
     delete window.crypto;
     Object.defineProperty(window, 'crypto', cryptoDescriptor);
   }
 });

 it('...', () => {
   expect(origCryptoDescriptor).toBeTruthy();
   expect(origCryptoDescriptor.configurable).toBeTruthy();

   const cryptoMock = ...;
   delete window.crypto;
   window.crypto = cryptoMock;
   ...
 });

The descriptor should be restored in afterEach because it will be executed even if test fails. And test will fail if a property is non-configurable. This is possible in some browsers, so a test should be excluded from suite in browsers that are known to fail it.

The same concerns a function that involves non-globals like HTMLElement object, but if it is possible to mock this object entirely instead of mocking its properties, this is the preferable strategy.


问:
splitting multiple values in one column into multiple rows R
I have a data frame which for the most part is one observation per row. However, some rows have multiple values:

```<code># A tibble: 3 x 2
          `number`   abilities
             <dbl>       <chr>
1               51       b1261
2               57        d710
3               57 b1301; d550

structure(list(`number` = c(51, 57, 57), abilities = c("b1261",
"d710", "b1301; d550")), .Names = c("number", "abilities"
), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
))
</code>```

I'd like to get the following:

```<code># A tibble: 3 x 2
          `number`   abilities
             <dbl>       <chr>
1               51       b1261
2               57        d710
3               57        d550
4               57       b1301
</code>```

It's straight forward enough to split on the ; but I'm not sure how to easily add a new row, especially as abilities might contain more than 2 values.

This is very similar to: R semicolon delimited a column into rows but doesn't need to remove duplicates

答:
There's a function separate_rows in tidyr to do just that:

```<code>library(tidyr)
## The ";\\s+" means that the separator is a ";" followed by one or more spaces
separate_rows(df,abilities,sep=";\\s+")
  number abilities
   <dbl>     <chr>
1     51     b1261
2     57      d710
3     57     b1301
4     57      d550
</code>```

Body:
I have a data frame which for the most part is one observation per row. However, some rows have multiple values:

# A tibble: 3 x 2
          `number`   abilities
             <dbl>       <chr>
1               51       b1261
2               57        d710
3               57 b1301; d550

structure(list(`number` = c(51, 57, 57), abilities = c("b1261",
"d710", "b1301; d550")), .Names = c("number", "abilities"
), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
))

I'd like to get the following:

# A tibble: 3 x 2
          `number`   abilities
             <dbl>       <chr>
1               51       b1261
2               57        d710
3               57        d550
4               57       b1301

It's straight forward enough to split on the ; but I'm not sure how to easily add a new row, especially as abilities might contain more than 2 values.

This is very similar to: R semicolon delimited a column into rows but doesn't need to remove duplicates

Body:
There's a function separate_rows in tidyr to do just that:

library(tidyr)
## The ";\\s+" means that the separator is a ";" followed by one or more spaces
separate_rows(df,abilities,sep=";\\s+")
  number abilities
   <dbl>     <chr>
1     51     b1261
2     57      d710
3     57     b1301
4     57      d550


答:
dplyr is good for this as it has unnest:

```<code>library(tidyverse)
library(stringr)
df %>%
    mutate(unpacked = str_split(abilities, ";")) %>%
    unnest %>%
    mutate(abilities = str_trim(unpacked))
</code>```

Title: splitting multiple values in one column into multiple rows R

Body:
dplyr is good for this as it has unnest:

library(tidyverse)
library(stringr)
df %>%
    mutate(unpacked = str_split(abilities, ";")) %>%
    unnest %>%
    mutate(abilities = str_trim(unpacked))


问:
Are there alternative methods for saying 'next' in a pl/sql for loop?
So I've got a for loop that processes a list of IDs and has some fairly complex things to do. Without going into all the ugly details, basically this:

```
    DECLARE
      l_selected APEX_APPLICATION_GLOBAL.VC_ARR2;

      ...snip...
    BEGIN

      -- get the list ids
      l_selected := APEX_UTIL.STRING_TO_TABLE(:P4_SELECT_LIST);
      -- process each in a nice loop
      FOR i IN 1..l_selected.count
      LOOP
        -- do some data checking stuff...

        -- here we will look for duplicate entries, so we can noop if duplicate is found
        BEGIN
          SELECT county_id INTO v_dup_check FROM org_county_accountable
          WHERE organization_id = :P4_ID AND county_id = v_county_id;
          -- NEXT;! NOOP;! but there is no next!
        EXCEPTION WHEN NO_DATA_FOUND THEN
          dbms_output.put_line('no dups found, proceeding');
        END;
        -- here we have code we only want to execute if there are no dupes already
        IF v_dup_check IS NULL THEN
          -- if not a duplicate record, proceed...

        ELSE
          -- reset duplicate check variable
          v_dup_check := NULL;
        END;
      END LOOP;
    END;
```

How I normally handle this is by selecting into a value, and then wrap the following code in an IF statement checking to make sure that duplicate check variable is NULL. But it's annoying. I just want to be able to say NEXT; or NOOP; or something. Especially since I already have to catch the NO_DATA_FOUND exception. I suppose I could write a letter to Oracle, but I'm curious how others handle this.

I could also wrap this in a function, too, but I was looking for something a little cleaner/simpler.

答:
Another method is to raise and handle a user-defined exception:

```<code>DECLARE
  l_selected APEX_APPLICATION_GLOBAL.VC_ARR2;
  duplicate_org_county EXCEPTION;

  ...snip...
BEGIN

  -- get the list ids
  l_selected := APEX_UTIL.STRING_TO_TABLE(:P4_SELECT_LIST);
  -- process each in a nice loop
  FOR i IN 1..l_selected.count
  LOOP
    BEGIN
      -- do some data checking stuff...

      -- here we will look for duplicate entries, so we can noop if duplicate is found
      BEGIN
        SELECT county_id INTO v_dup_check FROM org_county_accountable
        WHERE organization_id = :P4_ID AND county_id = v_county_id;
        RAISE duplicate_org_county;
      EXCEPTION WHEN NO_DATA_FOUND THEN
        dbms_output.put_line('no dups found, proceeding');
      END;
      -- here we have code we only want to execute if there are no dupes already

    EXCEPTION
      WHEN duplicate_org_county THEN NULL;
    END;
  END LOOP;
END;
</code>```

I wouldn't normally do this, but if there were half a dozen reasons to jump to the next record, this might be preferable to multiple nested IFs.

OwnerDisplayName: Billy Gray

Body:
So I've got a for loop that processes a list of IDs and has some fairly complex things to do. Without going into all the ugly details, basically this:

    DECLARE
      l_selected APEX_APPLICATION_GLOBAL.VC_ARR2;

      ...snip...
    BEGIN

      -- get the list ids
      l_selected := APEX_UTIL.STRING_TO_TABLE(:P4_SELECT_LIST);
      -- process each in a nice loop
      FOR i IN 1..l_selected.count
      LOOP
        -- do some data checking stuff...

        -- here we will look for duplicate entries, so we can noop if duplicate is found
        BEGIN
          SELECT county_id INTO v_dup_check FROM org_county_accountable
          WHERE organization_id = :P4_ID AND county_id = v_county_id;
          -- NEXT;! NOOP;! but there is no next!
        EXCEPTION WHEN NO_DATA_FOUND THEN
          dbms_output.put_line('no dups found, proceeding');
        END;
        -- here we have code we only want to execute if there are no dupes already
        IF v_dup_check IS NULL THEN
          -- if not a duplicate record, proceed...

        ELSE
          -- reset duplicate check variable
          v_dup_check := NULL;
        END;
      END LOOP;
    END;

How I normally handle this is by selecting into a value, and then wrap the following code in an IF statement checking to make sure that duplicate check variable is NULL. But it's annoying. I just want to be able to say NEXT; or NOOP; or something. Especially since I already have to catch the NO_DATA_FOUND exception. I suppose I could write a letter to Oracle, but I'm curious how others handle this.

I could also wrap this in a function, too, but I was looking for something a little cleaner/simpler.

Body:
Another method is to raise and handle a user-defined exception:

DECLARE
  l_selected APEX_APPLICATION_GLOBAL.VC_ARR2;
  duplicate_org_county EXCEPTION;

  ...snip...
BEGIN

  -- get the list ids
  l_selected := APEX_UTIL.STRING_TO_TABLE(:P4_SELECT_LIST);
  -- process each in a nice loop
  FOR i IN 1..l_selected.count
  LOOP
    BEGIN
      -- do some data checking stuff...

      -- here we will look for duplicate entries, so we can noop if duplicate is found
      BEGIN
        SELECT county_id INTO v_dup_check FROM org_county_accountable
        WHERE organization_id = :P4_ID AND county_id = v_county_id;
        RAISE duplicate_org_county;
      EXCEPTION WHEN NO_DATA_FOUND THEN
        dbms_output.put_line('no dups found, proceeding');
      END;
      -- here we have code we only want to execute if there are no dupes already

    EXCEPTION
      WHEN duplicate_org_county THEN NULL;
    END;
  END LOOP;
END;

I wouldn't normally do this, but if there were half a dozen reasons to jump to the next record, this might be preferable to multiple nested IFs.

OwnerDisplayName: Tony Andrews


问:
Insert into with a sub select * not working
If Table A and B have identical structures (except ID field). In A its autoassigned, but in B it is expecting the value from an insert.

How can I do a INSERT INTO A (select * from B).

What is the quickest, most flexible SQL that can run in a stored proc.

答:
Specify the columns explicitly:</p>

```<code>INSERT INTO TableA (col1, col2)
SELECT col1, col2 FROM TableB
</code>```

Body:
Specify the columns explicitly:

INSERT INTO TableA (col1, col2)
SELECT col1, col2 FROM TableB


问:
Difference between synchronized(this) and few synchronized methods of class
In Programming Interviews Exposed book (Wrox publications), code for Producer consumer problem uses 'synchronized' keyword for each of produce() and consume() methods inside a class called IntBuffer. Is this different than using synchronized(this) inside each of those methods ? The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion. The methods produce and consume should both entirely be synchronized right ?

Code in the book:

```<code>public class IntBuffer
{
    private int index;
    private int[] buffer = new int[8];

    // Function called by producer thread
    public synchronized void produce(int num) {
        while(index == buffer.length - 1) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        buffer[index++] = num;
        notifyAll();
    }

    // Function called by consumer thread
    public synchronized int consume() {
        while(index == 0) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        int ret = buffer[--index];
        notifyAll();
        return ret;
    }
}
</code>```

答:
Is this different than using synchronized(this) inside each of those methods?

No.

The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion.

That's not correct. Both methods are synchronized on the same object, so only one thread can be in either method, unless wait() is called, which it is, which releases the lock.

The methods produce and consume should both entirely be synchronized right?

Yes, and you said they are. Unclear what you are asking here.

Body:
In Programming Interviews Exposed book (Wrox publications), code for Producer consumer problem uses 'synchronized' keyword for each of produce() and consume() methods inside a class called IntBuffer. Is this different than using synchronized(this) inside each of those methods ? The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion. The methods produce and consume should both entirely be synchronized right ?

Code in the book:

public class IntBuffer
{
    private int index;
    private int[] buffer = new int[8];

    // Function called by producer thread
    public synchronized void produce(int num) {
        while(index == buffer.length - 1) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        buffer[index++] = num;
        notifyAll();
    }

    // Function called by consumer thread
    public synchronized int consume() {
        while(index == 0) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        int ret = buffer[--index];
        notifyAll();
        return ret;
    }
}