问:
Is a non-correlated exists(...) query in the where clause executed for each row or just once?
I have the following query:

```<code>SELECT *
FROM   t1, t2
WHERE  t1.some_id = t2.some_id
       and
       not exists(select true from some_table where some_column = true)
</code>```

Here, the not exists(select true from some_table where ...) does not refer to t1 or t2 from the main query.

Is this not exists(select true from some_table where ...) executed just once or for every tuple from the product between t1 and t2 for which t1.some_id = t2.some_id is true?

In other words, if it is executed just once, an empty table can be returned immediately if the result is false. Logically, we have written:

```<code>if (not exists(select true from some_table where some_column = true))
    SELECT *
    FROM   t1, t2
    WHERE  t1.some_id = t2.some_id
else
    empty table
</code>```

答:
First, learn to use proper join syntax:

```<code>SELECT *
FROM t1 JOIN
     t2
     ON t1.some_id = t2.some_id
WHERE not exists(select true from some_table where some_column = true);
</code>```

The subquery should be executed only once.  However, ultimately that is up to the Postgres optimizer.  You can guarantee that the code is executed only once using a LEFT JOIN:

```<code>SELECT t1.*, t2.*
FROM t1 JOIN
     t2
     ON t1.some_id = t2.some_id LEFT JOIN
     some_table st
     ON st.some_column = true
WHERE st.some_column IS NULL;
</code>```

Body:
I have the following query:

SELECT *
FROM   t1, t2
WHERE  t1.some_id = t2.some_id
       and
       not exists(select true from some_table where some_column = true)

Here, the not exists(select true from some_table where ...) does not refer to t1 or t2 from the main query.

Is this not exists(select true from some_table where ...) executed just once or for every tuple from the product between t1 and t2 for which t1.some_id = t2.some_id is true?

In other words, if it is executed just once, an empty table can be returned immediately if the result is false. Logically, we have written:

if (not exists(select true from some_table where some_column = true))
    SELECT *
    FROM   t1, t2
    WHERE  t1.some_id = t2.some_id
else
    empty table

Body:
First, learn to use proper join syntax:

SELECT *
FROM t1 JOIN
     t2
     ON t1.some_id = t2.some_id
WHERE not exists(select true from some_table where some_column = true);

The subquery should be executed only once.  However, ultimately that is up to the Postgres optimizer.  You can guarantee that the code is executed only once using a LEFT JOIN:

SELECT t1.*, t2.*
FROM t1 JOIN
     t2
     ON t1.some_id = t2.some_id LEFT JOIN
     some_table st
     ON st.some_column = true
WHERE st.some_column IS NULL;


来源: stackexchange

问:
What does Spacy use to create vector representations?
What is Spacy's built in method of creating vector representations?
I performed NLP on my corpus, and then used .similarity (cosine similarity) to map out documents that were "similar". However, I am unsure what method spacy uses to create vector representations. To my knowledge, I am thinking that it is probably word2vec skip-gram with negative sampling, however, I would like to be sure!</p>

答: Spacy's default English model uses GloVe word embeddings to compute the similarity between two words. You can find more information in the SpaCy documentation.</p>

ContentLicense: CC BY-SA 3.0


问:
Loading Bar on my website
Please I'm trying to knockoff a loading bar on my site, I have searched through the files, still can't find it. I also tried inspecting using google chrome, but I couldn't target the loader. Kindly help out

Click here for to visit website.

答:
Remove Pace library/plugin from your index.html in head section
 & from assets folder inside your application.</p>

```<code><link href="assets/plugins/pace/pace.css" rel="stylesheet">
<script src="assets/plugins/pace/pace.min.js"></script>
</code>```

Title: Loading Bar on my website

Body:
Remove Pace library/plugin from your index.html in head section
 & from assets folder inside your application.

<link href="assets/plugins/pace/pace.css" rel="stylesheet">
<script src="assets/plugins/pace/pace.min.js"></script>


问:
Disable all tooltips in MATLAB editor
I'm using MATLAB on a server via ssh access (OPENGL rendering). When I'm editing the code it is extremely annoying, that eg. on mouseover a warning or editing a variable that appears several times in the code a tooltip pops up!

Because in this setup it appears as an extra window, and the connection crashes, when I try to close it.

Does anyone of you know how to disable especially the warning popups without losing the yellow underlining of warnings?

Here a screenshot of what I mean:

答:
You can disable the popups, but you'll lose the interactive underlining in the MATLAB Editor.

To disable the popups, got to Preferences->Code Analyzer, and uncheck the option "Enable integrated warning and error messages".

Even though you'll lose the interactive underlinings in the MATLAB Editor, you can still use the Code Analyzer directly.

If you save your file and then type checkcode myfile.m, the Code Analyzer will run, and show you the places at which you would have had underlinings in the editor.

Title: Disable all tooltips in MATLAB editor


问:
Why the "linenos" option fails to add the line number in Jekyll?
I am using jekyll to generate my website.  I want to add a line number column to my code block.  I searched google, and everyone told me to add a "linenos" option to the hightlight tag, but i doesn't work in my case:

```<code>{% highlight ruby linenos %}
def foo():
puts 'foo'
end
{% endhighlight %}
</code>```

The highlight is working well, but the line numbers....

Could you help me with this?  If you want to see the source css/html files, hit here.

Thanks!

Further checking:

the html generated for this section is :

```<code><div class="highlight">```
    def foo():
    puts
    'foo'
    end
```</div>
</code>```

答:
I did the same thing. Although line number were showing the css wasn't being beautiful. The main reason was that bootstrap was conflicting with my style.css. Adding the following to the style.css resolved it.</p>

```<code>.highlight pre {
    background-color: transparent;
    border: transparent;
    color: inherit;
}
</code>```

Body:
I am using jekyll to generate my website.  I want to add a line number column to my code block.  I searched google, and everyone told me to add a "linenos" option to the hightlight tag, but i doesn't work in my case:

{% highlight ruby linenos %}
def foo():
puts 'foo'
end
{% endhighlight %}

The highlight is working well, but the line numbers....

Could you help me with this?  If you want to see the source css/html files, hit here.

Thanks!

Further checking:

the html generated for this section is :

    def foo():
    puts
    'foo'
    end

Body:
I did the same thing. Although line number were showing the css wasn't being beautiful. The main reason was that bootstrap was conflicting with my style.css. Adding the following to the style.css resolved it.

.highlight pre {
    background-color: transparent;
    border: transparent;
    color: inherit;
}


问:
Error when requesting a Jsonp using JIRA REST API
I made this function to request some tickets from JIRA,I gave the data type as jsonp to avoid the Cross origin problem , and when I make the request I get the response in browser debugger , but cannot handle the json response "SyntaxError: missing ; before statement" , is there any way to read json if I send the request for jsonp ?</p>

```<code>     var ajaxUrl = jira/rest/api...
     jQuery.ajax({
        url:ajaxUrl,
        dataType: 'jsonp',
        jsonpCallback: 'callback',
        type : "GET",
        beforeSend: function (xhr){
          success: function w(data){
            console.log(data);
            alert('Sucess data: ' + data);
          };
          error: function e(data){alert('alert error');}
        }
    })
</code>```

答: I solved the problem , I changed the jsonp in json , and I remade the corss from jira server how it is explained here : https://community.atlassian.com/t5/Answers-Developer-Questions/Enable-CORS-in-JIRA-REST-API/qaq-p/553997    , it looks like the problem was on the preflight part.</p>

Body:
I made this function to request some tickets from JIRA,I gave the data type as jsonp to avoid the Cross origin problem , and when I make the request I get the response in browser debugger , but cannot handle the json response "SyntaxError: missing ; before statement" , is there any way to read json if I send the request for jsonp ?

     var ajaxUrl = jira/rest/api...
     jQuery.ajax({
        url:ajaxUrl,
        dataType: 'jsonp',
        jsonpCallback: 'callback',
        type : "GET",
        beforeSend: function (xhr){
          success: function w(data){
            console.log(data);
            alert('Sucess data: ' + data);
          };
          error: function e(data){alert('alert error');}
        }
    })


问:
how to select multiple nodes (if it contains particular text) in a treeview in c#
I have a treeview like below,

```<code>tables
--table1
  --tab1
  --tab2
--table2
  --tab2
  --tab2
</code>```

I am giving a text "tab" and using  treeViewMenu.SelectedNode = txtbox1.Text, it selects the very first match (i.e node: table1)

I want all the nodes having "tab" in its name to be selected. (i.e table1 and table2)

I have tried passing an array to treeViewMenu.SelectedNode =array[], but this is not working.

答:
A TreeView is not designed for MultiSelect. But if you only want to see which Nodes match to the string in the TextBox you can change the BackColor of this Nodes.

```<code>private void txtbox1_TextChanged(object sender, EventArgs e)
{
    foreach (TreeNode tn in this.treeViewMenu.Nodes)
    {
        SetColor(tn);
    }
}

private void SetColor(TreeNode Node)
{
    if (Node.Text.Contains(this.txtbox1.Text))
    {
        Node.BackColor = System.Drawing.Color.Blue;
        Node.ForeColor = System.Drawing.Color.White;
        Node.Tag = true; //for later to find out which Nodes are "selected"
    }
    else
    {
        Node.BackColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.Window);
        Node.ForeColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.WindowText);
        Node.Tag = false;
    }

    foreach (TreeNode subNode in Node.Nodes)
    {
        SetColor(subNode);
    }
}
</code>```

To find out which Nodes are "selected" you can use this:

