问:
AutoCompleteTextView adapter issue
I have an AutoCompleteTextView, and depending from the changes in it, it shows the dropdown list with the data from server. Via listener after changing every symbol I make request to the server and take some list.

After that I show that list in AutoCompleteTextView,  in code I do it by this way:

```<code>List<String> list = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
    list.add(jsonArray.getJSONObject(i).getString("title"));
}
String[] cities = list.toArray(new String[list.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DistanceCalculation.this, R.layout.support_simple_spinner_dropdown_item, cities);
AutoCompleteTextView my = (AutoCompleteTextView) myView;
my.setAdapter(adapter);
</code>```

Problem is it oftenly shows only the first element of the list, and after long click it shows the full list. I don understand why its happening.

Sorry for the bad eng, thanks in advance! Also you could check the rest of the code below:

xml part:

```<code><AutoCompleteTextView
 android:id="@+id/from"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_alignParentStart="true"
 android:layout_marginTop="15dp"
 android:background="@drawable/td_inp"
 android:hint="Откуда"
 android:paddingBottom="5dp"
 android:paddingLeft="5dp"
 android:paddingRight="5dp"
 android:paddingTop="5dp"
 android:textColor="#000"
 android:textColorHint="#757575" />
</code>```

AutoCompleteTextView and its listener in onCreate

```<code>tCityFrom = (AutoCompleteTextView) findViewById(R.id.from);
tCityFrom.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) {
        if(s.length() >= 2) load_city(ssid, s.toString(),tCityFrom);
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
</code>```

答:
I assume you want to show AutoComplete suggestions according to what user types. You have to load data from server onTextChanged():

```<code>tCityFrom = (AutoCompleteTextView) findViewById(R.id.from);
tCityFrom.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) { }
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.length() >= 2)
            load_city(ssid, s.toString(),tCityFrom);
   }
});
</code>```

Then declare ArrayList and Adapter globally:

```<code>List<String> list;
ArrayAdapter<String> adapter;
</code>```

In onCreate():

```<code>list = new ArrayList<String>();
adapter = new ArrayAdapter<String>(DistanceCalculation.this, R.layout.support_simple_spinner_dropdown_item, cities);
AutoCompleteTextView my = (AutoCompleteTextView) myView;
my.setAdapter(adapter);
</code>```

Replace your first code snippet of load_city() with below code :

```<code>list.clear();
for (int i = 0; i < jsonArray.length(); i++) {
    list.add(jsonArray.getJSONObject(i).getString("title"));
}
adapter.notifyDataSetChanged();
</code>```

Hope this helps.

Title: AutoCompleteTextView adapter issue

Body:
I have an AutoCompleteTextView, and depending from the changes in it, it shows the dropdown list with the data from server. Via listener after changing every symbol I make request to the server and take some list.

After that I show that list in AutoCompleteTextView,  in code I do it by this way:

List<String> list = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
    list.add(jsonArray.getJSONObject(i).getString("title"));
}
String[] cities = list.toArray(new String[list.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DistanceCalculation.this, R.layout.support_simple_spinner_dropdown_item, cities);
AutoCompleteTextView my = (AutoCompleteTextView) myView;
my.setAdapter(adapter);

Problem is it oftenly shows only the first element of the list, and after long click it shows the full list. I don understand why its happening.

Sorry for the bad eng, thanks in advance! Also you could check the rest of the code below:

xml part:

<AutoCompleteTextView
 android:id="@+id/from"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_alignParentStart="true"
 android:layout_marginTop="15dp"
 android:background="@drawable/td_inp"
 android:hint="Откуда"
 android:paddingBottom="5dp"
 android:paddingLeft="5dp"
 android:paddingRight="5dp"
 android:paddingTop="5dp"
 android:textColor="#000"
 android:textColorHint="#757575" />

AutoCompleteTextView and its listener in onCreate

tCityFrom = (AutoCompleteTextView) findViewById(R.id.from);
tCityFrom.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) {
        if(s.length() >= 2) load_city(ssid, s.toString(),tCityFrom);
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    public void onTextChanged(CharSequence s, int start, int before, int count) {}
});

Body:
I assume you want to show AutoComplete suggestions according to what user types. You have to load data from server onTextChanged():

tCityFrom = (AutoCompleteTextView) findViewById(R.id.from);
tCityFrom.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) { }
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.length() >= 2)
            load_city(ssid, s.toString(),tCityFrom);
   }
});

Then declare ArrayList and Adapter globally:

List<String> list;
ArrayAdapter<String> adapter;

In onCreate():

list = new ArrayList<String>();
adapter = new ArrayAdapter<String>(DistanceCalculation.this, R.layout.support_simple_spinner_dropdown_item, cities);
AutoCompleteTextView my = (AutoCompleteTextView) myView;
my.setAdapter(adapter);

Replace your first code snippet of load_city() with below code :

list.clear();
for (int i = 0; i < jsonArray.length(); i++) {
    list.add(jsonArray.getJSONObject(i).getString("title"));
}
adapter.notifyDataSetChanged();

Hope this helps.


来源: stackexchange

问:
Does Dart support functional programming?
Does Google Dart language allow for functional programming to occur? In particular, are the following features supported?

functions stored as variables (references),

functional currying,

lazy parameters

Other features of functional programming?

It looks like Dart does not support immutable data.

答:
To your last point, immutability, see:

https://github.com/google/built_collection.dart

https://github.com/google/built_value.dart

which provide library and codegen support for immutable collections and "value types". These help bridge the gap between OO and functional programming, for example allowing inline "updates" to immutable values:

```<code>var node = new Node((b) => b
  ..left.left.left.right.left.right.label = 'I’m a leaf!'
  ..left.left.right.right.label = 'I’m also a leaf!');
var updatedNode = node.rebuild((b) => b
  ..left.left.right.right.label = 'I’m not a leaf any more!'
  ..left.left.right.right.right.label = 'I’m the leaf now!');
</code>```

Where "node" and "updatedNode" are both immutable. More detail in this article: built_value for Immutable Object Models.

ContentLicense: CC BY-SA 3.0

Body:
To your last point, immutability, see:

https://github.com/google/built_collection.dart

https://github.com/google/built_value.dart

which provide library and codegen support for immutable collections and "value types". These help bridge the gap between OO and functional programming, for example allowing inline "updates" to immutable values:

var node = new Node((b) => b
  ..left.left.left.right.left.right.label = 'I’m a leaf!'
  ..left.left.right.right.label = 'I’m also a leaf!');
var updatedNode = node.rebuild((b) => b
  ..left.left.right.right.label = 'I’m not a leaf any more!'
  ..left.left.right.right.right.label = 'I’m the leaf now!');

Where "node" and "updatedNode" are both immutable. More detail in this article: built_value for Immutable Object Models.


问:
Polymer : Property 'response' bound to attribute 'last-response' not found in 'properties' for element 'menu-kaart'
I'm working on a project in polymer and while I was busy, I get this error:

Property 'response' bound to attribute 'last-response' not found in 'properties' for element 'menu-kaart'

Since I am new to polymer, I don't know what to do. I searched over the internet and I can't find the solution.

Here is the code:

```<code><link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">

<dom-module id="menu-kaart">

<template>
<style>
  :host {
      display: block;
      background-color: maroon;
      padding: 15px;
      color: deepskyblue;
    }

    body {
      margin: 0px;
    }

    h1 {
      color: antiquewhite;
      text-decoration: none;
    }

    h3, p {
      color: antiquewhite;
    }

    div {
      color: white;
    }
</style>

<iron-ajax
  auto
  url="/cgi-bin/menulezen.py"
  handle-as="json"
  last-response="{{response}}">
  </iron-ajax>
    <h1>Menukaart</h1>
  <template is="dom-repeat" items="{{response}}">
    <div>
        <h3>{{item.Gerecht}}</h3>
        <p>Ingredienten: {{item.Ingredienten}} <br>
        Opmerkingen: {{item.Opmerkingen}}</p>
    </div>
  </template>
</code>```

```<code></dom-module>

<script>
Polymer({
is: 'menu-kaart',
properties: {

}
</script>
</code>```

答:
Try modifying your script tag to

```<code><script>
  Polymer({
    is: 'menu-kaart',
    properties: {
       response: {
          type: Object
       }
    }
</script>
</code>```

I'd also recommend you to upgrade your Polymer version to latest 1.x i.e. 1.8 or something relatively newer as Polymer has done a lot of fixes/changes since 1.3.

Lastly, i'll recommend you to read some documentations or some video tutorials to have a better understanding of Polymer

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a project in polymer and while I was busy, I get this error:

Property 'response' bound to attribute 'last-response' not found in 'properties' for element 'menu-kaart'

Since I am new to polymer, I don't know what to do. I searched over the internet and I can't find the solution.

Here is the code:

<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">

<dom-module id="menu-kaart">

<template>

<iron-ajax
  auto
  url="/cgi-bin/menulezen.py"
  handle-as="json"
  last-response="{{response}}">
  </iron-ajax>

Menukaart

  <template is="dom-repeat" items="{{response}}">

{{item.Gerecht}}

Ingredienten: {{item.Ingredienten}}

        Opmerkingen: {{item.Opmerkingen}}

  </template>

</dom-module>

Body:
Try modifying your script tag to

<script>
  Polymer({
    is: 'menu-kaart',
    properties: {
       response: {
          type: Object
       }
    }
</script>

I'd also recommend you to upgrade your Polymer version to latest 1.x i.e. 1.8 or something relatively newer as Polymer has done a lot of fixes/changes since 1.3.

Lastly, i'll recommend you to read some documentations or some video tutorials to have a better understanding of Polymer


问:
Tweets are not posted using Fabric
I’m trying to post tweets form my android application. After the user authorize my application to use its account, normally the tweet have to be posted automatically but in my case, nothing happened. The authentication part works fine, the problem is in the share part. Using Fabric, this is how I post the tweet:

```<code>TwitterSession session = Twitter.getSessionManager().getActiveSession();
StatusesService statusesService = Twitter.getApiClient(session).getStatusesService();
statusesService.update(message, null, null, null, null, null, null, null, String.valueOf(new Callback<Tweet>() {
@Override
public void success(Result<Tweet> result) {
Log.d("Tweet", "post success");
}
@Override
public void failure(TwitterException e) {
e.printStackTrace();
}
}));
</code>```

When I debug the success and the failure.
I got any error, no exception, but nothing is posted.
What is wrong with what I’m doing?

答:
Try checking this its a lil bit old code</p>

```<code> try {

            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_SUBJECT, "");
            intent.putExtra(Intent.EXTRA_TEXT, "");
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            intent.setType("text/plain");
            intent.setType("image/jpeg");
            intent.setPackage("com.twitter.android");
            startActivity(intent);
        } catch (Exception e) {
            commonAction.showToast("No twitter App Installed in device");
            Log.v("VM", "Exception while sending image on" + "com.twitter.android.PostActivity" + " " + e.getMessage());
        }
</code>```

Title: Tweets are not posted using Fabric

Body:
I’m trying to post tweets form my android application. After the user authorize my application to use its account, normally the tweet have to be posted automatically but in my case, nothing happened. The authentication part works fine, the problem is in the share part. Using Fabric, this is how I post the tweet:

TwitterSession session = Twitter.getSessionManager().getActiveSession();
StatusesService statusesService = Twitter.getApiClient(session).getStatusesService();
statusesService.update(message, null, null, null, null, null, null, null, String.valueOf(new Callback<Tweet>() {
@Override
public void success(Result<Tweet> result) {
Log.d("Tweet", "post success");
}
@Override
public void failure(TwitterException e) {
e.printStackTrace();
}
}));

When I debug the success and the failure.
I got any error, no exception, but nothing is posted.
What is wrong with what I’m doing?

Body:
Try checking this its a lil bit old code

 try {

            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_SUBJECT, "");
            intent.putExtra(Intent.EXTRA_TEXT, "");
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            intent.setType("text/plain");
            intent.setType("image/jpeg");
            intent.setPackage("com.twitter.android");
            startActivity(intent);
        } catch (Exception e) {
            commonAction.showToast("No twitter App Installed in device");
            Log.v("VM", "Exception while sending image on" + "com.twitter.android.PostActivity" + " " + e.getMessage());
        }


问:
Getting new data in DOM without refresh
I have page where I add time range, on button INSERT & SAVE send data to API and from response set data to table. But problem is, my data is not showing dynamically. I need refresh page to see changes. I try to use $watch, but this not working or I doing something wrong. Here is my plunker.

答:
thnx to @Slava Utesinov for starting point. Here is how I make this.
First, for adding new time interval, I use this in $http success. First I push new data to $scope and after I $watch this $scope for change

```<code> $scope.urbanTimeRange.push(data);
 $scope.$watchCollection('urbanTimeRange', function (newValue, oldValue, scope) {
}, true);
</code>```

Also, when I remove time intervals, I use splice method and after $watch for change. Here we see index, I get index from my html where I track selected item in ng-repeat with $index.

This is controller:

```<code>$scope.urbanTimeRange.splice(index, 1);
$scope.$watchCollection('urbanTimeRange', function (newValue, oldValue, scope) {
});
</code>```

This is html

```<code><tr ng-repeat='timeRange in urbanTimeRange track by $index'>
                            <td>{{timeRange.from_time | date:'shortTime'}}</td>
                            <td>{{timeRange.to_time | date:'shortTime'}}</td>
                            <td><angular-smartconfirm confirm="removeRow(timeRange.id, $index)"><i class="fa fa-close"></i></angular-smartconfirm></td>
                        </tr>
</code>```

Title: Getting new data in DOM without refresh

Body:
thnx to @Slava Utesinov for starting point. Here is how I make this.
First, for adding new time interval, I use this in $http success. First I push new data to $scope and after I $watch this $scope for change

 $scope.urbanTimeRange.push(data);
 $scope.$watchCollection('urbanTimeRange', function (newValue, oldValue, scope) {
}, true);

Also, when I remove time intervals, I use splice method and after $watch for change. Here we see index, I get index from my html where I track selected item in ng-repeat with $index.

This is controller:

$scope.urbanTimeRange.splice(index, 1);
$scope.$watchCollection('urbanTimeRange', function (newValue, oldValue, scope) {
});

This is html

<tr ng-repeat='timeRange in urbanTimeRange track by $index'>
                            <td>{{timeRange.from_time | date:'shortTime'}}</td>
                            <td>{{timeRange.to_time | date:'shortTime'}}</td>
                            <td><angular-smartconfirm confirm="removeRow(timeRange.id, $index)"><i class="fa fa-close"></i></angular-smartconfirm></td>
                        </tr>


问:
Argument error in Rails
I am trying to create a new project in Rails. But I am facing following error:

```<code>Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/path_support.rb:25:in `initialize': wrong number of arguments (given 0, expected 1) (ArgumentError)
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:329:in `new'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:329:in `paths'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:352:in `path'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:979:in `dirs'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:831:in `stubs'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:1036:in `find_by_path'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:189:in `try_activate'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:126:in `rescue in require'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:40:in `require'
from <internal:gem_prelude>:6:in `<internal:gem_prelude>'
</code>```

How can I resolve this?

答:
Follow this link if you are new in rails

http://guides.rubyonrails.org/getting_started.html
This is link for how to create rails project and more details here

Title: Argument error in Rails

Body:
I am trying to create a new project in Rails. But I am facing following error:

Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/path_support.rb:25:in `initialize': wrong number of arguments (given 0, expected 1) (ArgumentError)
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:329:in `new'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:329:in `paths'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:352:in `path'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:979:in `dirs'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:831:in `stubs'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:1036:in `find_by_path'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems.rb:189:in `try_activate'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:126:in `rescue in require'
from /Users/c192/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:40:in `require'
from <internal:gem_prelude>:6:in `<internal:gem_prelude>'

How can I resolve this?


问:
Vue2 error 'classList' of null error
So i am writhing a component in Vue. Just a simple navigation. Withing methods i made a active script. i also made a "created" loadfunction script and console the element of it.

It gives me the following error in the console:

```<code>TypeError: Cannot read property 'classList' of null
at VueComponent.created (eval at <anonymous> (app.js:1002), <anonymous>:23:67)
at callHook (eval at <anonymous> (app.js:672), <anonymous>:2275:21)
at VueComponent.Vue._init (eval at <anonymous> (app.js:672), <anonymous>:3758:5)
at new VueComponent (eval at <anonymous> (app.js:672), <anonymous>:3922:12)
at createComponentInstanceForVnode (eval at <anonymous> (app.js:672), <anonymous>:3117:10)
at init (eval at <anonymous> (app.js:672), <anonymous>:2925:45)
at createComponent (eval at <anonymous> (app.js:672), <anonymous>:4656:9)
at createElm (eval at <anonymous> (app.js:672), <anonymous>:4599:9)
at createChildren (eval at <anonymous> (app.js:672), <anonymous>:4724:9)
at createElm (eval at <anonymous> (app.js:672), <anonymous>:4632:9)
</code>```

Weirdly enough when i remove .classList it still gives a null value and not a empty array.

Here is my code for the component (note this is in dutch):

```<code><script>
export default {
    name: 'frontnav',
    data () {
        return {
            aantal: [
                'Aankomende Gasten',
                'In Huis',
                'Vertrekkende Gasten',
                'Dag Gasten'],
            dag: [
                'Vandaag',
                'Morgen',
                'Overmorgen',
                'Deze Week',
                'Volgende Week'],
            active: 'Aankomende Gasten'
        }
    },
    methods: {
        makeActive: function (aantal) {
            this.active = aantal;
            let el = document.querySelector('nav tr a:first-child');
            document.querySelector('.' + item).classList.add('active');
        },
        loadfunction: function () {
           const el = document.querySelector('nav a:first-child');
           el.classList.add('active');
        }
    },
    created () {
       this.loadfunction();
        console.log(document.querySelector('nav tr a:first-child').classList);
    }
}
</code>```

答:
Change created() to mounted().

If you're manipulating DOM, you'll be better wait for it.

Title: Vue2 error 'classList' of null error

Body:
So i am writhing a component in Vue. Just a simple navigation. Withing methods i made a active script. i also made a "created" loadfunction script and console the element of it.

It gives me the following error in the console:

TypeError: Cannot read property 'classList' of null
at VueComponent.created (eval at <anonymous> (app.js:1002), <anonymous>:23:67)
at callHook (eval at <anonymous> (app.js:672), <anonymous>:2275:21)
at VueComponent.Vue._init (eval at <anonymous> (app.js:672), <anonymous>:3758:5)
at new VueComponent (eval at <anonymous> (app.js:672), <anonymous>:3922:12)
at createComponentInstanceForVnode (eval at <anonymous> (app.js:672), <anonymous>:3117:10)
at init (eval at <anonymous> (app.js:672), <anonymous>:2925:45)
at createComponent (eval at <anonymous> (app.js:672), <anonymous>:4656:9)
at createElm (eval at <anonymous> (app.js:672), <anonymous>:4599:9)
at createChildren (eval at <anonymous> (app.js:672), <anonymous>:4724:9)
at createElm (eval at <anonymous> (app.js:672), <anonymous>:4632:9)

Weirdly enough when i remove .classList it still gives a null value and not a empty array.

Here is my code for the component (note this is in dutch):


问:
A good development environment setup for Web2Py
Have been trying out Web2Py for a couple of days now and I decided it to be a keeper. But there is one thing that concerns me a lot and that might be a showstopper in the end. I need a nice development environment & setup I can trust and be productive with. Coming from the MS Visual Studio world I'm looking for something with good autocomplete / intellisense + functions for versioning and deployment.

I did some attempts to edit my code in Eclipse but it needs additional setup to run with autocomplete, and for debugging I dont know if it's possible. (Noticed there was a Django project template in Eclipse which is a bit tempting I must say.)

Wing Ide has a instruction on how to get web2py up and running and I am up to testing that one. Not free, but very cheap compared to much in the Windows world.

I also want a good versioning (hg) setup, and preferably a semi-automatic FTP-deployment-method.

What IDE do Web2Py developers use, and how do your setup look like?

A complete setup script for a project in a good IDE would be awesome! (Just like the installation is, one click to get it running 100%).

Pycharm looks good, perhaps that one can add web2py support  http://youtrack.jetbrains.net/issue/PY-1648

Thanks a lot!

答: Have you considered using fewer tools? Both Python and web2py don't require a whole lot of code to get a lot accomplished. web2py only adds 10 or 15 new function calls (besides the HTML helpers and validators). You might find that Eclipse and other IDEs actually get in the way. Setting up new apps in web2py is simple through the admin system. Since the new app scaffolding copies the welcome app, you can customize new app setup by editing the welcome app. With Mercurial (or Git, Subversion or Bazaar) you can set up a server on your machine or with one of the public sites and either push or pull updates to your production server. Keep it simple, I say.</p>

ContentLicense: CC BY-SA 2.5


问:
Fastest Way To std::vector<Derived> to std::vector<Base>
Here is the test code:

```<code>class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(b);//Compiler Error
    return 0;
}
</code>```

Since std::vector and std::vector is different type, we can't make conversion from one to another.

An optional way can be:

```<code>class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(std::vector<A>(b.begin(), b.end()));
    return 0;
}
</code>```

It acts, but it takes extra copying from B to A. If A or B is a large object, it can be very slow. A better choice is:

```<code>class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(std::vector<A>(std::make_move_iterator(b.begin()), std::make_move_iterator(b.end())));
    return 0;
}
</code>```

Since it just move the iter instead of the whole B class, it take a better performance. But there are some extra cost - If b is a very large vector with huge number of items, iteration also can slow down my code.

So I wonder if there is a way to directly convert std::vector to std::vector without any extra cost?

答:
One approach is to make the vector a template parameter of the Test function. The calling code will remain the same, there is no copying required. </p>

```<code>#include <vector>
#include <iostream>

class A{
public:
    virtual void print() const {
        std::cout << "A" << std::endl;
    }
};
class B : public A{
    virtual void print() const {
        std::cout << "B" << std::endl;
    }
};

template <typename ContainerA>
void Test(const ContainerA& aas)
{
    for(const A& a:aas) {
        a.print();
    }
}

int main()
{
    std::vector<A> a;
    a.push_back(A());
    std::vector<B> b;
    b.push_back(B());
    Test(a);
    Test(b);
    return 0;
}
</code>```

Body:
Here is the test code:

class A{};
class B : public A{};

void Test(const std::vector& a)
{
}

int main()
{
    std::vector a;
    std::vector b;
    Test(a);
    Test(b);//Compiler Error
    return 0;
}

Since std::vector and std::vector is different type, we can't make conversion from one to another.

An optional way can be:

class A{};
class B : public A{};

void Test(const std::vector& a)
{
}

int main()
{
    std::vector a;
    std::vector b;
    Test(a);
    Test(std::vector(b.begin(), b.end()));
    return 0;
}

It acts, but it takes extra copying from B to A. If A or B is a large object, it can be very slow. A better choice is:

class A{};
class B : public A{};

void Test(const std::vector& a)
{
}

int main()
{
    std::vector a;
    std::vector b;
    Test(a);
    Test(std::vector(std::make_move_iterator(b.begin()), std::make_move_iterator(b.end())));
    return 0;
}

Since it just move the iter instead of the whole B class, it take a better performance. But there are some extra cost - If b is a very large vector with huge number of items, iteration also can slow down my code.

So I wonder if there is a way to directly convert std::vector to std::vector without any extra cost?

Body:
One approach is to make the vector a template parameter of the Test function. The calling code will remain the same, there is no copying required.

#include <vector>
#include <iostream>

class A{
public:
    virtual void print() const {
        std::cout << "A" << std::endl;
    }
};
class B : public A{
    virtual void print() const {
        std::cout << "B" << std::endl;
    }
};

template <typename ContainerA>
void Test(const ContainerA& aas)
{
    for(const A& a:aas) {
        a.print();
    }
}

int main()
{
    std::vector<A> a;
    a.push_back(A());
    std::vector<B> b;
    b.push_back(B());
    Test(a);
    Test(b);
    return 0;
}


问:
Can't add Global.asax file to WCF project
I have an webservice made with WCF, used this getting started tutorial: https://msdn.microsoft.com/en-us/library/ms730935(v=vs.110).aspx.

Using Visual Studio 2015 Community.

When using Add Item on the project, and searching for the Global.asax file, I can't find it, it's not in Web>General or anywhere. The only way I could add it is to create the file manually and then adding existing item but enabling the open file window to show all files. Obviously this doesn't work, there is no code behind or anything.

Thanks in advance

答: If i understood our question you can find it under Web with the name of "Global Application Class"


问:
Using Protractor with Firefox or IE
Protractor works fine with Chrome, but I cannot get it to start up Firefox or Internet Explorer.

Windows 7

Node v6.9.1

Snippet from package.json:

```<code>"scripts": {
    ....
    "webdriver-manager-update": "webdriver-manager update --ie",
    "protractor": "protractor protractor.conf.js",
    ...
},
...
"devDependencies": {
    ...
    "protractor": "5.1.1",
    ...
}
</code>```

protractor.conf.js:

```<code>exports.config = {
    capabilities: {
      browserName: "firefox" // or "internet explorer"
    },
    specs: ["target/e2e/**/*.e2e-spec.js"]
};
</code>```

After running npm run webdriver-manager-update, <project-home>\node_modules\protractor\node_modules\webdriver-manager\selenium\ contains the files chromedriver_2.28.exe, geckodriver-v0.15.0.exe and IEDriverServer3.3.0.exe.

When running npm run protractor, I get an error:

```<code>[12:29:45] I/launcher - Running 1 instances of WebDriver
[12:29:45] I/local - Starting selenium standalone server...
[12:29:46] I/local - Selenium standalone server started at http://192.168.213.25:62661/wd/hub
[12:29:46] E/launcher - The path to the driver executable must be set by the webdriver.gecko.driver system property
</code>```

(for IE, it refers to the webdriver.ie.driver system property)

After lots of googling, I tried the following fixes:

a) Add <project-home>\node_modules\protractor\node_modules\webdriver-manager\selenium\ to the system environment variable Path. This seems to make no difference.