```<code>private void btn_GetSelected_Click(object sender, EventArgs e)
{
    string selectedNodes = "";

    foreach (TreeNode tn in this.treeViewMenu.Nodes)
    {
        GetSelectedNodesByTag(tn, ref selectedNodes);
    }
    MessageBox.Show(selectedNodes, "Selected Nodes");
}

private void GetSelectedNodesByTag(TreeNode Node, ref string SelectedNodes)
{
    if ((bool)Node.Tag == true)
    {
        if (SelectedNodes != "") SelectedNodes += "\n";
        SelectedNodes += Node.FullPath;
    }

    foreach (TreeNode subNode in Node.Nodes)
    {
        GetSelectedNodesByTag(subNode, ref SelectedNodes);
    }
}
</code>```

You also could use the CheckBoxes-Property to show the selected Nodes:

```<code>private void SetChecked(TreeNode Node)
{
    if (Node.Text.Contains(this.txtbox1.Text))
    {
        Node.Checked = true;
    }
    else
    {
        Node.Checked = false;
    }

    foreach (TreeNode subNode in Node.Nodes)
    {
        SetChecked(subNode);
    }
}
</code>```

And find out which Nodes are checked:

```<code>private void GetCheckedNodes(TreeNode Node, ref string SelectedNodes)
{
    if (Node.Checked)
    {
        if (SelectedNodes != "") SelectedNodes += "\n";
        SelectedNodes += Node.FullPath;
    }

    foreach (TreeNode subNode in Node.Nodes)
    {
        GetCheckedNodes(subNode, ref SelectedNodes);
    }
}
</code>```

Body:
I have a treeview like below,

tables
--table1
  --tab1
  --tab2
--table2
  --tab2
  --tab2

I am giving a text "tab" and using  treeViewMenu.SelectedNode = txtbox1.Text, it selects the very first match (i.e node: table1)

I want all the nodes having "tab" in its name to be selected. (i.e table1 and table2)

I have tried passing an array to treeViewMenu.SelectedNode =array[], but this is not working.

Body:
A TreeView is not designed for MultiSelect. But if you only want to see which Nodes match to the string in the TextBox you can change the BackColor of this Nodes.

private void txtbox1_TextChanged(object sender, EventArgs e)
{
    foreach (TreeNode tn in this.treeViewMenu.Nodes)
    {
        SetColor(tn);
    }
}

private void SetColor(TreeNode Node)
{
    if (Node.Text.Contains(this.txtbox1.Text))
    {
        Node.BackColor = System.Drawing.Color.Blue;
        Node.ForeColor = System.Drawing.Color.White;
        Node.Tag = true; //for later to find out which Nodes are "selected"
    }
    else
    {
        Node.BackColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.Window);
        Node.ForeColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.WindowText);
        Node.Tag = false;
    }

    foreach (TreeNode subNode in Node.Nodes)
    {
        SetColor(subNode);
    }
}

To find out which Nodes are "selected" you can use this:

private void btn_GetSelected_Click(object sender, EventArgs e)
{
    string selectedNodes = "";

    foreach (TreeNode tn in this.treeViewMenu.Nodes)
    {
        GetSelectedNodesByTag(tn, ref selectedNodes);
    }
    MessageBox.Show(selectedNodes, "Selected Nodes");
}

private void GetSelectedNodesByTag(TreeNode Node, ref string SelectedNodes)
{
    if ((bool)Node.Tag == true)
    {
        if (SelectedNodes != "") SelectedNodes += "\n";
        SelectedNodes += Node.FullPath;
    }

    foreach (TreeNode subNode in Node.Nodes)
    {
        GetSelectedNodesByTag(subNode, ref SelectedNodes);
    }
}

You also could use the CheckBoxes-Property to show the selected Nodes:

private void SetChecked(TreeNode Node)
{
    if (Node.Text.Contains(this.txtbox1.Text))
    {
        Node.Checked = true;
    }
    else
    {
        Node.Checked = false;
    }

    foreach (TreeNode subNode in Node.Nodes)
    {
        SetChecked(subNode);
    }
}

And find out which Nodes are checked:

private void GetCheckedNodes(TreeNode Node, ref string SelectedNodes)
{
    if (Node.Checked)
    {
        if (SelectedNodes != "") SelectedNodes += "\n";
        SelectedNodes += Node.FullPath;
    }

    foreach (TreeNode subNode in Node.Nodes)
    {
        GetCheckedNodes(subNode, ref SelectedNodes);
    }
}


问:
how access value of array list on Struts framework by properties file
```<code>arraylist.add(new ListItem("Activity1", "ActivityName1"));
</code>```

suppose ActivityName1 value store in properties file to provide locale feature.

now how can i access the value of Activity1 key that associate to ActivityName1 value on jsp ( ActivityName1 corresponds to a properties file value) by using Struts.

i want to find the ActivityName1 value that store in properties file by using the Activity1 key in Struts framework.

ContentLicense: CC BY-SA 2.5

Body:
arraylist.add(new ListItem("Activity1", "ActivityName1"));

suppose ActivityName1 value store in properties file to provide locale feature.

now how can i access the value of Activity1 key that associate to ActivityName1 value on jsp ( ActivityName1 corresponds to a properties file value) by using Struts.

i want to find the ActivityName1 value that store in properties file by using the Activity1 key in Struts framework.

Body: <p>Try to Use hashmap..And add that map to the array list..Use


问:
React Native+Redux: connect trouble
I am quite new to React Native / Redux. Trying to study I wrote simpliest example. But it seems connecting doesn't work. Can anybody explain me why?

My code

```<code>import React, { Component } from 'react';
import {
  AppRegistry,
  Text,
  View
} from 'react-native';
import { createStore } from 'redux';
import { connect, Provider } from 'react-redux';

function reducer(state, action) {
  if( state === undefined )
    return {
      age: 31
    };

  return state;
}

var store = createStore(reducer);

const App = (props) => {
  return (
    <View>
      <Text>Store: { JSON.stringify(store.getState()) }</Text>
      <Text>Props: { JSON.stringify(props) }</Text>
    </View>
  );
}

class test0003 extends Component {
  render() {
    return (
      <Provider store={store}>
      <App/>
      </Provider>
    );
  }
}

function mapStateToProps(state) {
  return {
    age: state.age
  }
}
export default connect(
  mapStateToProps
)(App);

AppRegistry.registerComponent('test0003', () => test0003);
</code>```

Output

```<code>Store: {"age":31}
Props: {}
</code>```

connect doesn't work. What's wrong with this code?

答:
Trouble because of Redux requires to separate presentational and container components. Correct code:

```<code>import React, { Component } from 'react';
import {
    AppRegistry,
    Text,
    View
} from 'react-native';
import { createStore } from 'redux';
import { connect, Provider } from 'react-redux';

function reducer(state, action) {
    if( state === undefined )
        return {
            age: 31
        };

    return state;
}

var store = createStore(reducer);

const App = (props) => {
    return (
        <View>
          <Text>Store: { JSON.stringify(store.getState()) }</Text>
          <Text>Props: { JSON.stringify(props) }</Text>
        </View>
    );
}

class test0003 extends Component {
    render() {
        return (
            <Provider store={store}>
              <AppContainer/>
            </Provider>
        );
    }
}

function mapStateToProps(state) {
    return {
        age: state.age
    }
}
var AppContainer = connect(
    mapStateToProps
)(App);

AppRegistry.registerComponent('test0003', () => test0003);
</code>```

connect creates container AppContainer based on presentation App.

Title: React Native+Redux: connect trouble

Body:
I am quite new to React Native / Redux. Trying to study I wrote simpliest example. But it seems connecting doesn't work. Can anybody explain me why?

My code

import React, { Component } from 'react';
import {
  AppRegistry,
  Text,
  View
} from 'react-native';
import { createStore } from 'redux';
import { connect, Provider } from 'react-redux';

function reducer(state, action) {
  if( state === undefined )
    return {
      age: 31
    };

  return state;
}

var store = createStore(reducer);

const App = (props) => {
  return (
    <View>
      <Text>Store: { JSON.stringify(store.getState()) }</Text>
      <Text>Props: { JSON.stringify(props) }</Text>
    </View>
  );
}

class test0003 extends Component {
  render() {
    return (
      <Provider store={store}>
      <App/>
      </Provider>
    );
  }
}

function mapStateToProps(state) {
  return {
    age: state.age
  }
}
export default connect(
  mapStateToProps
)(App);

AppRegistry.registerComponent('test0003', () => test0003);

Output

Store: {"age":31}
Props: {}

connect doesn't work. What's wrong with this code?

Body:
Trouble because of Redux requires to separate presentational and container components. Correct code:

import React, { Component } from 'react';
import {
    AppRegistry,
    Text,
    View
} from 'react-native';
import { createStore } from 'redux';
import { connect, Provider } from 'react-redux';

function reducer(state, action) {
    if( state === undefined )
        return {
            age: 31
        };

    return state;
}

var store = createStore(reducer);

const App = (props) => {
    return (
        <View>
          <Text>Store: { JSON.stringify(store.getState()) }</Text>
          <Text>Props: { JSON.stringify(props) }</Text>
        </View>
    );
}

class test0003 extends Component {
    render() {
        return (
            <Provider store={store}>
              <AppContainer/>
            </Provider>
        );
    }
}

function mapStateToProps(state) {
    return {
        age: state.age
    }
}
var AppContainer = connect(
    mapStateToProps
)(App);

AppRegistry.registerComponent('test0003', () => test0003);

connect creates container AppContainer based on presentation App.