b) Add the following line to protractor.conf.js:

```<code>seleniumArgs: ["-Dwebdriver.gecko.driver=<project-home>\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\geckodriver-v0.15.0.exe"],
</code>```

Now npm run protractor yields:

```<code>[12:40:35] I/launcher - Running 1 instances of WebDriver
[12:40:35] I/local - Starting selenium standalone server...
[12:40:35] E/launcher - Error: Error: Server terminated early with status 1
    at Error (native)
    at earlyTermination.catch.e (<project-home>\node_modules\selenium-webdriver\remote\index.js:252:52)
    at process._tickCallback (internal/process/next_tick.js:103:7)
[12:40:35] E/launcher - Process exited with error code 100
</code>```

(analoguous behavior with IE)

My search results suggest I am not the only one having this problem, but unfortunately, I did not discover a solution.

答:
Finally I found the solution in an answer by Nick Tomlin:

Its is not seleniumArgs you need to set, but localSeleniumStandaloneOpts.jvmArgs. So, in protractor.conf.js, write:

```<code>localSeleniumStandaloneOpts: {
    jvmArgs: ["-Dwebdriver.gecko.driver=<project-home>\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\geckodriver-v0.15.0.exe"]
  },
</code>```

(analoguous for IE)

Title: Using Protractor with Firefox or IE

Body:
Protractor works fine with Chrome, but I cannot get it to start up Firefox or Internet Explorer.

Windows 7

Node v6.9.1

Snippet from package.json:

"scripts": {
    ....
    "webdriver-manager-update": "webdriver-manager update --ie",
    "protractor": "protractor protractor.conf.js",
    ...
},
...
"devDependencies": {
    ...
    "protractor": "5.1.1",
    ...
}

protractor.conf.js:

exports.config = {
    capabilities: {
      browserName: "firefox" // or "internet explorer"
    },
    specs: ["target/e2e/**/*.e2e-spec.js"]
};

After running npm run webdriver-manager-update, <project-home>\node_modules\protractor\node_modules\webdriver-manager\selenium\ contains the files chromedriver_2.28.exe, geckodriver-v0.15.0.exe and IEDriverServer3.3.0.exe.

When running npm run protractor, I get an error:

[12:29:45] I/launcher - Running 1 instances of WebDriver
[12:29:45] I/local - Starting selenium standalone server...
[12:29:46] I/local - Selenium standalone server started at http://192.168.213.25:62661/wd/hub
[12:29:46] E/launcher - The path to the driver executable must be set by the webdriver.gecko.driver system property

(for IE, it refers to the webdriver.ie.driver system property)

After lots of googling, I tried the following fixes:

a) Add <project-home>\node_modules\protractor\node_modules\webdriver-manager\selenium\ to the system environment variable Path. This seems to make no difference.

b) Add the following line to protractor.conf.js:

seleniumArgs: ["-Dwebdriver.gecko.driver=<project-home>\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\geckodriver-v0.15.0.exe"],

Now npm run protractor yields:

[12:40:35] I/launcher - Running 1 instances of WebDriver
[12:40:35] I/local - Starting selenium standalone server...
[12:40:35] E/launcher - Error: Error: Server terminated early with status 1
    at Error (native)
    at earlyTermination.catch.e (<project-home>\node_modules\selenium-webdriver\remote\index.js:252:52)
    at process._tickCallback (internal/process/next_tick.js:103:7)
[12:40:35] E/launcher - Process exited with error code 100

(analoguous behavior with IE)

My search results suggest I am not the only one having this problem, but unfortunately, I did not discover a solution.

Body:
Finally I found the solution in an answer by Nick Tomlin:

Its is not seleniumArgs you need to set, but localSeleniumStandaloneOpts.jvmArgs. So, in protractor.conf.js, write:

localSeleniumStandaloneOpts: {
    jvmArgs: ["-Dwebdriver.gecko.driver=<project-home>\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\geckodriver-v0.15.0.exe"]
  },

(analoguous for IE)


问:
htaccess redirect based on specific keyword
I really need to redirect this below URL based on "index/1992" keyword.

http://www.goldcoasttouristparks.com.au/burleighbeach-parkhome/obookings3/Search/index/1992/1?A=&D=&Ad=Adults&C=Children&I=Infants

to redirect http://www.goldcoasttouristparks.com.au/burleighbeach-parkhome/

答:
Put the below htaccess rule at the below of you .htaccess file if any else create a new .htacees file</p>

```<code>RewriteRule (index/1992) /burleighbeach-parkhome/ [R,301,L]
</code>```

Body:
Put the below htaccess rule at the below of you .htaccess file if any else create a new .htacees file

RewriteRule (index/1992) /burleighbeach-parkhome/ [R,301,L]


问:
Do I need a thread in a boot_completed and startForeground started service?
I'm starting my service with the BOOT_COMPLETED broadcast and then bring it to the front with startForeground. Using it in a closed system, so it won't bother any other apps. Anyhow, I have three questions that are pretty similar to each other :-) , they are:

I usually make a thread inside my services, but do I need to do that in this case? Which thread is it blocking sins it's starting at boot-up? The UI-thread?

If I start a service with startForeground and I start a thread in that service, will the thread also be on foreground?

Will every service/activity that I start from the service (that's on foreground) automatically also be on foreground?

Thanks!

答:
1.) Activities and services ALWAYS run in the UI thread.

2.) Threads have no notion of foreground or background. They're not tied to your activity, they're tied to your process.

3.) What do you think foreground means? All that does it make it a slightly higher priority for android to keep alive if it runs out of memory.


问:
Error in class.phpmailer.php
I am using the phpmailer api to send mails in a joomla site with the RSForm! Pro 1.52.9 component.

All was working ok but today I start to getting the following error when summiting a form build with the RSForm component:

```<code>   PHP Fatal error:  Only variables can be passed by reference in .../libraries/vendor/phpmailer/phpmailer/class.phpmailer.php on line 1182
</code>```

I am using joomla 3.6 and my php version is php 5.3

答: The problem was resolved by changing the php version to 5.6.</p>

Title: Error in class.phpmailer.php

Body:
I am using the phpmailer api to send mails in a joomla site with the RSForm! Pro 1.52.9 component.

All was working ok but today I start to getting the following error when summiting a form build with the RSForm component:

   PHP Fatal error:  Only variables can be passed by reference in .../libraries/vendor/phpmailer/phpmailer/class.phpmailer.php on line 1182

I am using joomla 3.6 and my php version is php 5.3


问:
Spark scala error
hey i tried to use spark with scala. When i try this code

```<code>    object d29 {
    def main(args: Array[String]){
    val name : String ="myspark"
    val master : String ="local[1]"
    val conf : SparkConf = new SparkConf().setAppName(name).setMaster(master)
    val  spContext : JavaSparkContext = new JavaSparkContext(conf)
    val file = spContext.textFile("zed/text.csv")
    val mapped = file.map(s=>s.length)
    }
}
</code>```

i got this error for the s : missing parameter type

thank you

答:
If you are using Scala, then do not create a JavaSparkContext. Use SparkContext instead :

```<code>val spContext: SparkContext = new SparkContext(conf)
</code>```

Then your code will work.

If you are using Spark 2, use the new SparkSession instead of SparkContext.

Title: Spark scala error

Body:
hey i tried to use spark with scala. When i try this code

    object d29 {
    def main(args: Array[String]){
    val name : String ="myspark"
    val master : String ="local[1]"
    val conf : SparkConf = new SparkConf().setAppName(name).setMaster(master)
    val  spContext : JavaSparkContext = new JavaSparkContext(conf)
    val file = spContext.textFile("zed/text.csv")
    val mapped = file.map(s=>s.length)
    }
}

i got this error for the s : missing parameter type

thank you

Body:
If you are using Scala, then do not create a JavaSparkContext. Use SparkContext instead :

val spContext: SparkContext = new SparkContext(conf)

Then your code will work.

If you are using Spark 2, use the new SparkSession instead of SparkContext.


问:
Identifier expected but integer literal found
I got this problem when writing a recursive function that calculates the number of points where two general functions f1 and f2 are equal(Assuming only Integer values).