问:
TFS-DASHBOARD - Adding a Enlarge button a widget
Hi i am using Iframe Dashboard widget extension I configured it my self so it can be displayed in "6x6" format which doesn't work, unfortunetly TFS maximum widget size is 4x4 that is too small to show some of my work,How can i add a Enlarge button/function  to the widget?Some of TFS default widgets have that button.

This is my VSS configuration javascript.

```<code>VSS.init({
  explicitNotifyLoaded: true,
  usePlatformStyles: true
});

VSS.require(["TFS/Dashboards/WidgetHelpers"],
  function(WidgetHelpers) {
    WidgetHelpers.IncludeWidgetStyles();
    VSS.register("IframeDashboardWidget", function() {
      var getServerStatus = function(widgetSettings) {
        var $iframe = $('#iframe');
        var settings = JSON.parse(widgetSettings.customSettings.data);
        if (settings && settings.url) {
          $iframe.attr("src", settings.url);
        } else {
          $iframe.attr("src", 'data:text/html,<html><body style="font:1.2em sans-serif;background-color:#008000;color:#ffffff;font:16px Segoe UI,Helvetica Neue,Helvetica,Arial,Verdana,sans-serif"><div>Iframe</div><div>Dashboard</div><div>Widget</div></body></html>');
        }

        return WidgetHelpers.WidgetStatusHelper.Success();
      }

      return {
        load: function(widgetSettings) {
          $iframe.resizeTo();
          return getServerStatus(widgetSettings);
        },
        reload: function(widgetSettings) {
          return getServerStatus(widgetSettings);
        }
      }
    });
    VSS.notifyLoadSucceeded();
  });
</code>```

答:
There is a  concept of supported size in the widget.

supportedSizes

Array of sizes supported by your widget. When a widget supports
  multiple sizes, the first size in the array is the default size of the
  widget. The widget size is specified in terms of the rows and columns
  occupied by the widget in the dashboard grid. One row/column
  corresponds to 160px. Any dimension above 1x1 will get an additional
  10px that represent the gutter between widgets. For example, a 3x2
  widget will be 160*3+10*2 wide and 160*2+10*1 tall. The maximum
  supported size is 4x4.

More details please refer  this tutorial: Add a dashboard widget

Update

You could try to use  VSS.resize() function, but it has the scroll bar. For example, VSS.resize(400,500) (before VSS.notifyLoadSucceeded();).

Body:
Hi i am using Iframe Dashboard widget extension I configured it my self so it can be displayed in "6x6" format which doesn't work, unfortunetly TFS maximum widget size is 4x4 that is too small to show some of my work,How can i add a Enlarge button/function  to the widget?Some of TFS default widgets have that button.

This is my VSS configuration javascript.

VSS.init({
  explicitNotifyLoaded: true,
  usePlatformStyles: true
});

VSS.require(["TFS/Dashboards/WidgetHelpers"],
  function(WidgetHelpers) {
    WidgetHelpers.IncludeWidgetStyles();
    VSS.register("IframeDashboardWidget", function() {
      var getServerStatus = function(widgetSettings) {
        var $iframe = $('#iframe');
        var settings = JSON.parse(widgetSettings.customSettings.data);
        if (settings && settings.url) {
          $iframe.attr("src", settings.url);
        } else {
          $iframe.attr("src", 'data:text/html,
Iframe

Dashboard

Widget
');
        }

        return WidgetHelpers.WidgetStatusHelper.Success();
      }

      return {
        load: function(widgetSettings) {
          $iframe.resizeTo();
          return getServerStatus(widgetSettings);
        },
        reload: function(widgetSettings) {
          return getServerStatus(widgetSettings);
        }
      }
    });
    VSS.notifyLoadSucceeded();
  });


问:
Django: How to mention number of process? like how it is done with Flaks
I am trying to create a simple Fibonacci web service with
* Django and
* Flask

I am using djangorestframework and flask_restful
I am doing this to make some comparison.

with Flask I am able to specify
the number of process or
to use threading etc. with Api in flask_restful

```<code>from flask import Flask, request, Response, jsonify
from flask_restful import abort, Resource, Api, reqparse
api = Api(app)
api.add_resource(Test, '/test/')

app.run(port=1234, host='0.0.0.0', threaded=True) #processes=50)
</code>```

My question, how to specify the same in django rest framework?
From the docs I am not able to find a straight forward answer, yet..

答: Run the Django project through uwsgi or mod_wsgi. </p>

Body:
I am trying to create a simple Fibonacci web service with
* Django and
* Flask

I am using djangorestframework and flask_restful
I am doing this to make some comparison.

with Flask I am able to specify
the number of process or
to use threading etc. with Api in flask_restful

from flask import Flask, request, Response, jsonify
from flask_restful import abort, Resource, Api, reqparse
api = Api(app)
api.add_resource(Test, '/test/')

app.run(port=1234, host='0.0.0.0', threaded=True) #processes=50)

My question, how to specify the same in django rest framework?
From the docs I am not able to find a straight forward answer, yet..


答:
```<code><div class="pace  pace-inactive">
    <div class="pace-progress" style="width: 100%;" data-progress-text="100%" data-progress="99">
        <div class="pace-progress-inner"></div>
    </div>
    <div class="pace-activity"></div>
</div>
</code>```

Remove this html construct. There also should be a javascript/css which triggers the loading bar. You can remove that too.

It's inside your head:

```<code><script src="assets/plugins/pace/pace.min.js"></script>
<link href="assets/plugins/pace/pace.css" rel="stylesheet">
</code>```

Title: Loading Bar on my website

Body:
Please I'm trying to knockoff a loading bar on my site, I have searched through the files, still can't find it. I also tried inspecting using google chrome, but I couldn't target the loader. Kindly help out

Click here for to visit website.

Body:
<div class="pace  pace-inactive">
    <div class="pace-progress" style="width: 100%;" data-progress-text="100%" data-progress="99">
        <div class="pace-progress-inner"></div>
    </div>
    <div class="pace-activity"></div>
</div>

Remove this html construct. There also should be a javascript/css which triggers the loading bar. You can remove that too.

It's inside your head:

<script src="assets/plugins/pace/pace.min.js"></script>
<link href="assets/plugins/pace/pace.css" rel="stylesheet">


问:
Angular 4 GET 403 response
I write an app in Angular 4 that calls a REST API (DJANGO).
The code is as followed:

```<code>export class ForecastUnitService {

private path = 'forecastunit/';
private options;
constructor (private http: Http, private c:CentralService) {
this.options=this.c.createOptions();
}

getForecastUnits(): Observable<ForecastUnit[]> {
return this.http.get(this.c.createURL(this.path),this.options)
  .map(this.extractData)
  .catch(this.handleError);
}
...
}
</code>```

I add options that contains an authorization header, but still I get
a 403 forbidden. However when I try the call with cUrl or Postman or in swagger, with the same token I get results.
So first tought, the headers aren't correct but when I log options I get:

```<code>{"method":null,"headers":{"Authorization":["**Correct Token**"],"Content-Type":["application/json"]},"body":null,"url":null,"withCredentials":null,"responseType":null}
</code>```

So that is not the problem, when I look in the response from Chrome I see the following:

```<code>{"detail":"Authentication credentials were not provided."}
</code>```

So again no credentials, but I really passed them, what is going wrong?

答:
Could you show us the CentralService ?
Also you might want to avoid calling it in the constructor , instead implement OnInit </p>

Title: Angular 4 GET 403 response

Body:
I write an app in Angular 4 that calls a REST API (DJANGO).
The code is as followed:

export class ForecastUnitService {

private path = 'forecastunit/';
private options;
constructor (private http: Http, private c:CentralService) {
this.options=this.c.createOptions();
}

getForecastUnits(): Observable<ForecastUnit[]> {
return this.http.get(this.c.createURL(this.path),this.options)
  .map(this.extractData)
  .catch(this.handleError);
}
...
}

I add options that contains an authorization header, but still I get
a 403 forbidden. However when I try the call with cUrl or Postman or in swagger, with the same token I get results.
So first tought, the headers aren't correct but when I log options I get:

{"method":null,"headers":{"Authorization":["**Correct Token**"],"Content-Type":["application/json"]},"body":null,"url":null,"withCredentials":null,"responseType":null}

So that is not the problem, when I look in the response from Chrome I see the following:

{"detail":"Authentication credentials were not provided."}

So again no credentials, but I really passed them, what is going wrong?


问:
Android Studio 3 unable to build kotlin fragment
Im trying to use Kotlin with Android Studio 3.0 with my existing project.
I have created a fragment using kotlin. Im trying to use the kotlin fragment in my Java Activity. But everytime i try to run it I get

```<code>Error:(209, 5) error: cannot find symbol class BlankFragment
</code>```

BlankFragment.kt

```<code>import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class BlankFragment : Fragment() {

    // TODO: Rename and change types of parameters
    private var mParam1: String? = null
    private var mParam2: String? = null

    private var mListener: OnFragmentInteractionListener? = null

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1)
            mParam2 = getArguments().getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View
            = FragmentUi<Fragment>().createView(AnkoContext.create(ctx, this))

}

class FragmentUi<T>: AnkoComponent<T> {
    override fun createView(ui: AnkoContext<T>) = with(ui) {
        verticalLayout {
            textView {
                text = R.string.app_name

            }
        }
    }
}
</code>```

project - build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.1'
    ext.anko_version = '0.10.1'

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath "io.realm:realm-gradle-plugin:3.0.0"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

app build.gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    signingConfigs {
        splits {
            abi {
                enable true //enables the ABIs split mechanism
                reset() //reset the list of ABIs to be included to an empty string
                include 'x86', 'armeabi', 'armeabi-v7a', 'mips', 'x86_64', 'arm64-v8a'
                universalApk true
            }
        }
    project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]

    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.versionCodeOverride =
                    project.ext.versionCodes.get(output.getFilter(
                            com.android.build.OutputFile.ABI), 0) * 10000000 + android.defaultConfig.versionCode
        }
    }
}
compileSdkVersion 25
buildToolsVersion '26'
defaultConfig {
    applicationId "com.example"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 20
    versionName "v.32"
    testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.releaseConfig
    }
}
packagingOptions {
    exclude 'LICENSE.txt'
}
repositories {
    maven { url "https://jitpack.io" }
}
lintOptions {
    disable "ResourceType"
}
dexOptions {
    javaMaxHeapSize "4g"
}
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.google.code.gson:gson:2.6.2'
    //    compile 'io.realm:realm-android:0.87.5'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.github.jkwiecien:EasyImage:1.3.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.yarolegovich:lovely-dialog:1.0.4'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.github.ParkSangGwon:TedPermission:v1.0.12'
    compile 'com.github.lovetuzitong:MultiImageSelector:1.2'
    compile 'com.github.piotrek1543:CustomSpinner:0.1'
    compile 'com.github.ganfra:material-spinner:1.1.1'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'com.appyvet:materialrangebar:1.3'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.mixpanel.android:mixpanel-android:4.+'
    compile 'com.github.ericwlange:AndroidJSCore:3.0.1'
    compile 'com.android.support:multidex:1.0.0'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    }
    compile "org.jetbrains.anko:anko-sdk25:$anko_version"
    compile "org.jetbrains.anko:anko-sdk25-coroutines:$anko_version"
    compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
    compile files('libs/bcpkix-jdk15on-1.56.0.0.jar')
    compile files('libs/core-1.56.0.0.jar')
    compile files('libs/prov-1.56.0.0.jar')
}
apply plugin: 'com.google.gms.google-services'
</code>```

答:
Finally was able to get it working. For anyone who is going through a similar problem.

project build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.3'
    ext.anko_version = '0.10.1'

    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath "io.realm:realm-gradle-plugin:3.0.0"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

app build.gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'realm-android'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    signingConfigs {
        splits {
            abi {
                enable true //enables the ABIs split mechanism
                reset() //reset the list of ABIs to be included to an empty string
                include 'x86', 'armeabi', 'armeabi-v7a', 'mips', 'x86_64', 'arm64-v8a'
                universalApk true
            }
        }
    project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]

    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.versionCodeOverride =
                    project.ext.versionCodes.get(output.getFilter(
                            com.android.build.OutputFile.ABI), 0) * 10000000 + android.defaultConfig.versionCode
        }
    }
}
compileSdkVersion 25
buildToolsVersion '26'
defaultConfig {
    applicationId "com.example"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 20
    versionName "v.32"
    testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.releaseConfig
    }
}
packagingOptions {
    exclude 'LICENSE.txt'
}
repositories {
    maven { url "https://jitpack.io" }
}
lintOptions {
    disable "ResourceType"
}
dexOptions {
    javaMaxHeapSize "4g"
}
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.google.code.gson:gson:2.6.2'
    //    compile 'io.realm:realm-android:0.87.5'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.github.jkwiecien:EasyImage:1.3.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.yarolegovich:lovely-dialog:1.0.4'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.github.ParkSangGwon:TedPermission:v1.0.12'
    compile 'com.github.lovetuzitong:MultiImageSelector:1.2'
    compile 'com.github.piotrek1543:CustomSpinner:0.1'
    compile 'com.github.ganfra:material-spinner:1.1.1'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'com.appyvet:materialrangebar:1.3'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.mixpanel.android:mixpanel-android:4.+'
    compile 'com.github.ericwlange:AndroidJSCore:3.0.1'
    compile 'com.android.support:multidex:1.0.0'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    }
    compile "org.jetbrains.anko:anko-sdk25:$anko_version"
    compile "org.jetbrains.anko:anko-sdk25-coroutines:$anko_version"
    compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    compile files('libs/bcpkix-jdk15on-1.56.0.0.jar')
    compile files('libs/core-1.56.0.0.jar')
    compile files('libs/prov-1.56.0.0.jar')
}
apply plugin: 'com.google.gms.google-services'
</code>```

Body:
Im trying to use Kotlin with Android Studio 3.0 with my existing project.
I have created a fragment using kotlin. Im trying to use the kotlin fragment in my Java Activity. But everytime i try to run it I get

Error:(209, 5) error: cannot find symbol class BlankFragment

BlankFragment.kt

import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class BlankFragment : Fragment() {

    // TODO: Rename and change types of parameters
    private var mParam1: String? = null
    private var mParam2: String? = null

    private var mListener: OnFragmentInteractionListener? = null

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1)
            mParam2 = getArguments().getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View
            = FragmentUi<Fragment>().createView(AnkoContext.create(ctx, this))

}

class FragmentUi<T>: AnkoComponent<T> {
    override fun createView(ui: AnkoContext<T>) = with(ui) {
        verticalLayout {
            textView {
                text = R.string.app_name

            }
        }
    }
}

project - build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.1'
    ext.anko_version = '0.10.1'

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath "io.realm:realm-gradle-plugin:3.0.0"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app build.gradle

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    signingConfigs {
        splits {
            abi {
                enable true //enables the ABIs split mechanism
                reset() //reset the list of ABIs to be included to an empty string
                include 'x86', 'armeabi', 'armeabi-v7a', 'mips', 'x86_64', 'arm64-v8a'
                universalApk true
            }
        }
    project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]

    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.versionCodeOverride =
                    project.ext.versionCodes.get(output.getFilter(
                            com.android.build.OutputFile.ABI), 0) * 10000000 + android.defaultConfig.versionCode
        }
    }
}
compileSdkVersion 25
buildToolsVersion '26'
defaultConfig {
    applicationId "com.example"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 20
    versionName "v.32"
    testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.releaseConfig
    }
}
packagingOptions {
    exclude 'LICENSE.txt'
}
repositories {
    maven { url "https://jitpack.io" }
}
lintOptions {
    disable "ResourceType"
}
dexOptions {
    javaMaxHeapSize "4g"
}
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.google.code.gson:gson:2.6.2'
    //    compile 'io.realm:realm-android:0.87.5'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.github.jkwiecien:EasyImage:1.3.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.yarolegovich:lovely-dialog:1.0.4'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.github.ParkSangGwon:TedPermission:v1.0.12'
    compile 'com.github.lovetuzitong:MultiImageSelector:1.2'
    compile 'com.github.piotrek1543:CustomSpinner:0.1'
    compile 'com.github.ganfra:material-spinner:1.1.1'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'com.appyvet:materialrangebar:1.3'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.mixpanel.android:mixpanel-android:4.+'
    compile 'com.github.ericwlange:AndroidJSCore:3.0.1'
    compile 'com.android.support:multidex:1.0.0'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    }
    compile "org.jetbrains.anko:anko-sdk25:$anko_version"
    compile "org.jetbrains.anko:anko-sdk25-coroutines:$anko_version"
    compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
    compile files('libs/bcpkix-jdk15on-1.56.0.0.jar')
    compile files('libs/core-1.56.0.0.jar')
    compile files('libs/prov-1.56.0.0.jar')
}
apply plugin: 'com.google.gms.google-services'

Body:
Finally was able to get it working. For anyone who is going through a similar problem.

project build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.3'
    ext.anko_version = '0.10.1'

    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath "io.realm:realm-gradle-plugin:3.0.0"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app build.gradle

apply plugin: 'com.android.application'
apply plugin: 'realm-android'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    signingConfigs {
        splits {
            abi {
                enable true //enables the ABIs split mechanism
                reset() //reset the list of ABIs to be included to an empty string
                include 'x86', 'armeabi', 'armeabi-v7a', 'mips', 'x86_64', 'arm64-v8a'
                universalApk true
            }
        }
    project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]

    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.versionCodeOverride =
                    project.ext.versionCodes.get(output.getFilter(
                            com.android.build.OutputFile.ABI), 0) * 10000000 + android.defaultConfig.versionCode
        }
    }
}
compileSdkVersion 25
buildToolsVersion '26'
defaultConfig {
    applicationId "com.example"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 20
    versionName "v.32"
    testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.releaseConfig
    }
}
packagingOptions {
    exclude 'LICENSE.txt'
}
repositories {
    maven { url "https://jitpack.io" }
}
lintOptions {
    disable "ResourceType"
}
dexOptions {
    javaMaxHeapSize "4g"
}
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.google.code.gson:gson:2.6.2'
    //    compile 'io.realm:realm-android:0.87.5'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.github.jkwiecien:EasyImage:1.3.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.yarolegovich:lovely-dialog:1.0.4'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.github.ParkSangGwon:TedPermission:v1.0.12'
    compile 'com.github.lovetuzitong:MultiImageSelector:1.2'
    compile 'com.github.piotrek1543:CustomSpinner:0.1'
    compile 'com.github.ganfra:material-spinner:1.1.1'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'com.appyvet:materialrangebar:1.3'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.mixpanel.android:mixpanel-android:4.+'
    compile 'com.github.ericwlange:AndroidJSCore:3.0.1'
    compile 'com.android.support:multidex:1.0.0'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    }
    compile "org.jetbrains.anko:anko-sdk25:$anko_version"
    compile "org.jetbrains.anko:anko-sdk25-coroutines:$anko_version"
    compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    compile files('libs/bcpkix-jdk15on-1.56.0.0.jar')
    compile files('libs/core-1.56.0.0.jar')
    compile files('libs/prov-1.56.0.0.jar')
}
apply plugin: 'com.google.gms.google-services'