```<code>    object X1 {
    def numEqual(f1:Int=>Int,f2:Int=>Int)(a:Int,b:Int):Int=
    if(a>b) 0
    else f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b):0+numEqual(f1,f2)(a+1,b)
</code>```

And this is what compiler says :

X1.scala:5: error: identifier expected but integer literal found.
              f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b) : 0+numEqual(f1,f2)(a+1,b)
                                                                  ^
  one error found.

Thank you!

答:
The if construct in Scala is an expression. As the others already said, there's no ternary operator because there's no need for it - the if being already an expression.

I rewrote your function to a tail-recursive version (to avoid StackOverflowErrors), let's see how it looks:

@tailrec def numEqual(f1: Int => Int, f2: Int => Int)(a: Int, b: Int, res: Int = 0): Int =
  if (a > b) res
  else {
    val inc = if (f1(a) == f2(a)) 1 else 0
    numEqual(f1, f2)(a + 1, b, res + inc)
  }
```

Notice how the result of the if expression is assigned to inc - here you would normally use the ternary operator. Anyway, I hope this helps you.

Body:
I got this problem when writing a recursive function that calculates the number of points where two general functions f1 and f2 are equal(Assuming only Integer values).

    object X1 {
    def numEqual(f1:Int=>Int,f2:Int=>Int)(a:Int,b:Int):Int=
    if(a>b) 0
    else f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b):0+numEqual(f1,f2)(a+1,b)

And this is what compiler says :

X1.scala:5: error: identifier expected but integer literal found.
              f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b) : 0+numEqual(f1,f2)(a+1,b)
                                                                  ^
  one error found.

Thank you!

Body:
The if construct in Scala is an expression. As the others already said, there's no ternary operator because there's no need for it - the if being already an expression.

I rewrote your function to a tail-recursive version (to avoid StackOverflowErrors), let's see how it looks:

@tailrec def numEqual(f1: Int => Int, f2: Int => Int)(a: Int, b: Int, res: Int = 0): Int =
  if (a > b) res
  else {
    val inc = if (f1(a) == f2(a)) 1 else 0
    numEqual(f1, f2)(a + 1, b, res + inc)
  }

Notice how the result of the if expression is assigned to inc - here you would normally use the ternary operator. Anyway, I hope this helps you.


问:
finding and stripping a symbol in PySpark RDD
I have a bunch of Csv files that I'm loading into a PySpark RDD. They each have a double header which I've able to successfully remove after concatenating all the Csvs. The aim is to eventually have a nice clean Dataframe.

Theres a date time column in the original Csvs thats causing me issues however, here is what some of the values look like;

```<code>2017/02/15-9:54:
2017/02/15-9:56:
2017/02/15-9:58:
2017/02/15-10:00
2017/02/15-10:02
</code>```

I want to be able to strip the ':' when it happens to be the last character or format to a proper datetime.

Heres what my data looks like :

```<code>u'2017/02/15-11:28,name,99.77341,1.5625,53,14.44655,53,1596.375,1.436081,0.4915466,0.1103516,9.31524,3.125,2.910973,4.6875,53,46,1596.375,5.380112',
u'2017/02/16-7:48:,name,99.7734,4.6875,49,14.51247,49,1596.374,1.347595,0.4937897,0.1104431,9.318081,2.34375,2.90873,0,49,43,1596.374,5.213211,'
</code>```

I've tired:

```<code>rdd2= rdd.map(lambda x: x.replace('%Y/%m/%d-\d{2}:\d{2}:' , '%Y/%m/%d-\d{2}:\d{2}:\d{2}'))

rdd2 = rdd.map(lambda x: x.rstrip(':'))
</code>```

Any help would be appreciated

答:
If the datetime variable is the first column, you can do:

```<code>rdd.map(lambda x: (x[0].rstrip('\:'), x[1:])).map(lambda x: (x[0],) + x[1])
</code>```

Body:
I have a bunch of Csv files that I'm loading into a PySpark RDD. They each have a double header which I've able to successfully remove after concatenating all the Csvs. The aim is to eventually have a nice clean Dataframe.

Theres a date time column in the original Csvs thats causing me issues however, here is what some of the values look like;

2017/02/15-9:54:
2017/02/15-9:56:
2017/02/15-9:58:
2017/02/15-10:00
2017/02/15-10:02

I want to be able to strip the ':' when it happens to be the last character or format to a proper datetime.

Heres what my data looks like :

u'2017/02/15-11:28,name,99.77341,1.5625,53,14.44655,53,1596.375,1.436081,0.4915466,0.1103516,9.31524,3.125,2.910973,4.6875,53,46,1596.375,5.380112',
u'2017/02/16-7:48:,name,99.7734,4.6875,49,14.51247,49,1596.374,1.347595,0.4937897,0.1104431,9.318081,2.34375,2.90873,0,49,43,1596.374,5.213211,'

I've tired:

rdd2= rdd.map(lambda x: x.replace('%Y/%m/%d-\d{2}:\d{2}:' , '%Y/%m/%d-\d{2}:\d{2}:\d{2}'))

rdd2 = rdd.map(lambda x: x.rstrip(':'))

Any help would be appreciated

Body:
If the datetime variable is the first column, you can do:

rdd.map(lambda x: (x[0].rstrip('\:'), x[1:])).map(lambda x: (x[0],) + x[1])


问:
Laravel get file content
```<code>Route::get('marquee', function(){
    echo  File::get('\storage\app\marquee.json');
});
</code>```

I have a json file place inside storage/app

My question is how can I read this content from controller or route?

答:
You can use storage_path()  function for locate the storage folder and then join app folder name like that:

```<code>$path = storage_path() . "/app/marquee.json";
echo  File::get($path);
</code>```

Title: Laravel get file content

Body:
Route::get('marquee', function(){
    echo  File::get('\storage\app\marquee.json');
});

I have a json file place inside storage/app

My question is how can I read this content from controller or route?

Body:
You can use storage_path()  function for locate the storage folder and then join app folder name like that:

$path = storage_path() . "/app/marquee.json";
echo  File::get($path);


问:
How to manually specify class labels in keras flow_from_directory?
Problem: I am training a model for multilabel image recognition. My images are therefore associated with multiple y labels. This is conflicting with the convenient keras method "flow_from_directory" of the ImageDataGenerator, where each image is supposed to be in the folder of the corresponding label (https://keras.io/preprocessing/image/).

Workaround: Currently, I am reading all images into a numpy array and use the "flow" function from there. But this results in heavy memory loads and a slow read-in process.

Question: Is there a way to use the "flow_from_directory" method and to supply manually the (multiple) class labels?

Update: I ended up extending the DirectoryIterator class for the multilabel case. You can now set the attribute "class_mode" to the value "multilabel" and provide a dictionary "multlabel_classes" which maps filenames to their labels. Code: https://github.com/tholor/keras/commit/29ceafca3c4792cb480829c5768510e4bdb489c5

答:
You could write a custom generator class that would read the files in from the directory and apply the labeling.  That custom generator could also take in an ImageDataGenerator instance which would produce the batches using flow().

I am imagining something like this:

```<code>class Generator():

    def __init__(self, X, Y, img_data_gen, batch_size):
        self.X = X
        self.Y = Y  # Maybe a file that has the appropriate label mapping?
        self.img_data_gen = img_data_gen  # The ImageDataGenerator Instance
        self.batch_size = batch_size

    def apply_labels(self):
        # Code to apply labels to each sample based on self.X and self.Y

    def get_next_batch(self):
        """Get the next training batch"""
        self.img_data_gen.flow(self.X, self.Y, self.batch_size)
</code>```

Then simply:

```<code>img_gen = ImageDataGenerator(...)
gen = Generator(X, Y, img_gen, 128)

model.fit_generator(gen.get_next_batch(), ...)
</code>```

*Disclaimer: I haven't actually tested this, but it should work in theory.

Body:
You could write a custom generator class that would read the files in from the directory and apply the labeling.  That custom generator could also take in an ImageDataGenerator instance which would produce the batches using flow().

I am imagining something like this:

class Generator():

    def __init__(self, X, Y, img_data_gen, batch_size):
        self.X = X
        self.Y = Y  # Maybe a file that has the appropriate label mapping?
        self.img_data_gen = img_data_gen  # The ImageDataGenerator Instance
        self.batch_size = batch_size

    def apply_labels(self):
        # Code to apply labels to each sample based on self.X and self.Y

    def get_next_batch(self):
        """Get the next training batch"""
        self.img_data_gen.flow(self.X, self.Y, self.batch_size)

Then simply:

img_gen = ImageDataGenerator(...)
gen = Generator(X, Y, img_gen, 128)

model.fit_generator(gen.get_next_batch(), ...)

*Disclaimer: I haven't actually tested this, but it should work in theory.


答:
Using Storage facade:

```<code>Storage::disk('local')->get('marquee.json');
</code>```

The old way, using File facade (deprecated for Laravel 7):

```<code>File::get(storage_path('app/marquee.json'));
</code>```

Title: Laravel get file content

Body:
Using Storage facade:

Storage::disk('local')->get('marquee.json');

The old way, using File facade (deprecated for Laravel 7):

File::get(storage_path('app/marquee.json'));


问:
Do I really have to write 8 different SQL queries for this?
I'm attempting to write ONE query that will do a COUNT on several columns, group them by their respective column.

Here's the query I have right now:

```<code>SELECT COUNT(*) as total,
COUNT(q3_pay) as q3_pay_total,
COUNT(q3_holidays) as q3_holidays_total,
COUNT(q3_vacation) as q3_vacation_total,
COUNT(q3_sick) as q3_sick_total,
COUNT(q3_insurance) as q3_insurance_total,
COUNT(q3_retirement) as q3_retirement_total,
COUNT(q3_fsa) as q3_fsa_total
FROM exit_responses
</code>```

I need to find two things:

The total number of responses for each column COUNT(column).

The total number of response X for each column COUNT(column[x]) <-- example

Is there any way for me to do this without creating a new sql query for each column?

I currently have other queries that do this such as this one:

```<code>SELECT COUNT(*) as total, q2 FROM exit_responses
GROUP BY q2
</code>```

Thanks, everyone :).

答:
As others have said, please post DDL or table along with some sample rows and the expected output.

Hmm, I don't suppose this is what you want to do?

```<code>select 'Q3'                   as quarter,
       count(*)               as total,
       count(q3_pay)          as q3_pay_total,
       count(q3_holidays)     as q3_holidays_total,
       count(q3_vacation)     as q3_vacation_total,
       count(q3_sick)         as q3_sick_total,
       count(q3_insurance)    as q3_insurance_total,
       count(q3_retirement)   as q3_retirement_total,
       count(q3_fsa)          as q3_fsa_total
  from exit_responses
union all
select 'Q2'                   as quarter,
       count(*)               as total,
       count(q2_pay)          as q2_pay_total,
       count(q2_holidays)     as q2_holidays_total,
       count(q2_vacation)     as q2_vacation_total,
       count(q2_sick)         as q2_sick_total,
       count(q2_insurance)    as q2_insurance_total,
       count(q2_retirement)   as q2_retirement_total,
       count(q2_fsa)          as q2_fsa_total
  from exit_responses