问:
Range Selection in Matlab
I defined a matrix 6 by 6 and want to make a change in values in some ranges.

```<code>c = floor(rand(6,6) * 100)
</code>```

the result:

```<code>22    26    10     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25    73    81    16    69    53
29    34    26    17    69    65
61    58    59    42    63    40
</code>```

then I run:

```<code>c(c(1:3,:)<17) = 0

22     0     0     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25     0     0    16    69    53
29    34     0    17    69    65
61    58    59    42    63    40
</code>```

I want to make elements in rows between 1 and 3 which are less than 17 zero, but the result seems wrong to me! any idea?

答:
Use a logical index built from two conditions: element is less than the threshold and row index is within the set of target rows.

```<code>th = 17;                                                  % threshold
rows = [1 2 3];                                           % target rows
ind = bsxfun(@and, c<th, ismember(1:size(c,1), rows).');  % logical index
c(ind) = 0;                                               % set entries to 0
</code>```

For your example input

```<code>c = [22    26    10     2     9     3
     38    82    90    42    59     6
     58    98    87    31    47    31
     25    73    81    16    69    53
     29    34    26    17    69    65
     61    58    59    42    63    40]
</code>```

this gives

```<code>c =
    22    26     0     0     0     0
    38    82    90    42    59     0
    58    98    87    31    47    31
    25    73    81    16    69    53
    29    34    26    17    69    65
    61    58    59    42    63    40
</code>```

Title: Range Selection in Matlab

Body:
I defined a matrix 6 by 6 and want to make a change in values in some ranges.

c = floor(rand(6,6) * 100)

the result:

22    26    10     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25    73    81    16    69    53
29    34    26    17    69    65
61    58    59    42    63    40

then I run:

c(c(1:3,:)<17) = 0

22     0     0     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25     0     0    16    69    53
29    34     0    17    69    65
61    58    59    42    63    40

I want to make elements in rows between 1 and 3 which are less than 17 zero, but the result seems wrong to me! any idea?

Body:
Use a logical index built from two conditions: element is less than the threshold and row index is within the set of target rows.

th = 17;                                                  % threshold
rows = [1 2 3];                                           % target rows
ind = bsxfun(@and, c<th, ismember(1:size(c,1), rows).');  % logical index
c(ind) = 0;                                               % set entries to 0

For your example input

c = [22    26    10     2     9     3
     38    82    90    42    59     6
     58    98    87    31    47    31
     25    73    81    16    69    53
     29    34    26    17    69    65
     61    58    59    42    63    40]

this gives

c =
    22    26     0     0     0     0
    38    82    90    42    59     0
    58    98    87    31    47    31
    25    73    81    16    69    53
    29    34    26    17    69    65
    61    58    59    42    63    40


问:
CSS change affect 2 elements?
I wanted to place one of menu pages into border with red background, so i used this CSS to do that:

```<code>.page-item-4  {
 border:3px; border-style:solid; border-color:#000; padding: 1em;background:
 red;font-weight: bold;
  }
</code>```

and works OK when you are on homepage, or some other page. when click on SHOP page both elements : "SHOP" and "Programmes personnalisés" got the same styling. Why ? I want only SHOP to use that styling. Can someone to tell me where is issue? Issue is present only in this page.

答:
On this page : https://nutrifit-shop.com/programmes-personnalises/

```<code><li class="page_item page-item-497 current_page_item">
<a href="https://nutrifit-shop.com/programmes-personnalises/">Programmes personnalisés</a>
</li>
</code>```

But on this page : https://nutrifit-shop.com/boutique/

```<code><li class="page_item page-item-4 current_page_item97">
<a href="https://nutrifit-shop.com/programmes-personnalises/">Programmes personnalisés</a>
</li>
</code>```

On the Shop page, your class should be

```<code>page_item page-item-497 current_page_item
</code>```

Instead of

```<code>page_item page-item-4 current_page_item97
</code>```

Title: CSS change affect 2 elements?

Body:
I wanted to place one of menu pages into border with red background, so i used this CSS to do that:

.page-item-4  {
 border:3px; border-style:solid; border-color:#000; padding: 1em;background:
 red;font-weight: bold;
  }

and works OK when you are on homepage, or some other page. when click on SHOP page both elements : "SHOP" and "Programmes personnalisés" got the same styling. Why ? I want only SHOP to use that styling. Can someone to tell me where is issue? Issue is present only in this page.

Body:
On this page : https://nutrifit-shop.com/programmes-personnalises/

<li class="page_item page-item-497 current_page_item">
<a href="https://nutrifit-shop.com/programmes-personnalises/">Programmes personnalisés</a>
</li>

But on this page : https://nutrifit-shop.com/boutique/

<li class="page_item page-item-4 current_page_item97">
<a href="https://nutrifit-shop.com/programmes-personnalises/">Programmes personnalisés</a>
</li>

On the Shop page, your class should be

page_item page-item-497 current_page_item

Instead of

page_item page-item-4 current_page_item97


问:
Sort array by date php
Array keys are date and want to sort array by date in Asending order. Following is array:</p>

```<code>Array
(
    [07/14/2017] => Array
        (
            [ID] => 5442
            [post_content] => Test1
            [post_title] => Testevents1
        )

    [01/11/2017] => Array
        (
            [ID] => 5443
            [post_content] => Test2
            [post_title] => Testevents2
        )
)
</code>```

答:
You can use uksort to do that:

```<code>uksort($arr, function ($a, $b) {
    $t1 = strtotime($a);
    $t2 = strtotime($b);
    if ($t1 == $t2) {
        return 0;
    }
    return ($t1 > $t2) ? 1 : -1;
});
</code>```

Title: Sort array by date php

Body:
Array keys are date and want to sort array by date in Asending order. Following is array:

Array
(
    [07/14/2017] => Array
        (
            [ID] => 5442
            [post_content] => Test1
            [post_title] => Testevents1
        )

    [01/11/2017] => Array
        (
            [ID] => 5443
            [post_content] => Test2
            [post_title] => Testevents2
        )
)

Body:
You can use uksort to do that:

uksort($arr, function ($a, $b) {
    $t1 = strtotime($a);
    $t2 = strtotime($b);
    if ($t1 == $t2) {
        return 0;
    }
    return ($t1 > $t2) ? 1 : -1;
});


问:
Android EditText Transparent Background
I want to have a transparent background for Android EditText widget. How is that possible?</p>

答:
set this in layout will work

```<code>android:background="@color/transparent
</code>```

and add this in colors.xml

```<code><color name="transparent">#00000000</color>
</code>```

Title: Android EditText Transparent Background

Body:
set this in layout will work

android:background="@color/transparent

and add this in colors.xml

<color name="transparent">#00000000</color>


问:
How can I change the extension name in a string with bash?
I want to translate the following python code to bash. The code changes the extension name to .html and runs Safari to open it.

```<code>#!/usr/bin/env python
import os.path
import os

oldName = $TM_FILEPATH
(name, ext) = os.path.splitext(oldName)
rename = name + ".html"
os.system("open -a Safari %s" % rename)
</code>```

How can I change the file extension with bash?

答:
If you happen to know the extension you can switch it like this:</p>

```<code>$ MY_FILE=file.html
$ NEW_EXT=${MY_FILE/html/php}
$ echo ${NEW_EXT}
file.php
</code>```

Body:
I want to translate the following python code to bash. The code changes the extension name to .html and runs Safari to open it.

#!/usr/bin/env python
import os.path
import os

oldName = $TM_FILEPATH
(name, ext) = os.path.splitext(oldName)
rename = name + ".html"
os.system("open -a Safari %s" % rename)

How can I change the file extension with bash?

Body:
If you happen to know the extension you can switch it like this:

$ MY_FILE=file.html
$ NEW_EXT=${MY_FILE/html/php}
$ echo ${NEW_EXT}
file.php


问:
Remove Custom button from Datatable

How can I remove the Copy, CSV, Excel, PDF and Print button on the top right corner. They are the default feature of datatables I suppose. I am trying to remove them but I did not find nay information on how can I remove or hide them.

Following is the code

```<code>oTable = $('#lenderList').dataTable(
        {
            bServerSide: true,
            bProcessing: true,
            searching: true,
            sAjaxSource: "loanAdminAjax?ajax=true&searchCol="+$('#category').val(),
            sServerMethod: 'POST',
            sPaginationType: "full_numbers",
            bPaginate: true,
            bLengthChange: true,
            bFilter: true,
            bSort: true,
            bInfo: true,
            bAutoWidth: true,

            aoColumns: [
                {
                    "sName": "loanApplicationNumber",
                    mData: "loanApplicationNumber"
                },
                {
                    "sName": "name",
                    mData: "name"
                },
                {
                    "sName": "submissionDate",
                    mData: "submissionDate"
                },
                {
                    "sName": "kycEmailId",
                    mData: "kycEmailId"
                },
                {
                    "sName": "appVersion",
                    mData: "appVersion"
                },
                {
                    "sName": "documentStatus",
                    mData: "documentStatus"
                },
                {
                    "sName": "latestRemark",
                    mData: "latestRemark"
                },
                {
                    "sName": "appName",
                    mData: "appName"
                }

            ],
            "dom": 'T<"clear"><"button">lfrtip'

        }
    );
</code>```

答:
Below is the code to show the buttons,
you should remove the buttons which you want to.</p>

```<code>$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    } );
} )
</code>```

Title: Remove Custom button from Datatable

Body:
How can I remove the Copy, CSV, Excel, PDF and Print button on the top right corner. They are the default feature of datatables I suppose. I am trying to remove them but I did not find nay information on how can I remove or hide them.

Following is the code

oTable = $('#lenderList').dataTable(
        {
            bServerSide: true,
            bProcessing: true,
            searching: true,
            sAjaxSource: "loanAdminAjax?ajax=true&searchCol="+$('#category').val(),
            sServerMethod: 'POST',
            sPaginationType: "full_numbers",
            bPaginate: true,
            bLengthChange: true,
            bFilter: true,
            bSort: true,
            bInfo: true,
            bAutoWidth: true,

            aoColumns: [
                {
                    "sName": "loanApplicationNumber",
                    mData: "loanApplicationNumber"
                },
                {
                    "sName": "name",
                    mData: "name"
                },
                {
                    "sName": "submissionDate",
                    mData: "submissionDate"
                },
                {
                    "sName": "kycEmailId",
                    mData: "kycEmailId"
                },
                {
                    "sName": "appVersion",
                    mData: "appVersion"
                },
                {
                    "sName": "documentStatus",
                    mData: "documentStatus"
                },
                {
                    "sName": "latestRemark",
                    mData: "latestRemark"
                },
                {
                    "sName": "appName",
                    mData: "appName"
                }

            ],
            "dom": 'T<"clear"><"button">lfrtip'

        }
    );

Body:
Below is the code to show the buttons,
you should remove the buttons which you want to.

$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    } );
} )


问:
Group by and count number of unique days
I have a Pandas DataFrame with the following columns :

```<code>COLS=['DATA','DSC_MATERIAL','DSC_FORNECEDOR','MTR_QUANTIDADE','MTR_VALOR','PRECO']
df2=df[COLS]
</code>```

I'm trying to do a groupby to analyse the data and I'm using this code:

```<code>f={'MTR_VALOR':['sum'],'MTR_QUANTIDADE':['sum'],'preco':['mean'], 'DATE': lambda x: x.nunique()}
df_milho.groupby(['DSC_MATERIAL','DSC_FORNECEDOR']).agg(f)
</code>```

For the DATE I want the number of unique dates, but what I'm getting is the following:

I'm assuming this is because the calculation is being done correctly but it is keeping the datetime64[ns] format. Any idea how I can solve this?

答:
For me it works nice in pandas 0.20.2.

```<code>np.random.seed(45)
rng = pd.date_range('2017-04-03', periods=10)
df_milho = pd.DataFrame({'DATE': rng,
                        'preco': np.random.randint(10, size=10),
                        'MTR_VALOR': np.random.randint(10, size=10),
                        'MTR_QUANTIDADE': np.random.randint(10, size=10),
                        'DSC_FORNECEDOR':list('aaeeeeeddd'),
                        'DSC_MATERIAL':list('aaaabbbddd')})
print (df_milho)
        DATE DSC_FORNECEDOR DSC_MATERIAL  MTR_QUANTIDADE  MTR_VALOR  preco
0 2017-04-03              a            a               8          6      3
1 2017-04-04              a            a               4          8      0
2 2017-04-05              e            a               6          7      5
3 2017-04-06              e            a               4          8      3
4 2017-04-07              e            b               9          5      4
5 2017-04-08              e            b               1          2      9
6 2017-04-09              e            b               6          8      8
7 2017-04-10              d            d               8          1      1
8 2017-04-11              d            d               8          6      5
9 2017-04-12              d            d               1          4      9

f={'MTR_VALOR':'sum','MTR_QUANTIDADE':['sum'],'preco':['mean'],'DATE': lambda x: x.nunique()}
df1 = df_milho.groupby(['DSC_MATERIAL','DSC_FORNECEDOR']).agg(f)
print (df1)
                                DATE preco MTR_QUANTIDADE MTR_VALOR
                            <lambda>  mean            sum       sum
DSC_MATERIAL DSC_FORNECEDOR
a            a                     2   1.5             12        14
             e                     2   4.0             10        15
b            e                     3   7.0             16        15
d            d                     3   5.0             17        11
</code>```

But it seems there can be another solutions with pd.Series.nunique:

```<code>f={'MTR_VALOR':'sum','MTR_QUANTIDADE':['sum'],
   'preco':['mean'], 'DATE': lambda x: pd.Series.nunique(x)}
df1 = df_milho.groupby(['DSC_MATERIAL','DSC_FORNECEDOR']).agg(f)
print (df1)
                                DATE preco MTR_QUANTIDADE MTR_VALOR
                            <lambda>  mean            sum       sum
DSC_MATERIAL DSC_FORNECEDOR
a            a                     2   1.5             12        14
             e                     2   4.0             10        15
b            e                     3   7.0             16        15
d            d                     3   5.0             17        11
</code>```

Or nunique with rename:

```<code>f={'MTR_VALOR':'sum','MTR_QUANTIDADE':'sum','preco':'mean', 'DATE': 'nunique'}
d = {'DATE':'uniquedates','preco':'precomean',
    'MTR_QUANTIDADE':'MTR_QUANTIDADEsum','MTR_VALOR':'MTR_VALORsum'}
df1 = df_milho.groupby(['DSC_MATERIAL','DSC_FORNECEDOR']).agg(f).rename(columns=d)
print (df1)
                             uniquedates  precomean  MTR_QUANTIDADEsum  \
DSC_MATERIAL DSC_FORNECEDOR
a            a                         2        1.5                 12
             e                         2        4.0                 10
b            e                         3        7.0                 16
d            d                         3        5.0                 17

                             MTR_VALORsum
DSC_MATERIAL DSC_FORNECEDOR
a            a                         14
             e                         15
b            e                         15
d            d                         11
</code>```

Body:
I have a Pandas DataFrame with the following columns :

COLS=['DATA','DSC_MATERIAL','DSC_FORNECEDOR','MTR_QUANTIDADE','MTR_VALOR','PRECO']
df2=df[COLS]

I'm trying to do a groupby to analyse the data and I'm using this code:

f={'MTR_VALOR':['sum'],'MTR_QUANTIDADE':['sum'],'preco':['mean'], 'DATE': lambda x: x.nunique()}
df_milho.groupby(['DSC_MATERIAL','DSC_FORNECEDOR']).agg(f)

For the DATE I want the number of unique dates, but what I'm getting is the following:

I'm assuming this is because the calculation is being done correctly but it is keeping the datetime64[ns] format. Any idea how I can solve this?

Body:
For me it works nice in pandas 0.20.2.

np.random.seed(45)
rng = pd.date_range('2017-04-03', periods=10)
df_milho = pd.DataFrame({'DATE': rng,
                        'preco': np.random.randint(10, size=10),
                        'MTR_VALOR': np.random.randint(10, size=10),
                        'MTR_QUANTIDADE': np.random.randint(10, size=10),
                        'DSC_FORNECEDOR':list('aaeeeeeddd'),
                        'DSC_MATERIAL':list('aaaabbbddd')})
print (df_milho)
        DATE DSC_FORNECEDOR DSC_MATERIAL  MTR_QUANTIDADE  MTR_VALOR  preco
0 2017-04-03              a            a               8          6      3
1 2017-04-04              a            a               4          8      0
2 2017-04-05              e            a               6          7      5
3 2017-04-06              e            a               4          8      3
4 2017-04-07              e            b               9          5      4
5 2017-04-08              e            b               1          2      9
6 2017-04-09              e            b               6          8      8
7 2017-04-10              d            d               8          1      1
8 2017-04-11              d            d               8          6      5
9 2017-04-12              d            d               1          4      9

f={'MTR_VALOR':'sum','MTR_QUANTIDADE':['sum'],'preco':['mean'],'DATE': lambda x: x.nunique()}
df1 = df_milho.groupby(['DSC_MATERIAL','DSC_FORNECEDOR']).agg(f)
print (df1)
                                DATE preco MTR_QUANTIDADE MTR_VALOR
                            <lambda>  mean            sum       sum
DSC_MATERIAL DSC_FORNECEDOR
a            a                     2   1.5             12        14
             e                     2   4.0             10        15
b            e                     3   7.0             16        15
d            d                     3   5.0             17        11

But it seems there can be another solutions with pd.Series.nunique:

f={'MTR_VALOR':'sum','MTR_QUANTIDADE':['sum'],
   'preco':['mean'], 'DATE': lambda x: pd.Series.nunique(x)}
df1 = df_milho.groupby(['DSC_MATERIAL','DSC_FORNECEDOR']).agg(f)
print (df1)
                                DATE preco MTR_QUANTIDADE MTR_VALOR
                            <lambda>  mean            sum       sum
DSC_MATERIAL DSC_FORNECEDOR
a            a                     2   1.5             12        14
             e                     2   4.0             10        15
b            e                     3   7.0             16        15
d            d                     3   5.0             17        11

Or nunique with rename:

f={'MTR_VALOR':'sum','MTR_QUANTIDADE':'sum','preco':'mean', 'DATE': 'nunique'}
d = {'DATE':'uniquedates','preco':'precomean',
    'MTR_QUANTIDADE':'MTR_QUANTIDADEsum','MTR_VALOR':'MTR_VALORsum'}
df1 = df_milho.groupby(['DSC_MATERIAL','DSC_FORNECEDOR']).agg(f).rename(columns=d)
print (df1)
                             uniquedates  precomean  MTR_QUANTIDADEsum  \
DSC_MATERIAL DSC_FORNECEDOR
a            a                         2        1.5                 12
             e                         2        4.0                 10