</code>```

Body:
I'm attempting to write ONE query that will do a COUNT on several columns, group them by their respective column.

Here's the query I have right now:

SELECT COUNT(*) as total,
COUNT(q3_pay) as q3_pay_total,
COUNT(q3_holidays) as q3_holidays_total,
COUNT(q3_vacation) as q3_vacation_total,
COUNT(q3_sick) as q3_sick_total,
COUNT(q3_insurance) as q3_insurance_total,
COUNT(q3_retirement) as q3_retirement_total,
COUNT(q3_fsa) as q3_fsa_total
FROM exit_responses

I need to find two things:

The total number of responses for each column COUNT(column).

The total number of response X for each column COUNT(column[x]) <-- example

Is there any way for me to do this without creating a new sql query for each column?

I currently have other queries that do this such as this one:

SELECT COUNT(*) as total, q2 FROM exit_responses
GROUP BY q2

Thanks, everyone :).

Body:
As others have said, please post DDL or table along with some sample rows and the expected output.

Hmm, I don't suppose this is what you want to do?

select 'Q3'                   as quarter,
       count(*)               as total,
       count(q3_pay)          as q3_pay_total,
       count(q3_holidays)     as q3_holidays_total,
       count(q3_vacation)     as q3_vacation_total,
       count(q3_sick)         as q3_sick_total,
       count(q3_insurance)    as q3_insurance_total,
       count(q3_retirement)   as q3_retirement_total,
       count(q3_fsa)          as q3_fsa_total
  from exit_responses
union all
select 'Q2'                   as quarter,
       count(*)               as total,
       count(q2_pay)          as q2_pay_total,
       count(q2_holidays)     as q2_holidays_total,
       count(q2_vacation)     as q2_vacation_total,
       count(q2_sick)         as q2_sick_total,
       count(q2_insurance)    as q2_insurance_total,
       count(q2_retirement)   as q2_retirement_total,
       count(q2_fsa)          as q2_fsa_total
  from exit_responses


答:
just found out that const el = document.querySelector('nav a:first-child');

All making it a collection. :/

it should be

```<code>const el = document.querySelectorAll('nav a:first-child');
</code>```

Title: Vue2 error 'classList' of null error

Body:
So i am writhing a component in Vue. Just a simple navigation. Withing methods i made a active script. i also made a "created" loadfunction script and console the element of it.

It gives me the following error in the console:

TypeError: Cannot read property 'classList' of null
at VueComponent.created (eval at <anonymous> (app.js:1002), <anonymous>:23:67)
at callHook (eval at <anonymous> (app.js:672), <anonymous>:2275:21)
at VueComponent.Vue._init (eval at <anonymous> (app.js:672), <anonymous>:3758:5)
at new VueComponent (eval at <anonymous> (app.js:672), <anonymous>:3922:12)
at createComponentInstanceForVnode (eval at <anonymous> (app.js:672), <anonymous>:3117:10)
at init (eval at <anonymous> (app.js:672), <anonymous>:2925:45)
at createComponent (eval at <anonymous> (app.js:672), <anonymous>:4656:9)
at createElm (eval at <anonymous> (app.js:672), <anonymous>:4599:9)
at createChildren (eval at <anonymous> (app.js:672), <anonymous>:4724:9)
at createElm (eval at <anonymous> (app.js:672), <anonymous>:4632:9)

Weirdly enough when i remove .classList it still gives a null value and not a empty array.

Here is my code for the component (note this is in dutch):

Body:
just found out that const el = document.querySelector('nav a:first-child');

All making it a collection. :/

it should be

const el = document.querySelectorAll('nav a:first-child');


问:
Regexp to select images with whitespaces
Im tried several combinations but it seams to end up by inserting every possible sign.

I have a regexp that looks like

```<code><img[^>]*?src=["']([\w:\\\/\s\S]*[.a-zA-Z]{3,})[^>]*?>
</code>```

I want to select the src part from an image.

Sample URL looks like

```<code>Sample <img alt="foo" src="c:\my-folder\contains.dot\and space\in myImagePath.png" title="bar" >
</code>```

but this selects title as well, I want to stop at the src's end " .

I also tried some more constelations but with same or no result....

Is there a was to stop at " when first " was mached ?

ORIGINAL DATA

Original HTMLCode copied from VS2017 console:

```<code><style>*{font-family: Arial, Helvetica, sans-serif;}</style><p><img src=\"C:\\Users\\JustMe\\Desktop\\de mo1.png\" width=\"1635\" height=\"989\" /></p>\n<p> </p>
</code>```

Code I used originaly:

```<code>using System.Text.RegularExpressions;

...

public List<string[]> FetchLinksFromSource(string htmlSource)
    {
        List<string[]> links = new List<string[]>();

        int i = 1;
        string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
        MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        foreach (Match m in matchesImgSrc)
        {
            string[] matches = new string[3];
            string href = m.Groups[1].Value;
            matches[0] = href;
            matches[1] = new Uri(href).ToString();
            matches[2] = "imageID_" + i++.ToString();
            links.Add(matches);
        }
        return links;
    }
</code>```

This code crashes if image or path has white spaces!

答:
I prefer use \1 for end of src= with the same " or ' in the beginning:

```<code><img[^>]*?src=("|')(.*?)\1[^>]*?>
</code>```

Demo

Body:
Im tried several combinations but it seams to end up by inserting every possible sign.

I have a regexp that looks like

]*?src=["']([\w:\\\/\s\S]*[.a-zA-Z]{3,})[^>]*?>

I want to select the src part from an image.

Sample URL looks like

Sample

but this selects title as well, I want to stop at the src's end " .

I also tried some more constelations but with same or no result....

Is there a was to stop at " when first " was mached ?

ORIGINAL DATA

Original HTMLCode copied from VS2017 console:

\n

Code I used originaly:

using System.Text.RegularExpressions;

...

public List<string[]> FetchLinksFromSource(string htmlSource)
    {
        List<string[]> links = new List<string[]>();

        int i = 1;
        string regexImgSrc = @"]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
        MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        foreach (Match m in matchesImgSrc)
        {
            string[] matches = new string[3];
            string href = m.Groups[1].Value;
            matches[0] = href;
            matches[1] = new Uri(href).ToString();
            matches[2] = "imageID_" + i++.ToString();
            links.Add(matches);
        }
        return links;
    }

This code crashes if image or path has white spaces!

Body:
I prefer use \1 for end of src= with the same " or ' in the beginning:

<img[^>]*?src=("|')(.*?)\1[^>]*?>

Demo


问:
Angular2 Tutorial (Tour of Heroes): Cannot find module 'angular2-in-memory-web-api'
I have followed the Tutorial. After changing app/maint.ts in the Http chapter I get the error when starting the app via command line:

app/main.ts(5,51): error TS2307: Cannot find module 'angular2-in-memory-web-api'.

(Visual Studio Code gives me the same error within main.ts - red wavy underlining.)

Here is my systemjs.config.js:

```<code>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Add package entries for angular packages
  ngPackageNames.forEach(function(pkgName) {
    packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
  });
  var config = {
    map: map,
    packages: packages
  }
  System.config(config);
})(this);
</code>```

Here is my app/main.ts:

```<code>// Imports for loading & configuring the in-memory web api
import { provide }    from '@angular/core';
import { XHRBackend } from '@angular/http';

import { InMemoryBackendService, SEED_DATA } from 'angular2-in-memory-web-api';
import { InMemoryDataService }               from './in-memory-data.service';

// The usual bootstrapping imports
import { bootstrap }      from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent }   from './app.component';

bootstrap(AppComponent, [
    HTTP_PROVIDERS,
    provide(XHRBackend, { useClass: InMemoryBackendService }), // in-mem server
    provide(SEED_DATA,  { useClass: InMemoryDataService })     // in-mem server data
]);
</code>```

答:
I got this error because I was importing InMemoryWebApiModule from angular2-in-memory-web-api I removed the 2. Actually I had two entries in my package.json file; one was angular2-in-memory-web-api and the second wasangular-in-memory-web-api. Using angular-in-memory-web-api solved the problem for me. So your import should be like this:

import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
...
@NgModule({

imports: [
InMemoryWebApiModule.forRoot(InMemoryDataService)
]
})
```

Using cli-angular you need not to change anything regarding system.config.js.

Body:
I have followed the Tutorial. After changing app/maint.ts in the Http chapter I get the error when starting the app via command line:

app/main.ts(5,51): error TS2307: Cannot find module 'angular2-in-memory-web-api'.

(Visual Studio Code gives me the same error within main.ts - red wavy underlining.)

Here is my systemjs.config.js:

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Add package entries for angular packages
  ngPackageNames.forEach(function(pkgName) {
    packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
  });
  var config = {
    map: map,
    packages: packages
  }
  System.config(config);
})(this);

Here is my app/main.ts:

// Imports for loading & configuring the in-memory web api
import { provide }    from '@angular/core';
import { XHRBackend } from '@angular/http';

import { InMemoryBackendService, SEED_DATA } from 'angular2-in-memory-web-api';
import { InMemoryDataService }               from './in-memory-data.service';

// The usual bootstrapping imports
import { bootstrap }      from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent }   from './app.component';

bootstrap(AppComponent, [
    HTTP_PROVIDERS,
    provide(XHRBackend, { useClass: InMemoryBackendService }), // in-mem server
    provide(SEED_DATA,  { useClass: InMemoryDataService })     // in-mem server data
]);

Body:
I got this error because I was importing InMemoryWebApiModule from angular2-in-memory-web-api I removed the 2. Actually I had two entries in my package.json file; one was angular2-in-memory-web-api and the second wasangular-in-memory-web-api. Using angular-in-memory-web-api solved the problem for me. So your import should be like this:

import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
...
@NgModule({

imports: [
InMemoryWebApiModule.forRoot(InMemoryDataService)
]
})

Using cli-angular you need not to change anything regarding system.config.js.


问:
Conditional construct not working in Python regex
I an a newbie in python and I want to use my regex in re.sub. I tried it on regex101 and it works. Somehow when I tried to use it on my python (version 3.6) it doesn't work properly. I get the following warning

bad character in group name '?=[^\t]*' at position 5

This is my code:

```<code>re = r"(?(?=[^\t]*)([\t]+))";
str = 'a            bold, italic,           teletype';
subst = ',';

result = re.sub($re, $subst, $str);
</code>```

答:
I suppose you could do this:

```<code>import re

regex = r'(^\w*?[\t]+)'
s = 'a      bold, italic,           teletype'

def repl(match):
    s = match.group(0)
    return s.rstrip() + ', '

print(re.sub(regex,repl, s))
</code>```

out

```<code>a, bold, italic,            teletype
</code>```

Here we are capturing the beginning of the string through any tabs that may occur after the first word, and passing the match to a callable. The callable removes trailing tabs with rstrip and adds a trailing comma.

Note: if the first tab occurs after the first word, it's not replaced. i.e. 'a bold, italic,           teletype' is left unchanged. Is that what you want?

Body:
I an a newbie in python and I want to use my regex in re.sub. I tried it on regex101 and it works. Somehow when I tried to use it on my python (version 3.6) it doesn't work properly. I get the following warning

bad character in group name '?=[^\t]*' at position 5

This is my code:

re = r"(?(?=[^\t]*)([\t]+))";
str = 'a            bold, italic,           teletype';
subst = ',';

result = re.sub($re, $subst, $str);

Body:
I suppose you could do this:

import re

regex = r'(^\w*?[\t]+)'
s = 'a      bold, italic,           teletype'

def repl(match):
    s = match.group(0)
    return s.rstrip() + ', '

print(re.sub(regex,repl, s))

out

a, bold, italic,            teletype