b            e                         3        7.0                 16
d            d                         3        5.0                 17

                             MTR_VALORsum
DSC_MATERIAL DSC_FORNECEDOR
a            a                         14
             e                         15
b            e                         15
d            d                         11


问:
Problems with bcp utility
I want to extract a SELCET query with the bcp utility. But it doesn't work. MS SQL underlines "bcp" marks it.

```<code>DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + @DBName+']');

PRINT (' DATABASE SELECTED: '+ @DBName)

bcp "SELECT [Role ID],[Name] FROM [dbo].[Permission Set]" out "C:\Users\Public\Documents\test.txt" -c -T
</code>```

The error message is:

```<code>Msg 102, Level 15, State 1, Line 19
Incorrect syntax near 'bcp'.
</code>```

Does anybody know the correct syntax? If I compare it with the examples on the docs.microsoft website (https://learn.microsoft.com/en-us/sql/tools/bcp-utility#o) I do not see my mistake.

答:
You need to use xp_cmdshell procedure to execute the bcp command in T-SQL script

```<code>Declare @sql varchar(8000)
Select @sql = 'bcp "SELECT [Role ID],[Name] FROM [dbo].[Permission Set]" out "C:\Users\Public\Documents\test.txt" -c -T'
Exec master..xp_cmdshell @sql
</code>```

Title: Problems with bcp utility

Body:
I want to extract a SELCET query with the bcp utility. But it doesn't work. MS SQL underlines "bcp" marks it.

DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + @DBName+']');

PRINT (' DATABASE SELECTED: '+ @DBName)

bcp "SELECT [Role ID],[Name] FROM [dbo].[Permission Set]" out "C:\Users\Public\Documents\test.txt" -c -T

The error message is:

Msg 102, Level 15, State 1, Line 19
Incorrect syntax near 'bcp'.

Does anybody know the correct syntax? If I compare it with the examples on the docs.microsoft website (https://learn.microsoft.com/en-us/sql/tools/bcp-utility#o) I do not see my mistake.

Body:
You need to use xp_cmdshell procedure to execute the bcp command in T-SQL script

Declare @sql varchar(8000)
Select @sql = 'bcp "SELECT [Role ID],[Name] FROM [dbo].[Permission Set]" out "C:\Users\Public\Documents\test.txt" -c -T'
Exec master..xp_cmdshell @sql


问:
How to give space between two cells in tableview?
I want a space between two cell in table view,

I want cell like this,

How can i do that?

答:
1) first create 2 sections in table view.
2) create an empty cell.
3) create the cell with data you want to display.
4) use the method

(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section==0) {

if (indexPath.row % 2 != 1) {
            return 15.0;
        } else {
return 100;
        }
}
else

```<code>if (indexPath.row % 2 != 1) {
    return 100.0;
} else {
    return 15.0;
}
</code>```

}

It will add space between the cells. It worked for me.

Body:
1) first create 2 sections in table view.
2) create an empty cell.
3) create the cell with data you want to display.
4) use the method

(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section==0) {

if (indexPath.row % 2 != 1) {
            return 15.0;
        } else {
return 100;
        }
}
else

if (indexPath.row % 2 != 1) {
    return 100.0;
} else {
    return 15.0;
}

}

It will add space between the cells. It worked for me.


问:
How can we make the backward button disable in the all browsers?

Possible Duplicate:

  Disable browser's back button

Hi everyone,I have a portal site and i want to make the backward button to disable state after the user gets logout.Is it possible by C# programming?Or we need to go for client side scripts like  Javascript or jquery?Please help me regarding this .

答:
You can't do anything on the client with server-side code (C#) except send content to the browser.

There are Javascript things you can do to manipulate the history to a degree, but my guess is you have an architecture problem here; There's no reason you should prevent clicking 'back' simply because they have logged out. Your application should detect that they are logged out, and present them with appropriate content.

Finally, to answer your question: You can't just disable the back button. Period.


问:
Using Laravel query builder method whereIn() with sub query
I am developing a Web Application using Laravel 5.3. I am now having an issue with Laravel query builder method, whereIn.

I have table like this.

```<code>student - id, name, dob
course - id, code
student_course -  student_id, course_id
</code>```

What I want to do is I want to get students searching by course_id of student_course table without joining any table. In manual query, I do like this.

```<code>SELECT * FROM `student` WHERE `student`.`id` IN (SELECT `student_id` FROM `student_course` WHRE `course_id`= ?)
</code>```

So now when I try to convert it into Laravel query builder, I have a problem. Here is my code:

```<code>DB::table('student')->whereIn('id',[ "Here I want to run sub query" ])->get();
</code>```

As you can see in the second parameter of whereIn(), I get problem. In this scenario, do I need to run raw query? How can I run raw query as second parameter? If not, how can I filter by course_id just in one query like above and not joining to any table?

答:
If you want pass through model, you can use:</p>

```<code>$res = Student::whereIn('id',StudentCourse::where('course_id',$course_id)->pluck('student_id')->toArray())->get();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am developing a Web Application using Laravel 5.3. I am now having an issue with Laravel query builder method, whereIn.

I have table like this.

student - id, name, dob
course - id, code
student_course -  student_id, course_id

What I want to do is I want to get students searching by course_id of student_course table without joining any table. In manual query, I do like this.

SELECT * FROM `student` WHERE `student`.`id` IN (SELECT `student_id` FROM `student_course` WHRE `course_id`= ?)

So now when I try to convert it into Laravel query builder, I have a problem. Here is my code:

DB::table('student')->whereIn('id',[ "Here I want to run sub query" ])->get();

As you can see in the second parameter of whereIn(), I get problem. In this scenario, do I need to run raw query? How can I run raw query as second parameter? If not, how can I filter by course_id just in one query like above and not joining to any table?

Body:
If you want pass through model, you can use:

$res = Student::whereIn('id',StudentCourse::where('course_id',$course_id)->pluck('student_id')->toArray())->get();


问:
How to build a machine learning system (smart system) that updates automatically?
I am kinda a newbie in machine learning. I have done lots of learning related to data analysis and ML algorithms, and I've got very good results and understanding of the algorithms. However, my approaches are normally getting datasets, writing scripts or notebooks to solve the problems and that's pretty much it. Which means, no matter how fancy I create a script, I have to run the script everytime for each update, this is not enough.

I think that machine learning is more than that, and there are already smart systems that are constantly updating their systems automatically, and I am really interested in that, but can't really find any good materials that dive deep into that field.

Let's just say, like the classic example, there's a website that has a ML system at the backend that identifies iris categories, and it's visitors constantly upload new observations of irises and the visitors get the category of the iris they upload, and the backend system continues to improve accordingly.

How can I get to learn thing like this? Would be super keen to dive into this field.

I'd really appreciate all your opinions!

Thanks a lot!

答:
you are asking "Incremental way of learning " !!

it's depends on what task are you doing. you can not apply incremental learning everywhere. the real problem is when we train , in the process of training , there are many other things that are related(inter dependent). which gets changed during a new cycle.

so if you can make your algorithm independent , then you can do "incremental way of learning" !!


问:
How to make model class for following JSON response in swift iOS
Hi i am beginner  for swift ios and my requirement is have to display Json response to table list i got response from web-services and response seems like below

MY requirement is how to map that model classes to Array and how to display them in tableList can some one help me please

JsonResponse:-

```<code>[{
  "_id" : "5470def9e0c0be27780121d7",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
  "name" : "Mondo",
  "hasVip" : false,
  "location" : {
    "city" : "Madrid"
  }
}, {
  "_id" : "540b2ff281b30f3504a1c72f",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
  "name" : "Teatro Kapital",
  "hasVippler" : false,
  "location" : {
    "address" : "Atocha, 125",
    "city" : "Madrid"
  }
}, {
  "_id" : "540cd44581b30f3504a1c73b",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
  "name" : "Charada",
  "hasVippler" : false,
  "location" : {
    "address" : "La Bola, 13",
    "city" : "Madrid"
  }
}]
</code>```

mapping:

Club:-

```<code>class Club {

    var id: String = ""
    var name: String = ""
    var imageUrl: String = ""
    var hasVip: Bool = false
    var desc: String = ""
    var location: [Location] = []

}
</code>```

Location:-

```<code>class Location {

    var country: String = ""
    var city: String = ""
    var address: String = ""
    var zip: String = ""
    var underground: [String] = []

}
</code>```

NSURlSession code:-

```<code>class BackGroundPostCall: NSObject {

    var delegate:PostProtocol?

    func callPostService(url:String,params:NSDictionary){

        print("url is===>\(url)")

        let request = NSMutableURLRequest(URL: NSURL(string:url)!)

        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

        let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
                    print("Response: \(json)")
                } else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
        }

        task.resume()
    }
}
</code>```

答:
Model class:

```<code>class test : Unboxable {
let id : String
let imageURl : String
let name : String
let hasVip : Bool
let city : String

required init(unboxer: Unboxer) throws {
    self.id = unboxer.unbox(key: "id") ?? ""
    self.imageURl = unboxer.unbox(key: "imageUrl") ?? ""
    self.name = unboxer.unbox(key: "name") ?? ""
    self.hasVip = unboxer.unbox(key: "hasVip") ?? false
    self.city = (unboxer.unbox(key: "city") ?? nil)!
}
}
</code>```

parse json:

```<code>if let object = json as? [Any] {
                // json is an array

                var data :[test] = []
                for respObject in object {

                    var dict = respObject as? Dictionary<String,AnyObject>
                    dict?["city"] = dict?["location"]?["city"] as AnyObject
                     let result1: [test] = try unbox(dictionaries: [dict!])
                    data.append(contentsOf: result1)

                }

                print(data)
</code>```

For more details follow
https://github.com/JohnSundell/Unbox

Body:
Hi i am beginner  for swift ios and my requirement is have to display Json response to table list i got response from web-services and response seems like below

MY requirement is how to map that model classes to Array and how to display them in tableList can some one help me please

JsonResponse:-

[{
  "_id" : "5470def9e0c0be27780121d7",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
  "name" : "Mondo",
  "hasVip" : false,
  "location" : {
    "city" : "Madrid"
  }
}, {
  "_id" : "540b2ff281b30f3504a1c72f",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
  "name" : "Teatro Kapital",
  "hasVippler" : false,
  "location" : {
    "address" : "Atocha, 125",
    "city" : "Madrid"
  }
}, {
  "_id" : "540cd44581b30f3504a1c73b",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
  "name" : "Charada",
  "hasVippler" : false,
  "location" : {
    "address" : "La Bola, 13",
    "city" : "Madrid"
  }
}]

mapping:

Club:-

class Club {

    var id: String = ""
    var name: String = ""
    var imageUrl: String = ""
    var hasVip: Bool = false
    var desc: String = ""
    var location: [Location] = []

}

Location:-

class Location {

    var country: String = ""
    var city: String = ""
    var address: String = ""
    var zip: String = ""
    var underground: [String] = []

}

NSURlSession code:-

class BackGroundPostCall: NSObject {

    var delegate:PostProtocol?

    func callPostService(url:String,params:NSDictionary){

        print("url is===>\(url)")

        let request = NSMutableURLRequest(URL: NSURL(string:url)!)

        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

        let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
                    print("Response: \(json)")
                } else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
        }

        task.resume()
    }
}

Body:
Model class:

class test : Unboxable {
let id : String
let imageURl : String
let name : String
let hasVip : Bool
let city : String

required init(unboxer: Unboxer) throws {
    self.id = unboxer.unbox(key: "id") ?? ""
    self.imageURl = unboxer.unbox(key: "imageUrl") ?? ""
    self.name = unboxer.unbox(key: "name") ?? ""
    self.hasVip = unboxer.unbox(key: "hasVip") ?? false
    self.city = (unboxer.unbox(key: "city") ?? nil)!
}
}

parse json:

if let object = json as? [Any] {
                // json is an array

                var data :[test] = []
                for respObject in object {

                    var dict = respObject as? Dictionary<String,AnyObject>
                    dict?["city"] = dict?["location"]?["city"] as AnyObject
                     let result1: [test] = try unbox(dictionaries: [dict!])
                    data.append(contentsOf: result1)

                }

                print(data)

For more details follow
https://github.com/JohnSundell/Unbox


问:
Extract data from one workbook and copy to another workbook
I am trying to copy the data from one workbook  to another workbook.

I searched through Internet and came up with the below code. there is no error in the code.

The code works fine, but the Problem is,  it is opening both the Sheets , but not copying the data in Destination sheet.

in the code below, I have considered x as source sheet and y as Destination sheet.

Could someone suggest, where i am wrong and what is the reason i am not able to copy.

```<code>Sub test()
Dim x As Workbook
Dim y As Workbook
Dim val As Variant
Dim filename As String

Set x = Workbooks.Open("D:\Mikz\xxx.xlsx")

Set y = Sheets("Sheet1").Select
val = x.Sheets("Sheet2").Range("A1").Value
y.Sheets("Sheet1").Range("A1").Value = val

x.Close

End Sub
</code>```

答:
The reason for your error, lies in the section below:

```<code>Dim y As Workbook
Set y = Sheets("Sheet1").Select
</code>```

You defined y as workbook, but trying to assign a Worksheet object to it, and you added Select for some reason, which is defiantly not recommended.

It should be (if the workbook is open) :

```<code>Set y = Workbooks("YourBookName")
</code>```

The rest of your code would work just fine.

However, reading your post, I think you meant to define y As Worksheet.

And then the rest of your code should be:

```<code>Set y = Sheets("Sheet1")
val = x.Sheets("Sheet2").Range("A1").Value
y.Range("A1").Value = val
</code>```

Edit 1: Updated code (according to PO's new data)

```<code>Option Explicit

Sub test()

Dim x As Workbook
Dim y As Workbook
Dim Val As Variant
Dim filename As String

Set y = ThisWorkbook ' set ThisWorkbook object (where this code lies)
Set x = Workbooks.Open("D:\Mikz\xxx.xlsx")

Val = x.Sheets("Sheet2").Range("A1").Value
y.Sheets("Sheet1").Range("A1").Value = Val

x.Close

End Sub
</code>```

Edit 2: Code to copy columns A:E till last row with data

```<code>Option Explicit

Sub test()

Dim x As Workbook
Dim y As Workbook
Dim Val As Variant
Dim filename As String
Dim LastCell As Range
Dim LastRow As Long

Set y = ThisWorkbook ' set ThisWorkbook object (where this code lies)
Set x = Workbooks.Open("D:\Mikz\xxx.xlsx")
With x.Sheets("Sheet2")
    ' use the find method to get the last row in column A:E
    Set LastCell = .Columns("A:E").Find(What:="*", After:=.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
    If Not LastCell Is Nothing Then ' find was successful
        LastRow = LastCell.Row ' get last Row with data
    End If

    Val = .Range("A1:E" & LastRow).Value ' save range in 2-D array
End With

' resize the range from A1 through column E and the last row with data in copied workbook
y.Sheets("Sheet1").Range("A1").Resize(LastRow, 5).Value = Val

x.Close

End Sub
</code>```

Body:
I am trying to copy the data from one workbook  to another workbook.

I searched through Internet and came up with the below code. there is no error in the code.

The code works fine, but the Problem is,  it is opening both the Sheets , but not copying the data in Destination sheet.

in the code below, I have considered x as source sheet and y as Destination sheet.

Could someone suggest, where i am wrong and what is the reason i am not able to copy.

Sub test()
Dim x As Workbook
Dim y As Workbook
Dim val As Variant
Dim filename As String

Set x = Workbooks.Open("D:\Mikz\xxx.xlsx")

Set y = Sheets("Sheet1").Select
val = x.Sheets("Sheet2").Range("A1").Value
y.Sheets("Sheet1").Range("A1").Value = val

x.Close

End Sub

Body:
The reason for your error, lies in the section below:

Dim y As Workbook
Set y = Sheets("Sheet1").Select

You defined y as workbook, but trying to assign a Worksheet object to it, and you added Select for some reason, which is defiantly not recommended.

It should be (if the workbook is open) :

Set y = Workbooks("YourBookName")

The rest of your code would work just fine.

However, reading your post, I think you meant to define y As Worksheet.

And then the rest of your code should be:

Set y = Sheets("Sheet1")
val = x.Sheets("Sheet2").Range("A1").Value
y.Range("A1").Value = val

Edit 1: Updated code (according to PO's new data)

Option Explicit

Sub test()

Dim x As Workbook
Dim y As Workbook
Dim Val As Variant
Dim filename As String

Set y = ThisWorkbook ' set ThisWorkbook object (where this code lies)
Set x = Workbooks.Open("D:\Mikz\xxx.xlsx")

Val = x.Sheets("Sheet2").Range("A1").Value
y.Sheets("Sheet1").Range("A1").Value = Val

x.Close

End Sub

Edit 2: Code to copy columns A:E till last row with data

Option Explicit

Sub test()

Dim x As Workbook
Dim y As Workbook
Dim Val As Variant
Dim filename As String
Dim LastCell As Range
Dim LastRow As Long

Set y = ThisWorkbook ' set ThisWorkbook object (where this code lies)
Set x = Workbooks.Open("D:\Mikz\xxx.xlsx")
With x.Sheets("Sheet2")
    ' use the find method to get the last row in column A:E
    Set LastCell = .Columns("A:E").Find(What:="*", After:=.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
    If Not LastCell Is Nothing Then ' find was successful
        LastRow = LastCell.Row ' get last Row with data
    End If

    Val = .Range("A1:E" & LastRow).Value ' save range in 2-D array
End With

' resize the range from A1 through column E and the last row with data in copied workbook
y.Sheets("Sheet1").Range("A1").Resize(LastRow, 5).Value = Val

x.Close

End Sub


问:
Visual Studio For Mac Cordova
I have 2 computer
First one is IMac and the second one is Windows10
I use visual studio + cordova to finish my android apps
and right now i am trying to install cordova in visual studio for mac
but I cant find any topic like this or documentation

sorry for my broken English
Please help me

答:
I find the answer myself...
https://learn.microsoft.com/en-us/visualstudio/cross-platform/tools-for-cordova/first-steps/ios-guide
share this for somebody who have same question as me</p>

Title: Visual Studio For Mac Cordova


答: Both items have the class page-item-4, so it's not a miracle. If you need to highlight the current menu item use .current_page_item instead or assign a custom class name to the desired menu item in the Wordpress backend (Design -> Menues).

Title: CSS change affect 2 elements?

Body:
I wanted to place one of menu pages into border with red background, so i used this CSS to do that:

.page-item-4  {
 border:3px; border-style:solid; border-color:#000; padding: 1em;background:
 red;font-weight: bold;
  }

and works OK when you are on homepage, or some other page. when click on SHOP page both elements : "SHOP" and "Programmes personnalisés" got the same styling. Why ? I want only SHOP to use that styling. Can someone to tell me where is issue? Issue is present only in this page.