Here we are capturing the beginning of the string through any tabs that may occur after the first word, and passing the match to a callable. The callable removes trailing tabs with rstrip and adds a trailing comma.

Note: if the first tab occurs after the first word, it's not replaced. i.e. 'a bold, italic,           teletype' is left unchanged. Is that what you want?


问:
Cannot create and attach file to an item in Podio using pypodio (PODIO API client, Python)
I cannot seem to create and attach a file to an item in podio using the pypodio client, which is the python wrapper for PODIO's API. I am trying to get the file id but keep on getting the error. I am using Python 3.6.0

My code is

```<code> `path = os.getcwd()`
 `filename="system_information"`
 `filepath = path + "\\system_information.txt"`
 `filedata=open(filepath)`
 uploading_response = pcbapp.Files.create(filename,filedata)
</code>```

I get an error shown below,
  File "c:\users\nipun.arora\src\podio-py\pypodio2\encode.py", line 317, in get_headers
    boundary = urllib.quote_plus(boundary)
AttributeError: module 'urllib' has no attribute 'quote_plus'

答: That's might be because there is no urllib.quote_plus in python3. Can you try running same code in python2?

Body:
I cannot seem to create and attach a file to an item in podio using the pypodio client, which is the python wrapper for PODIO's API. I am trying to get the file id but keep on getting the error. I am using Python 3.6.0

My code is

 `path = os.getcwd()`
 `filename="system_information"`
 `filepath = path + "\\system_information.txt"`
 `filedata=open(filepath)`
 uploading_response = pcbapp.Files.create(filename,filedata)

I get an error shown below,
  File "c:\users\nipun.arora\src\podio-py\pypodio2\encode.py", line 317, in get_headers
    boundary = urllib.quote_plus(boundary)
AttributeError: module 'urllib' has no attribute 'quote_plus'


问:
JS Promises: is there a neat way to resolve multiple promises as object properties?
I wrote the below code then realised it was resolving early (logging before all promises resolve):

```<code>readDirPromise
.then(categoriseFiles)
.then(({movies, series}) => ({
  movies: Promise.all(movies.map(movieTasks)),
  series: Promise.all(series.map(seriesTasks))
}))
.then((res) => {
  console.log(' done!', res)
})
</code>```

I've managed to rewrite it to resolve in the correct order:

```<code>readDirPromise
.then(categoriseFiles)
.then((cats) => Promise.all(cats.movies.map(movieTasks)).then((movies) => {
  cats.movies = movies
  return cats
}))
.then((cats) => Promise.all(cats.series.map(seriesTasks)).then((series) => {
  cats.series = series
  return cats
}))
.then((res) => {
  console.log(' done!', res)
})
</code>```

but I can't help but think... is there a neater, more extensible way?

答:
Instead of chaining the promises, you can create separate promises and resolve them in the the Promise.all method as you have done.

```<code>var p1 = getNewPromise();
var p2 = getNewPromise();
var p3 = getNewPromise();
</code>```

// From MDN

```<code>Promise.all([p1, p2, p3]).then(values => {
  console.log(values);
});
</code>```

Body:
I wrote the below code then realised it was resolving early (logging before all promises resolve):

readDirPromise
.then(categoriseFiles)
.then(({movies, series}) => ({
  movies: Promise.all(movies.map(movieTasks)),
  series: Promise.all(series.map(seriesTasks))
}))
.then((res) => {
  console.log(' done!', res)
})

I've managed to rewrite it to resolve in the correct order:

readDirPromise
.then(categoriseFiles)
.then((cats) => Promise.all(cats.movies.map(movieTasks)).then((movies) => {
  cats.movies = movies
  return cats
}))
.then((cats) => Promise.all(cats.series.map(seriesTasks)).then((series) => {
  cats.series = series
  return cats
}))
.then((res) => {
  console.log(' done!', res)
})

but I can't help but think... is there a neater, more extensible way?

Body:
Instead of chaining the promises, you can create separate promises and resolve them in the the Promise.all method as you have done.

var p1 = getNewPromise();
var p2 = getNewPromise();
var p3 = getNewPromise();

// From MDN

Promise.all([p1, p2, p3]).then(values => {
  console.log(values);
});


问:
Construct grid of points in Matlab
Consider two dimensions (x,y).

I want to construct in Matlab the grid of points such that -0.8<x<0.1 and 0.1<y<0.9. From such a grid I want to delete all the points such that -0.7<=x<=0 and 0.2<=y<=0.8.

I use "grid precision" equal to 0.001.

Here my code which does not seem to do what I want

```<code>%outside square
xgrid=(-0.8+0.001:0.001:0.1-0.001);
ygrid=(0.1+0.001:0.001:0.9-0.001);
[p,q] = meshgrid(xgrid, ygrid);
grid = [p(:) q(:)];
%inside square
xgrid1=(-0.7:0.001:0);
xgrid1=(0.2:0.001:0.8);
[p,q] = meshgrid(xgrid1, ygrid1);
grid1 = [p(:) q(:)];
%delete inside square from outside square
grid(ismember(grid,grid1, 'rows'),:)=[];
</code>```

Ismember does not seem to recognise that all the points in grid1 are in grid. What am I doing wrong?

答:
See this code with comments describing what to do

```<code>% Define grid precision, h, for more clarity and easier editing
h = 1e-3;
% Specify xgrid and ygrid using 2 parts each
xgrid = [-0.8+h:h:-0.7-h, 0+h:h:0.1];
ygrid = [0.1+h:h:0.2-h, 0.8+h:h:0.9-h];
% Make grid and use it to get coordinate pairs
[p,q] = meshgrid(xgrid, ygrid);
grid = [p(:) q(:)];
</code>```

You are trying to create a large grid, then remove an internal square from it. The above code creates just the resulting matrix, never making the internal square in the first place.

Edit

OP clarified that only coordinates where -0.7<=x<=0.0 AND 0.2<=y<=0.8 should be removed, the above is for the "OR" case. Below is for the "AND" case as desired...

```<code>% Define grid precision, h, for more clarity and easier editing
h = 1e-3;
% Specify xgrid and ygrid using 2 parts each
xgrid = [-0.8+h:h:0.1];
ygrid = [0.1+h:h:0.9-h];
% Make grid and use it to get coordinate pairs
[xx, yy] = meshgrid(xgrid, ygrid);
% Turn grids into column vectors
xx = xx(:); yy = yy(:);
% Logical indexing for where range removal condition is met
idx = (xx >= -0.7 & xx <= 0.0) & (yy >= 0.2 & yy <= 0.8)
% grid is all values of xx and yy which are NOT true in idx, so ~idx
grid = [xx(~idx) yy(~idx)];
</code>```

Title: Construct grid of points in Matlab

Body:
Consider two dimensions (x,y).

I want to construct in Matlab the grid of points such that -0.8<x<0.1 and 0.1<y<0.9. From such a grid I want to delete all the points such that -0.7<=x<=0 and 0.2<=y<=0.8.

I use "grid precision" equal to 0.001.

Here my code which does not seem to do what I want

%outside square
xgrid=(-0.8+0.001:0.001:0.1-0.001);
ygrid=(0.1+0.001:0.001:0.9-0.001);
[p,q] = meshgrid(xgrid, ygrid);
grid = [p(:) q(:)];
%inside square
xgrid1=(-0.7:0.001:0);
xgrid1=(0.2:0.001:0.8);
[p,q] = meshgrid(xgrid1, ygrid1);
grid1 = [p(:) q(:)];
%delete inside square from outside square
grid(ismember(grid,grid1, 'rows'),:)=[];

Ismember does not seem to recognise that all the points in grid1 are in grid. What am I doing wrong?

Body:
See this code with comments describing what to do

% Define grid precision, h, for more clarity and easier editing
h = 1e-3;
% Specify xgrid and ygrid using 2 parts each
xgrid = [-0.8+h:h:-0.7-h, 0+h:h:0.1];
ygrid = [0.1+h:h:0.2-h, 0.8+h:h:0.9-h];
% Make grid and use it to get coordinate pairs
[p,q] = meshgrid(xgrid, ygrid);
grid = [p(:) q(:)];

You are trying to create a large grid, then remove an internal square from it. The above code creates just the resulting matrix, never making the internal square in the first place.

Edit

OP clarified that only coordinates where -0.7<=x<=0.0 AND 0.2<=y<=0.8 should be removed, the above is for the "OR" case. Below is for the "AND" case as desired...

% Define grid precision, h, for more clarity and easier editing
h = 1e-3;
% Specify xgrid and ygrid using 2 parts each
xgrid = [-0.8+h:h:0.1];
ygrid = [0.1+h:h:0.9-h];
% Make grid and use it to get coordinate pairs
[xx, yy] = meshgrid(xgrid, ygrid);
% Turn grids into column vectors
xx = xx(:); yy = yy(:);
% Logical indexing for where range removal condition is met
idx = (xx >= -0.7 & xx <= 0.0) & (yy >= 0.2 & yy <= 0.8)
% grid is all values of xx and yy which are NOT true in idx, so ~idx
grid = [xx(~idx) yy(~idx)];


问:
Internal engine error in regex
I am trying to write a regex for the below use-case:

```<code>1. The name must begin with a letter (alphabet).
2. Should only contain alphanumeric characters.
3. No Special characters are allowed except underscore.
4. Should not have two or more consecutive underscores.
5. Cannot end with an underscore.
</code>```

My regex for this is ^[A-Za-z]+(?!.*[_]{2,})([a-zA-Z0-9_ ][a-zA-Z0-9]+)*$.
This regex gives expected output for the below inputs:

```<code>Customer_info
customer info_1
customer
customer___info
cust_info_1_f
ksldfhlksjdhfjskdhfsjdklfhslkdhfsdklfhsdkhfsdklhfdskhfklsdhfkdlshfklsdfhsdklhfsdklfh
</code>```

But for some special cases which includes the below inputs,

```<code>zxbnczmxncbzxnmcbzmxncbzxnxbczxmnbcvmznbxvcbzxnmcmzxvczx,zxc
zjkhsadhskjdhakjsdhaksjhdjkashdaskjdhaskdhaskjdhaskjdhasjkdhaskjdkajshd/ksajkhdashdjkad.asdjk,sa
</code>```

It fails with a message saying internal engine error.
What is reason behind this error?I did some research here, but didn't get much of help in my scenario. Please tell me what is wrong with my regex that is causing this error for some cases.

Note: I was using this tool for testing my regex.

答:
Your regex fails due to catastrophic backtracking due to the ([a-zA-Z0-9_ ][a-zA-Z0-9]+)* subpattern where the first character class may match the same chars as the second one, and the group is *-quantified.

Also, placing the negative lookahead after a + quantified [A-Za-z] pattern allows a lot more matching paths than you would like to let it.

You may fix your expression with

```<code>^[A-Za-z][a-zA-Z0-9]*([_ ][a-zA-Z0-9]+)*$
</code>```

Details:

^ - start of string

[a-zA-Z] - the first symbol must be a letter

[a-zA-Z0-9]* - there may appear 0+ letters/digits

([_ ][a-zA-Z0-9]+)* - zero or more sequences of

[_ ] - a _ or space

[a-zA-Z0-9]+ - 1 or more letters or digits

$ - end  of the string.

See the regex demo

Title: Internal engine error in regex

Body:
I am trying to write a regex for the below use-case:

1. The name must begin with a letter (alphabet).
2. Should only contain alphanumeric characters.
3. No Special characters are allowed except underscore.
4. Should not have two or more consecutive underscores.
5. Cannot end with an underscore.

My regex for this is ^[A-Za-z]+(?!.*[_]{2,})([a-zA-Z0-9_ ][a-zA-Z0-9]+)*$.
This regex gives expected output for the below inputs:

Customer_info
customer info_1
customer
customer___info
cust_info_1_f
ksldfhlksjdhfjskdhfsjdklfhslkdhfsdklfhsdkhfsdklhfdskhfklsdhfkdlshfklsdfhsdklhfsdklfh

But for some special cases which includes the below inputs,

zxbnczmxncbzxnmcbzmxncbzxnxbczxmnbcvmznbxvcbzxnmcmzxvczx,zxc
zjkhsadhskjdhakjsdhaksjhdjkashdaskjdhaskdhaskjdhaskjdhasjkdhaskjdkajshd/ksajkhdashdjkad.asdjk,sa

It fails with a message saying internal engine error.
What is reason behind this error?I did some research here, but didn't get much of help in my scenario. Please tell me what is wrong with my regex that is causing this error for some cases.

Note: I was using this tool for testing my regex.

Body:
Your regex fails due to catastrophic backtracking due to the ([a-zA-Z0-9_ ][a-zA-Z0-9]+)* subpattern where the first character class may match the same chars as the second one, and the group is *-quantified.

Also, placing the negative lookahead after a + quantified [A-Za-z] pattern allows a lot more matching paths than you would like to let it.

You may fix your expression with

^[A-Za-z][a-zA-Z0-9]*([_ ][a-zA-Z0-9]+)*$

Details:

^ - start of string

[a-zA-Z] - the first symbol must be a letter

[a-zA-Z0-9]* - there may appear 0+ letters/digits

([_ ][a-zA-Z0-9]+)* - zero or more sequences of

[_ ] - a _ or space

[a-zA-Z0-9]+ - 1 or more letters or digits

$ - end  of the string.

See the regex demo


问:
Best video format for HTML5?
I've got a set of videos that are going to be posted on a new site I'm developing, using our new html5 player. I know Firefox only supports .ogg format, whereas most others (including eventually IE9) support h264.

I'm looking to tap into the experience of the crowd here: has anyone had any luck with a single video format across browsers? Or am I doomed to double-encode everything? It just seems a shame to waste space on having two copies of each video because we can't standardize our codecs.

Thanks in advance!

PS (Flash player isn't really an option as a fallback, partly on principle and partly because of a rather large mobile userbase.)

答: Probably WebM if not Ogg. WebM's patents are owned by Google but have been released from that. Ogg is probably OK but there are concerns. H.264 is a patent trap waiting to happen.</p>

Title: Best video format for HTML5?


问:
python : error handling Ordered dict with unicode data
My script migrates data from MySQL to mongodb. It runs perfectly well when there are no unicode columns included. But throws me below error when OrgLanguages column is added.

```<code>    mongoImp = dbo.insert_many(odbcArray)
  File "/home/lrsa/.local/lib/python2.7/site-packages/pymongo/collection.py", line 711, in insert_many
    blk.execute(self.write_concern.document)
  File "/home/lrsa/.local/lib/python2.7/site-packages/pymongo/bulk.py", line 493, in execute
    return self.execute_command(sock_info, generator, write_concern)
  File "/home/lrsa/.local/lib/python2.7/site-packages/pymongo/bulk.py", line 319, in execute_command
    run.ops, True, self.collection.codec_options, bwc)
bson.errors.InvalidStringData: strings in documents must be valid UTF-8: 'Portugu\xeas do Brasil, ?????, English, Deutsch, Espa\xf1ol latinoamericano, Polish'
</code>```

My code:

```<code>import MySQLdb, MySQLdb.cursors, sys, pymongo, collections

odbcArray=[]
mongoConStr = '192.168.10.107:36006'
sqlConnect = MySQLdb.connect(host = "54.175.170.187", user = "testuser", passwd = "testuser", db = "testdb", cursorclass=MySQLdb.cursors.DictCursor)
mongoConnect = pymongo.MongoClient(mongoConStr)

sqlCur = sqlConnect.cursor()
sqlCur.execute("SELECT ID,OrgID,OrgLanguages,APILoginID,TransactionKey,SMTPSpeed,TimeZoneName,IsVideoWatched FROM organizations")

dbo = mongoConnect.eaedw.mysqlData
tuples = sqlCur.fetchall()

for tuple in tuples:
    odbcArray.append(collections.OrderedDict(tuple))

mongoImp = dbo.insert_many(odbcArray)

sqlCur.close()
mongoConnect.close()
sqlConnect.close()
sys.exit()
</code>```

Above script migraates data perfectly when tried without OrgLanguages column in the SELECT query.
To overcome this, I have tried to use the OrderedDict() in another way but gives me a different type of error

Changed Code:

```<code>for tuple in tuples:
    doc = collections.OrderedDict()
    doc['oid'] = tuple.OrgID
    doc['APILoginID'] = tuple.APILoginID
    doc['lang'] = unicode(tuple.OrgLanguages)
    odbcArray.append(doc)
mongoImp = dbo.insert_many(odbcArray)
</code>```

Error Received:

```<code>Traceback (most recent call last):
  File "pymsql.py", line 19, in <module>
    doc['oid'] = tuple.OrgID
AttributeError: 'dict' object has no attribute 'OrgID'
</code>```

答: Your MySQL connection is returning characters in a different encoding than UTF-8, which is the encoding that all BSON strings must be in. Try your original code but pass charset='utf8' to MySQLdb.connect.

Body:
My script migrates data from MySQL to mongodb. It runs perfectly well when there are no unicode columns included. But throws me below error when OrgLanguages column is added.

    mongoImp = dbo.insert_many(odbcArray)
  File "/home/lrsa/.local/lib/python2.7/site-packages/pymongo/collection.py", line 711, in insert_many
    blk.execute(self.write_concern.document)
  File "/home/lrsa/.local/lib/python2.7/site-packages/pymongo/bulk.py", line 493, in execute
    return self.execute_command(sock_info, generator, write_concern)
  File "/home/lrsa/.local/lib/python2.7/site-packages/pymongo/bulk.py", line 319, in execute_command
    run.ops, True, self.collection.codec_options, bwc)
bson.errors.InvalidStringData: strings in documents must be valid UTF-8: 'Portugu\xeas do Brasil, ?????, English, Deutsch, Espa\xf1ol latinoamericano, Polish'

My code:

import MySQLdb, MySQLdb.cursors, sys, pymongo, collections

odbcArray=[]
mongoConStr = '192.168.10.107:36006'
sqlConnect = MySQLdb.connect(host = "54.175.170.187", user = "testuser", passwd = "testuser", db = "testdb", cursorclass=MySQLdb.cursors.DictCursor)
mongoConnect = pymongo.MongoClient(mongoConStr)

sqlCur = sqlConnect.cursor()
sqlCur.execute("SELECT ID,OrgID,OrgLanguages,APILoginID,TransactionKey,SMTPSpeed,TimeZoneName,IsVideoWatched FROM organizations")

dbo = mongoConnect.eaedw.mysqlData
tuples = sqlCur.fetchall()

for tuple in tuples:
    odbcArray.append(collections.OrderedDict(tuple))

mongoImp = dbo.insert_many(odbcArray)

sqlCur.close()
mongoConnect.close()
sqlConnect.close()
sys.exit()

Above script migraates data perfectly when tried without OrgLanguages column in the SELECT query.
To overcome this, I have tried to use the OrderedDict() in another way but gives me a different type of error

Changed Code:

for tuple in tuples:
    doc = collections.OrderedDict()
    doc['oid'] = tuple.OrgID
    doc['APILoginID'] = tuple.APILoginID
    doc['lang'] = unicode(tuple.OrgLanguages)
    odbcArray.append(doc)
mongoImp = dbo.insert_many(odbcArray)

Error Received:

Traceback (most recent call last):
  File "pymsql.py", line 19, in <module>
    doc['oid'] = tuple.OrgID
AttributeError: 'dict' object has no attribute 'OrgID'


问:
How to get final redirected url after all redirection of tracking links?
I want to get final redirected url after all redirection in php. I used lots of function and code searched from web but no one is correct for some tracking url.

Here is my url : http://performance.ikoo.com/geo_tracking_redirect.html?a=CD441&program_id=1304274

It finally redirects to : https://www.shopandship.com/my-shopandship/profile.aspx

How can i get the final redirect url for such type of url.
please help.

答:
you can try this code for this url.. </p>

<p>Which returns redirected url for tracking url..  </p>

```<code>$url = "http://www.awin1.com/awclick.php?mid=5477&id=129196";
stream_context_set_default(array('http' => array('method' => 'HEAD')));
print_r(get_headers($url, 0));
$larr = get_headers($url, 1)["Location"];

$loc = is_array($larr) ? array_pop($larr):$larr;
echo $loc."```";
$domain = parse_url($loc, PHP_URL_HOST);
print_r($domain);
</code>```

Body:
you can try this code for this url..

Which returns redirected url for tracking url..

$url = "http://www.awin1.com/awclick.php?mid=5477&id=129196";
stream_context_set_default(array('http' => array('method' => 'HEAD')));
print_r(get_headers($url, 0));
$larr = get_headers($url, 1)["Location"];

$loc = is_array($larr) ? array_pop($larr):$larr;
echo $loc."</pre>";
$domain = parse_url($loc, PHP_URL_HOST);
print_r($domain);


问:
Error:Execution failed for task ':app:packageDebug' - Java heap space
I am getting this error in Android Studio logs when I am trying to build an APK.

Error:Execution failed for task ':app:packageDebug'.
Java heap space

This issue is coming when I am trying to build an APK with 350 MB size of .sqlite in assets directory. When I removed the .sqlite file then issue is gone.

My studio64.exe.vmoptions file for studio:

```<code>-Xms2048m
-Xmx3840m
-XX:ReservedCodeCacheSize=960m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=250
-da
-Djna.nosys=true
-Djna.boot.library.path=

-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Didea.paths.selector=AndroidStudio2.3
-Didea.platform.prefix=AndroidStudio
-Didea.jre.check=true
</code>```

答:
Add this at the end of gradle.properties file.

```<code>org.gradle.jvmargs=-XX\:MaxHeapSize\=512m -Xmx512m
</code>```

Body:
I am getting this error in Android Studio logs when I am trying to build an APK.

Error:Execution failed for task ':app:packageDebug'.
Java heap space

This issue is coming when I am trying to build an APK with 350 MB size of .sqlite in assets directory. When I removed the .sqlite file then issue is gone.

My studio64.exe.vmoptions file for studio:

-Xms2048m
-Xmx3840m
-XX:ReservedCodeCacheSize=960m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=250
-da
-Djna.nosys=true
-Djna.boot.library.path=

-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Didea.paths.selector=AndroidStudio2.3
-Didea.platform.prefix=AndroidStudio
-Didea.jre.check=true

Body:
Add this at the end of gradle.properties file.

org.gradle.jvmargs=-XX\:MaxHeapSize\=512m -Xmx512m


问:
What does `(c = *str) != 0` mean?
```<code>int equiv (char, char);
int nmatches(char *str, char comp) {
    char c;
    int n=0;
    while ((c = *str) != 0) {
       if (equiv(c,comp) != 0) n++;
      str++;
    }
    return (n);
}
</code>```

What does "(c = *str) != 0" actually mean?
Can someone please explain it to me or help give me the correct terms to search for an explanation myself?

答:
You don't need char c since you already have the pointer char *str, also you can replace != 0 with != '\0' for better readability (if not compatibility)

```<code>while (*str != '\0')
{
    if (equiv((*str),comp)
          != 0)
    { n++; }

    str++;
}
</code>```

To understand what the code does, you can read it like this

```<code>while ( <str> pointed-to value is-not <end_of_string> )
{
    if (function <equiv> with parameters( <str> pointed-to value, <comp> )
            returned non-zero integer value)
    then { increment <n> by 1 }

    increment pointer <str> by 1 x sizeof(char) so it points to next adjacent char
}
</code>```

Title: What does `(c = *str) != 0` mean?

Body:
int equiv (char, char);
int nmatches(char *str, char comp) {
    char c;
    int n=0;
    while ((c = *str) != 0) {
       if (equiv(c,comp) != 0) n++;
      str++;
    }
    return (n);
}

What does "(c = *str) != 0" actually mean?
Can someone please explain it to me or help give me the correct terms to search for an explanation myself?

Body:
You don't need char c since you already have the pointer char *str, also you can replace != 0 with != '\0' for better readability (if not compatibility)

while (*str != '\0')
{
    if (equiv((*str),comp)
          != 0)
    { n++; }

    str++;
}

To understand what the code does, you can read it like this

while ( <str> pointed-to value is-not <end_of_string> )
{
    if (function <equiv> with parameters( <str> pointed-to value, <comp> )
            returned non-zero integer value)
    then { increment <n> by 1 }

    increment pointer <str> by 1 x sizeof(char) so it points to next adjacent char
}


问:
Evenly sized columns between rows using grid/flex
Consider the following snippet:

#container{
  border: solid 1px black;
  display: inline-grid;
  grid-template-columns: repeat(3, auto);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="row">
    <div class="item">A1111</div>
    <div class="item">B1</div>
    <div class="item">C1</div>
  </div>
  <div class="row">
    <div class="item">A2</div>
    <div class="item">B2222</div>
    <div class="item">C2</div>
  </div>
  <div class="row">
    <div class="item">A3</div>
    <div class="item">B3</div>
    <div class="item">C3333</div>
  </div>
</div></code>```

The end result is a table-like display where each item of every row is the width of the widest item in that column.

```<code>A1111 A2    A3
B1    B2222 B3
C1    C2    C3333
</code>```

Which is great - but I need the table laid out as rows...

```<code>A1111 B1    C1
A2    B2222 C2
A3    B3    C3333
</code>```

display: table solves this - but table has some drawbacks around spacing, alignments and so-on. Therefore, grid and flex looks attractive.

Alas I cannot figure out how to get the information laid out as desired.

Adding display: grid to .row helps the order of information, but doesn't retain the equal column widths.

The item content will vary, and so cannot use fixed widths and it is not desired that the grid/flex spans the entire page/containing width.

答:
There's way which I would make it.

Attached JSFiddle(click)

```<code>.row {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}

.row > .item {
  display:block;
  flex: 1 1;

  border: 1px solid #000;
}
</code>```

There's such great guide about flex; Click here.

Body:
Consider the following snippet:

#container{
  border: solid 1px black;
  display: inline-grid;
  grid-template-columns: repeat(3, auto);
}

A1111

B1

C1

A2

B2222

C2

A3

B3

C3333

The end result is a table-like display where each item of every row is the width of the widest item in that column.

A1111 A2    A3
B1    B2222 B3
C1    C2    C3333

Which is great - but I need the table laid out as rows...

A1111 B1    C1
A2    B2222 C2
A3    B3    C3333

display: table solves this - but table has some drawbacks around spacing, alignments and so-on. Therefore, grid and flex looks attractive.

Alas I cannot figure out how to get the information laid out as desired.

Adding display: grid to .row helps the order of information, but doesn't retain the equal column widths.

The item content will vary, and so cannot use fixed widths and it is not desired that the grid/flex spans the entire page/containing width.

Body:
There's way which I would make it.

Attached JSFiddle(click)

.row {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}

.row > .item {
  display:block;
  flex: 1 1;

  border: 1px solid #000;
}

There's such great guide about flex; Click here.


问:
Angular 2.0 and Modal Dialog
I am trying to find some examples on how to do a Confirmation modal dialog in Angular 2.0. I have been using Bootstrap dialog for Angular 1.0  and unable to find any examples in the web for Angular 2.0. I also checked angular 2.0 docs with no luck.

Is there a way to use the Bootstrap dialog with Angular 2.0?

答:
Check ASUI dialog which create at runtime. There is no need of hide and show logic. Simply service will create a component at runtime using AOT
ASUI NPM </p>

Title: Angular 2.0 and Modal Dialog


问:
Two-way hash table
Is there an efficient implementation of a hash table, which maps key (integer) to values (string) and vice versa, for some compiled language?

Of course, one could always have two tables, one for key=>value mapping and other for value=>key. However that would not be very efficient, at least not memory-wise. Possibly both mappings can be in a single table, if the type system and intended usage allow it.

答:
This is the datastructureI usefor a bihash:
The overhead is four ints (for the indexes) per entry.

In the example below, with typedef unsigned char Index; , the overhead will be four characters, and the maximal table capacity will be 255.

```<code>        /* For demonstration purposes these types are VERY SMALL.
        ** Normally one would use unsigned short, or unsigned int.
        */
typedef unsigned char Index;
typedef unsigned short Hashval;
        /* Use the maximal representable value as sentinel value */
#define NIL ((Index)-1)

struct entry {
        Index head_key          /* The head-of-the-chain pointers */
                , head_val;     /* ... and for the values */
        Index next_key          /* linked list for chaining the keys */
                , next_val;     /* ... and for the values */
        };

struct table {
        unsigned totlen, keylen;
                /* free points to the root of the freetree */
        Index size, free;
                /* The complete payload, for both keys and values.
                 * layout = [key0|val0|key1|val1|..] (without padding/alignment)
                 */
        char *data;
        struct entry *entries; /* All the entries. Not pointers, but the actual entries. */
        };
        /* Macros for accessing the pool of payload */
#define NODE_KEY(p,n) ((p)->data + (n) * (p)->totlen)
#define NODE_VAL(p,n) ((p)->data + (n) * ((p)->totlen+(p)->keylen))

#define TH_OK 0
#define TH_KEY_NOT_FOUND 1
#define TH_VAL_NOT_FOUND 2
#define TH_BOTH_NOT_FOUND 3
#define TH_TABLE_FULL 4
#define TH_KEY_DUPLICATE 5
#define TH_VAL_DUPLICATE 6
#define TH_BOTH_DUPLICATE 7
#define TH_TOTAL_ECLIPSE 8

/********************************************/

    /* Allocate and initialise the hash table.
    ** Note: given fixed size, the table and the payload could be statically allocated,
    ** (but we'd still need to do the initialisation)
    */

struct table * table_new( unsigned keylen, unsigned vallen, unsigned totcount )
{
Index idx;
struct table *this;

if (totcount > NIL) {
        fprintf(stderr, "Table_new(%zu,%zu,%zu): totcount(%zu) larger than largest Index(%zu)\n"
                , (size_t) keylen, (size_t) vallen, (size_t) totcount
                , (size_t) totcount, ((size_t)NIL) -1 );
        return NULL;
        }
this = malloc (sizeof *this);
this->size = totcount;
this->keylen = keylen;
this->totlen = keylen+vallen;
this->data = malloc (totcount * this->totlen );
this->entries = malloc (totcount * sizeof *this->entries );

this->free = 0; /* start of freelist */
for( idx=0; idx < this->size; idx++ ) {
        this->entries[idx].head_key = NIL;
        this->entries[idx].head_val = NIL;
        this->entries[idx].next_key = NIL;
        this->entries[idx].next_val = idx+1; /* unused next pointer reused as freelist */
        };
this-> entries[idx-1].next_val = NIL; /* end of freelist */

fprintf(stderr, "Table_new(%zu,%zu,%zu) size = %zu+%zu+%zu\n"
                , (size_t) keylen, (size_t) vallen, (size_t) totcount
        , sizeof *this, (size_t)totcount * this->totlen, totcount * sizeof *this->entries
         );

return this;
}
</code>```

Title: Two-way hash table

Body:
This is the datastructureI usefor a bihash:
The overhead is four ints (for the indexes) per entry.

In the example below, with typedef unsigned char Index; , the overhead will be four characters, and the maximal table capacity will be 255.

        /* For demonstration purposes these types are VERY SMALL.
        ** Normally one would use unsigned short, or unsigned int.
        */
typedef unsigned char Index;
typedef unsigned short Hashval;
        /* Use the maximal representable value as sentinel value */
#define NIL ((Index)-1)

struct entry {
        Index head_key          /* The head-of-the-chain pointers */
                , head_val;     /* ... and for the values */
        Index next_key          /* linked list for chaining the keys */
                , next_val;     /* ... and for the values */
        };

struct table {
        unsigned totlen, keylen;
                /* free points to the root of the freetree */
        Index size, free;
                /* The complete payload, for both keys and values.
                 * layout = [key0|val0|key1|val1|..] (without padding/alignment)
                 */
        char *data;
        struct entry *entries; /* All the entries. Not pointers, but the actual entries. */
        };
        /* Macros for accessing the pool of payload */
#define NODE_KEY(p,n) ((p)->data + (n) * (p)->totlen)
#define NODE_VAL(p,n) ((p)->data + (n) * ((p)->totlen+(p)->keylen))

#define TH_OK 0
#define TH_KEY_NOT_FOUND 1
#define TH_VAL_NOT_FOUND 2
#define TH_BOTH_NOT_FOUND 3
#define TH_TABLE_FULL 4
#define TH_KEY_DUPLICATE 5
#define TH_VAL_DUPLICATE 6
#define TH_BOTH_DUPLICATE 7
#define TH_TOTAL_ECLIPSE 8

/********************************************/

    /* Allocate and initialise the hash table.
    ** Note: given fixed size, the table and the payload could be statically allocated,
    ** (but we'd still need to do the initialisation)
    */

struct table * table_new( unsigned keylen, unsigned vallen, unsigned totcount )
{
Index idx;
struct table *this;

if (totcount > NIL) {
        fprintf(stderr, "Table_new(%zu,%zu,%zu): totcount(%zu) larger than largest Index(%zu)\n"
                , (size_t) keylen, (size_t) vallen, (size_t) totcount
                , (size_t) totcount, ((size_t)NIL) -1 );
        return NULL;
        }
this = malloc (sizeof *this);
this->size = totcount;
this->keylen = keylen;
this->totlen = keylen+vallen;
this->data = malloc (totcount * this->totlen );
this->entries = malloc (totcount * sizeof *this->entries );

this->free = 0; /* start of freelist */
for( idx=0; idx < this->size; idx++ ) {
        this->entries[idx].head_key = NIL;
        this->entries[idx].head_val = NIL;
        this->entries[idx].next_key = NIL;
        this->entries[idx].next_val = idx+1; /* unused next pointer reused as freelist */
        };
this-> entries[idx-1].next_val = NIL; /* end of freelist */

fprintf(stderr, "Table_new(%zu,%zu,%zu) size = %zu+%zu+%zu\n"
                , (size_t) keylen, (size_t) vallen, (size_t) totcount
        , sizeof *this, (size_t)totcount * this->totlen, totcount * sizeof *this->entries
         );

return this;
}