问:
Match Documents based on Nested Array Values and Count Unique
I have a MongoDB Collection which has Documents in Given format,

```<code>{
    "_id" : ObjectId("595f5661f34ae7b2adee31bc"),
    "app_userUpdatedOn" : "2017-03-09T12:01:07.615Z",
    "appId" : 31625,
    "app_lastCommunicatedAt" : "2017-03-09T12:18:53.067Z",
    "currentDate" : "2017-03-09T12:19:28.626Z",
    "objectId" : "58c14850e4b0b2406992b29e",
    "name" : "APPSESSION",
    "action" : "START",
    "installationId" : "98088f6641a0fa79",
    "userName" : "98088f6641a0fa79",
    "properties" : [
        [
            "userid",
            "98088f6641a0fa79"
        ],
        [
            "app_os_version",
            "6.0.1"
        ],
        [
            "app_installAt",
            "2017-03-09T12:01:01.307Z"
        ],
        [
            "app_model",
            "SM-J210F"
        ],
        [
            "app_lastCommunicatedAt",
            "2017-03-09T12:18:53.067Z"
        ],
        [
            "app_carrier",
            "Jio 4G"
        ],
        [
            "app_counter",
            1
        ],
        [
            "app_brand",
            "samsung"
        ],
        [
            "app_lib_version",
            "1.0"
        ],
        [
            "app_app_version",
            "3.0.2"
        ],
        [
            "app_os",
            "Android"
        ]
    ],
    "date" : "2017-03-09"
}
{
    "_id" : ObjectId("595f5661f34ae7b2adee31bd"),
    "app_userUpdatedOn" : "2017-02-05T07:38:32.866Z",
    "appId" : 31625,
    "app_lastCommunicatedAt" : "2017-03-09T08:09:05.342Z",
    "currentDate" : "2017-03-09T12:19:28.806Z",
    "objectId" : "58c14850e4b06ec88ecaa9c6",
    "name" : "APPINSTALL",
    "action" : "START",
    "installationId" : "eef436554fbdf4ac",
    "userName" : "eef436554fbdf4ac",
    "properties" : [
        [
            "userid",
            "eef436554fbdf4ac"
        ],
        [
            "app_os_version",
            "5.1"
        ],
        [
            "app_installAt",
            "2017-02-05T11:20:49.809Z"
        ],
        [
            "app_model",
            "Micromax Q465"
        ],
        [
            "app_lastCommunicatedAt",
            "2017-03-09T08:09:05.342Z"
        ],
        [
            "app_carrier",
            "JIO 4G"
        ],
        [
            "app_counter",
            1
        ],
        [
            "app_brand",
            "Micromax"
        ],
        [
            "app_lib_version",
            "1.0"
        ],
        [
            "app_app_version",
            "3.0.2"
        ],
        [
            "app_os",
            "Android"
        ]
    ],
    "date" : "2017-03-09"
}
</code>```

I want to Fetch the Count and Unique Count of the Documents where currentDate lies in between, startDate and endDate, name is x (eg. APPSESSION), Containing multiple Properties Nested Array (like ["app_installAt","This can be any value instead of null"] ,["app_model","This can be any value instead of null"], and so on... ), Group By userName

Previously i have created a Query in which Nested Array Both Element are Known, and it is as follows

```<code>db.testing.aggregate(
      [
            {$match: {currentDate: {$gte:"2017-03-01T00:00:00.000Z", $lt:"2017-03-02T00:00:00.000Z"},name:"INSTALL"}},
            {$match: {properties: ["app_os_version","4.4.2"]}},
            {$match: {properties: ["app_carrier","telenor"]}},
            {$match: {properties: ["app_brand","Micromax"]}},
            {$group: {_id: "$userName"}},
            {$count: "uniqueCount"}
      ]
);
</code>```

But i am unable to find the Data where i know only 0th index of Property Data Nested Array.

Please do Help.

Thanks in Advance.... :)

答:
The query for this is essentially the use of $all for the multiple conditions to match in the array and then use $elemMatch and $eq to match the individual array elements.

For example to match and count the first document supplied in your question "only" the parameters would be:

```<code>db.testing.find({
  "currentDate": {
    "$gte": "2017-03-09T00:00:00.000Z",
    "$lt": "2017-03-10T00:00:00.000Z"
  },
  "properties": {
    "$all": [
      { "$elemMatch": { "$eq": ["app_os_version","6.0.1"] } },
      { "$elemMatch": { "$eq": ["app_carrier", "Jio 4G"] } },
      { "$elemMatch": { "$eq": ["app_brand", "samsung"] } }
    ]
  }
})
</code>```

With .aggregate() then you put the whole query into a single $match stage as in:

```<code>db.testing.aggregate([
  { "$match": {
    "currentDate": {
      "$gte": "2017-03-09T00:00:00.000Z",
      "$lt": "2017-03-10T00:00:00.000Z"
    },
    "properties": {
      "$all": [
        { "$elemMatch": { "$eq": ["app_os_version","6.0.1"] } },
        { "$elemMatch": { "$eq": ["app_carrier", "Jio 4G"] } },
        { "$elemMatch": { "$eq": ["app_brand", "samsung"] } }
      ]
    }
  }},
  { "$group": { "_id": "$userName" }
  { "$count": "unique_count"
])
</code>```

So $elemMatch in this context is going to examine each "inner" array and see if it matches the supplied conditions, which we give in argument as an "array" to the $eq operator.

The wrapping $all means that "all" the provided $elemMatch conditions "must" be met in order to fulfill the query conditions. And that is how the selection gets made with this type of structure.

If you needed to adjust one of those then the "inner" match is using the element of the array. So on the key it would use the "0" for the index position. i.e:

```<code>   { "$elemMatch": { "0": "app_os_version" } },
</code>```

Body:
I have a MongoDB Collection which has Documents in Given format,

{
    "_id" : ObjectId("595f5661f34ae7b2adee31bc"),
    "app_userUpdatedOn" : "2017-03-09T12:01:07.615Z",
    "appId" : 31625,
    "app_lastCommunicatedAt" : "2017-03-09T12:18:53.067Z",
    "currentDate" : "2017-03-09T12:19:28.626Z",
    "objectId" : "58c14850e4b0b2406992b29e",
    "name" : "APPSESSION",
    "action" : "START",
    "installationId" : "98088f6641a0fa79",
    "userName" : "98088f6641a0fa79",
    "properties" : [
        [
            "userid",
            "98088f6641a0fa79"
        ],
        [
            "app_os_version",
            "6.0.1"
        ],
        [
            "app_installAt",
            "2017-03-09T12:01:01.307Z"
        ],
        [
            "app_model",
            "SM-J210F"
        ],
        [
            "app_lastCommunicatedAt",
            "2017-03-09T12:18:53.067Z"
        ],
        [
            "app_carrier",
            "Jio 4G"
        ],
        [
            "app_counter",
            1
        ],
        [
            "app_brand",
            "samsung"
        ],
        [
            "app_lib_version",
            "1.0"
        ],
        [
            "app_app_version",
            "3.0.2"
        ],
        [
            "app_os",
            "Android"
        ]
    ],
    "date" : "2017-03-09"
}
{
    "_id" : ObjectId("595f5661f34ae7b2adee31bd"),
    "app_userUpdatedOn" : "2017-02-05T07:38:32.866Z",
    "appId" : 31625,
    "app_lastCommunicatedAt" : "2017-03-09T08:09:05.342Z",
    "currentDate" : "2017-03-09T12:19:28.806Z",
    "objectId" : "58c14850e4b06ec88ecaa9c6",
    "name" : "APPINSTALL",
    "action" : "START",
    "installationId" : "eef436554fbdf4ac",
    "userName" : "eef436554fbdf4ac",
    "properties" : [
        [
            "userid",
            "eef436554fbdf4ac"
        ],
        [
            "app_os_version",
            "5.1"
        ],
        [
            "app_installAt",
            "2017-02-05T11:20:49.809Z"
        ],
        [
            "app_model",
            "Micromax Q465"
        ],
        [
            "app_lastCommunicatedAt",
            "2017-03-09T08:09:05.342Z"
        ],
        [
            "app_carrier",
            "JIO 4G"
        ],
        [
            "app_counter",
            1
        ],
        [
            "app_brand",
            "Micromax"
        ],
        [
            "app_lib_version",
            "1.0"
        ],
        [
            "app_app_version",
            "3.0.2"
        ],
        [
            "app_os",
            "Android"
        ]
    ],
    "date" : "2017-03-09"
}

I want to Fetch the Count and Unique Count of the Documents where currentDate lies in between, startDate and endDate, name is x (eg. APPSESSION), Containing multiple Properties Nested Array (like ["app_installAt","This can be any value instead of null"] ,["app_model","This can be any value instead of null"], and so on... ), Group By userName

Previously i have created a Query in which Nested Array Both Element are Known, and it is as follows

db.testing.aggregate(
      [
            {$match: {currentDate: {$gte:"2017-03-01T00:00:00.000Z", $lt:"2017-03-02T00:00:00.000Z"},name:"INSTALL"}},
            {$match: {properties: ["app_os_version","4.4.2"]}},
            {$match: {properties: ["app_carrier","telenor"]}},
            {$match: {properties: ["app_brand","Micromax"]}},
            {$group: {_id: "$userName"}},
            {$count: "uniqueCount"}
      ]
);

But i am unable to find the Data where i know only 0th index of Property Data Nested Array.

Please do Help.

Thanks in Advance.... :)

Body:
The query for this is essentially the use of $all for the multiple conditions to match in the array and then use $elemMatch and $eq to match the individual array elements.

For example to match and count the first document supplied in your question "only" the parameters would be:

db.testing.find({
  "currentDate": {
    "$gte": "2017-03-09T00:00:00.000Z",
    "$lt": "2017-03-10T00:00:00.000Z"
  },
  "properties": {
    "$all": [
      { "$elemMatch": { "$eq": ["app_os_version","6.0.1"] } },
      { "$elemMatch": { "$eq": ["app_carrier", "Jio 4G"] } },
      { "$elemMatch": { "$eq": ["app_brand", "samsung"] } }
    ]
  }
})

With .aggregate() then you put the whole query into a single $match stage as in:

db.testing.aggregate([
  { "$match": {
    "currentDate": {
      "$gte": "2017-03-09T00:00:00.000Z",
      "$lt": "2017-03-10T00:00:00.000Z"
    },
    "properties": {
      "$all": [
        { "$elemMatch": { "$eq": ["app_os_version","6.0.1"] } },
        { "$elemMatch": { "$eq": ["app_carrier", "Jio 4G"] } },
        { "$elemMatch": { "$eq": ["app_brand", "samsung"] } }
      ]
    }
  }},
  { "$group": { "_id": "$userName" }
  { "$count": "unique_count"
])

So $elemMatch in this context is going to examine each "inner" array and see if it matches the supplied conditions, which we give in argument as an "array" to the $eq operator.

The wrapping $all means that "all" the provided $elemMatch conditions "must" be met in order to fulfill the query conditions. And that is how the selection gets made with this type of structure.

If you needed to adjust one of those then the "inner" match is using the element of the array. So on the key it would use the "0" for the index position. i.e:

   { "$elemMatch": { "0": "app_os_version" } },


来源: stackexchange

问:
SQL: Sum two columns as 'Name' and use that name in where
MySQL:

I'm trying to Sum two columns in my database and return that results. I have that bit working.

```<code>SELECT Id, SUM(Money + Bank) AS TotalMoney FROM Players_Stats GROUP BY Id
</code>```

Now I have the two columns totalling together i want to be able to use 'TotalMoney' in a where clause?

```<code>SELECT Id, SUM(Money + Bank) AS TotalMoney FROM Players_Stats
WHERE TotalMoney BETWEEN 100000 AND 1000000
GROUP BY Id
</code>```

I'm getting a error saying TotalMoney does not exist but I have declared it.

答:
You want to use a HAVING clause.  It comes after the GROUP BY.  And it can use the table alias (in MySQL):

```<code>SELECT Id, SUM(Money + Bank) AS TotalMoney
FROM Players_Stats
GROUP BY Id
HAVING TotalMoney BETWEEN 100000 AND 1000000;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
MySQL:

I'm trying to Sum two columns in my database and return that results. I have that bit working.

SELECT Id, SUM(Money + Bank) AS TotalMoney FROM Players_Stats GROUP BY Id

Now I have the two columns totalling together i want to be able to use 'TotalMoney' in a where clause?

SELECT Id, SUM(Money + Bank) AS TotalMoney FROM Players_Stats
WHERE TotalMoney BETWEEN 100000 AND 1000000
GROUP BY Id

I'm getting a error saying TotalMoney does not exist but I have declared it.

Body:
You want to use a HAVING clause.  It comes after the GROUP BY.  And it can use the table alias (in MySQL):

SELECT Id, SUM(Money + Bank) AS TotalMoney
FROM Players_Stats
GROUP BY Id
HAVING TotalMoney BETWEEN 100000 AND 1000000;


问:
systemd execute after a oneshot service
Hi is it possible to run a service after a "oneshot" type service

I want to run a script that started before display-manager.service but after gpu-manager.service, gpu-manager.service is a oneshot service that detect available gpu. This is my service :

```<code>[Unit]
After=gpu-manager.service
Before=display-manager.service

[Service]
Type=oneshot
ExecStart=myscript

[Install]
WantedBy=multi-user.target
</code>```

Will my service be started after gpu-manager and before display started ?

答:
Are you sure that you need 3 services?

You can use ExecStop or other directives to run multiple scripts and use 1 systemd service.

Try this solution

[Unit]
Description=example

[Service]
Type=oneshot
ExecStart=/usr/local/bin/on_start.sh
RemainAfterExit=true
ExecStop=/usr/local/bin/with_stopped.sh

[Install]
WantedBy=graphical.target
```

Title: systemd execute after a oneshot service

Body:
Hi is it possible to run a service after a "oneshot" type service

I want to run a script that started before display-manager.service but after gpu-manager.service, gpu-manager.service is a oneshot service that detect available gpu. This is my service :

[Unit]
After=gpu-manager.service
Before=display-manager.service

[Service]
Type=oneshot
ExecStart=myscript

[Install]
WantedBy=multi-user.target

Will my service be started after gpu-manager and before display started ?


问:
json format output from JavaScriptSerializer
```<code>var singleItems = new List<Products>();

singleItems.Add(new Products() { product_id = 1, title = "Bryon Hetrick", price = 50 });
singleItems.Add(new Products() { product_id = 2, title = "Nicole Wilcox", price = 20 });

var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(serializer);
</code>```

From above example code i am getting Json output like bellow.

```<code>[{"product_id":1,"title":"Bryon Hetrick","price":50},
 {"product_id":2,"title":"Nicole Wilcox","price":20}]
</code>```

But my Json need one more value called- "config" also i need whole data formatted exactly like bellow. How to edit my c# code to achieve that value?

```<code>{ "products":[{"product_id":"B071H6TBM5","title":"New Iphone 5S","price":"23.45"},{"product_id":"B071DM968J","title":"Iphone 4 old","price":"23.45"}],"config":{"token":"","Site":"Us","Mode":"ListMyItem"}}
</code>```

答:
You could make a Config class with the properties you require and then a composite class with Prodcuts and Config, i.e. ProductConfig:

```<code>public class Products
{
   public string product_id { get; set; }
   public string title { get; set; }
   public string price { get; set; }
}

public class Config
{
  public string token { get; set; }
  public string site { get; set; }
  public string mode { get; set; }
}

public class ProductConfig
{
   public List<Products> Products { get; set; }
   public Config Config { get; set; }
}
</code>```

You can then create/populate the ProductConfig class with the new properties.

```<code>public string SerializeProductConfig()
{
   ProductConfig pc = new ProductConfig();
   pc.Config = new Config { token = "DDTest", site = "US", mode = "Test Mode" };
   pc.Products = new List<Products>();
   pc.Products.Add(new Products() { product_id = "1", title = "Bryon Hetrick", price = "50" });
   pc.Products.Add(new Products() { product_id = "2", title = "Nicole Wilcox", price = "20" });

   var serializer = new JavaScriptSerializer();
   return serializer.Serialize(pc);
}
</code>```

and serialize the ProductConfig object using the JavaScript serializer or NewtonSoft which will give you the following JSON

```<code>{ // ProductConfig
  "Products": [
    {
      "product_id": "1",
      "title": "Bryon Hetrick",
      "price": "50"
    },
    {
      "product_id": "2",
      "title": "Nicole Wilcox",
      "price": "20"
    }
  ],
  "config": {
    "token": "DDTest",
    "site": "US",
    "mode": "Test Mode"
  }
}
</code>```

Body:
var singleItems = new List<Products>();

singleItems.Add(new Products() { product_id = 1, title = "Bryon Hetrick", price = 50 });
singleItems.Add(new Products() { product_id = 2, title = "Nicole Wilcox", price = 20 });

var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(serializer);

From above example code i am getting Json output like bellow.

[{"product_id":1,"title":"Bryon Hetrick","price":50},
 {"product_id":2,"title":"Nicole Wilcox","price":20}]

But my Json need one more value called- "config" also i need whole data formatted exactly like bellow. How to edit my c# code to achieve that value?

{ "products":[{"product_id":"B071H6TBM5","title":"New Iphone 5S","price":"23.45"},{"product_id":"B071DM968J","title":"Iphone 4 old","price":"23.45"}],"config":{"token":"","Site":"Us","Mode":"ListMyItem"}}

Body:
You could make a Config class with the properties you require and then a composite class with Prodcuts and Config, i.e. ProductConfig:

public class Products
{
   public string product_id { get; set; }
   public string title { get; set; }
   public string price { get; set; }
}

public class Config
{
  public string token { get; set; }
  public string site { get; set; }
  public string mode { get; set; }
}

public class ProductConfig
{
   public List<Products> Products { get; set; }
   public Config Config { get; set; }
}

You can then create/populate the ProductConfig class with the new properties.

public string SerializeProductConfig()
{
   ProductConfig pc = new ProductConfig();
   pc.Config = new Config { token = "DDTest", site = "US", mode = "Test Mode" };
   pc.Products = new List<Products>();
   pc.Products.Add(new Products() { product_id = "1", title = "Bryon Hetrick", price = "50" });
   pc.Products.Add(new Products() { product_id = "2", title = "Nicole Wilcox", price = "20" });

   var serializer = new JavaScriptSerializer();
   return serializer.Serialize(pc);
}

and serialize the ProductConfig object using the JavaScript serializer or NewtonSoft which will give you the following JSON

{ // ProductConfig
  "Products": [
    {
      "product_id": "1",
      "title": "Bryon Hetrick",
      "price": "50"
    },
    {
      "product_id": "2",
      "title": "Nicole Wilcox",
      "price": "20"
    }
  ],
  "config": {
    "token": "DDTest",
    "site": "US",
    "mode": "Test Mode"
  }
}


问:
react-router-redux, push method does not work
I am using react-router-redux.

I don't know how to create the demo to describe the issue simply.
I push all code on Github.
https://github.com/jiexishede/newReactSOAskDemo001

The a-href work well.
@https://github.com/jiexishede/newReactSOAskDemo001/blob/ask1/src/components/Home/Preview.js/#L37

Now, the push method does not work.

@https://github.com/jiexishede/newReactSOAskDemo001/blob/ask1/src/components/Home/Preview.js/#L30

I edit the code and update it on GitHub.

I import the hashHistory.

https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L9

hashHistory.push('detail/'+id); work well.
https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L32

disPatchpush @https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L31
It does not work.

In the Home.js:

```<code>  @connect(state => {
  return {
    list:state.home.list,

  };
}, dispatch => {

  return {
    actions: bindActionCreators(actions, dispatch),
    dispatchPush:  bindActionCreators(push, dispatch),
  }
})
</code>```

dispatchPush is passed from the Home.js to PreviewList to Preview.

答:
you miss routerMiddleware. Works beautifully after applying routerMiddleware.

```<code>import { browserHistory } from 'react-router';
import { routerReducer, routerMiddleware } from 'react-router-redux';
...
const finalCreateStore = compose(
  applyMiddleware(
      ThunkMiddleware,
      FetchMiddleware,
      routerMiddleware(browserHistory)
  ),
  DevTools.instrument(),
)(createStore);

const reducer = combineReducers({
  ...rootReducer,
  routing: routerReducer,
});

export default function configureStore(initialState) {
  const store = finalCreateStore(reducer, initialState);
  return store;
}
</code>```

Read this section of the docs - https://github.com/reactjs/react-router-redux#what-if-i-want-to-issue-navigation-events-via-redux-actions

Body:
I am using react-router-redux.

I don't know how to create the demo to describe the issue simply.
I push all code on Github.
https://github.com/jiexishede/newReactSOAskDemo001

The a-href work well.
@https://github.com/jiexishede/newReactSOAskDemo001/blob/ask1/src/components/Home/Preview.js/#L37

Now, the push method does not work.

@https://github.com/jiexishede/newReactSOAskDemo001/blob/ask1/src/components/Home/Preview.js/#L30

I edit the code and update it on GitHub.

I import the hashHistory.

https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L9

hashHistory.push('detail/'+id); work well.
https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L32

disPatchpush @https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L31
It does not work.

In the Home.js:

  @connect(state => {
  return {
    list:state.home.list,

  };
}, dispatch => {

  return {
    actions: bindActionCreators(actions, dispatch),
    dispatchPush:  bindActionCreators(push, dispatch),
  }
})

dispatchPush is passed from the Home.js to PreviewList to Preview.

Body:
you miss routerMiddleware. Works beautifully after applying routerMiddleware.

import { browserHistory } from 'react-router';
import { routerReducer, routerMiddleware } from 'react-router-redux';
...
const finalCreateStore = compose(
  applyMiddleware(
      ThunkMiddleware,
      FetchMiddleware,
      routerMiddleware(browserHistory)
  ),
  DevTools.instrument(),
)(createStore);

const reducer = combineReducers({
  ...rootReducer,
  routing: routerReducer,
});

export default function configureStore(initialState) {
  const store = finalCreateStore(reducer, initialState);
  return store;
}

Read this section of the docs - https://github.com/reactjs/react-router-redux#what-if-i-want-to-issue-navigation-events-via-redux-actions


问:
PHP function to remove key from a query string
I have a query string, like:

n1=v1&n2=v2&n3=v3

etc

I just want a php function that will accept the query string and the name (key), and remove the name value pair from the querystring.

Every example I have found uses regexes and assumes that the value will exist and that it will not be empty, but in my case (and possibly in general, I would like to know) this would also be a valid query:

n1=v1&n2=&n3

I don’t know in advance how many keys there will be.

I am convinced that regexes are monsters that eat time.  Eventually all matter in the universe will end up in a regex.

答:
```
function stripkey($input, $key) {</p>

<code>$parts= explode("&", $input);

foreach($parts as $k=>$part) {

    if(strpos($part, "=") !== false) {
        $parts2= explode("=", $part);

        if($key == $parts2[0]){

            unset($parts[$k]);
        }
    }
}
return join("&", $parts);
</code>```

<p>}</p>

ContentLicense: CC BY-SA 2.5

Body:
function stripkey($input, $key) {

$parts= explode("&", $input);

foreach($parts as $k=>$part) {

    if(strpos($part, "=") !== false) {
        $parts2= explode("=", $part);

        if($key == $parts2[0]){

            unset($parts[$k]);
        }
    }
}
return join("&", $parts);

}


问:
isChecked function is not working for radio button in android
Below is my activity_main.xml code

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingTop="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical">

       <RadioGroup
           android:layout_width="match_parent"
           android:layout_height="300dp"
           android:id="@+id/rgr">

           <RadioButton
               android:id="@+id/rb1"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_weight="1"
               android:text="Mechanical" />

           <RadioButton
               android:id="@+id/rb2"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_weight="1"
               android:text="Electrical" />

           <RadioButton
               android:id="@+id/rb3"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_weight="1"
               android:text="Civil" />

           <RadioButton
               android:id="@+id/rb4"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_weight="1"
               android:text="Computer Science" />
       </RadioGroup>

</LinearLayout>
</code>```

Below is MainActivity.java code

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
{           // https://www.youtube.com/watch?v=n7c3bIWcgZo

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RadioGroup radioGroup = (RadioGroup)findViewById(R.id.rgr);
        RadioButton radioButton1 = (RadioButton)findViewById(R.id.rb1);
        RadioButton radioButton2 = (RadioButton)findViewById(R.id.rb2);
        RadioButton radioButton3 = (RadioButton)findViewById(R.id.rb3);
        RadioButton radioButton4 = (RadioButton)findViewById(R.id.rb4);

        if(radioButton1.isChecked())
        {
               Toast.makeText(getApplicationContext(), radioButton1.getText(),Toast.LENGTH_LONG).show();
        }
        else if(radioButton2.isChecked())
        {
               Toast.makeText(getApplicationContext(), radioButton2.getText(),Toast.LENGTH_LONG).show();
        }
        else if(radioButton3.isChecked())
        {
               Toast.makeText(getApplicationContext(), radioButton3.getText(),Toast.LENGTH_LONG).show();
        }
        else if(radioButton4.isChecked())
        {
               Toast.makeText(getApplicationContext(), radioButton4.getText(),Toast.LENGTH_LONG).show();
        }
    }
</code>```

Now, when i run the app, the radio buttons are getting selected but the toast message is not coming when i select particular button.

i have also tried by removing radiogroup and keeping only radio buttons but still i think isChecked() fucntion is not excuting.

Please help me in solving this issue.

答:
You need to set OnCheckedChangeListener for radioGroup to find which radiobutton is checked or not. Do like this below </p>

```<code>radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
   @Override
   public void onCheckedChanged(RadioGroup group, int checkedId)
   {
       RadioButton radioButton = (RadioButton) findViewById(checkedId);
       Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
   }
 });
</code>```

Body:
Below is my activity_main.xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingTop="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical">

       <RadioGroup
           android:layout_width="match_parent"
           android:layout_height="300dp"
           android:id="@+id/rgr">

           <RadioButton
               android:id="@+id/rb1"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_weight="1"
               android:text="Mechanical" />

           <RadioButton
               android:id="@+id/rb2"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_weight="1"
               android:text="Electrical" />

           <RadioButton
               android:id="@+id/rb3"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_weight="1"
               android:text="Civil" />

           <RadioButton
               android:id="@+id/rb4"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_weight="1"
               android:text="Computer Science" />
       </RadioGroup>

</LinearLayout>

Below is MainActivity.java code

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
{           // https://www.youtube.com/watch?v=n7c3bIWcgZo

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RadioGroup radioGroup = (RadioGroup)findViewById(R.id.rgr);
        RadioButton radioButton1 = (RadioButton)findViewById(R.id.rb1);
        RadioButton radioButton2 = (RadioButton)findViewById(R.id.rb2);
        RadioButton radioButton3 = (RadioButton)findViewById(R.id.rb3);
        RadioButton radioButton4 = (RadioButton)findViewById(R.id.rb4);

        if(radioButton1.isChecked())
        {
               Toast.makeText(getApplicationContext(), radioButton1.getText(),Toast.LENGTH_LONG).show();
        }
        else if(radioButton2.isChecked())
        {
               Toast.makeText(getApplicationContext(), radioButton2.getText(),Toast.LENGTH_LONG).show();
        }
        else if(radioButton3.isChecked())
        {
               Toast.makeText(getApplicationContext(), radioButton3.getText(),Toast.LENGTH_LONG).show();
        }
        else if(radioButton4.isChecked())
        {
               Toast.makeText(getApplicationContext(), radioButton4.getText(),Toast.LENGTH_LONG).show();
        }
    }

Now, when i run the app, the radio buttons are getting selected but the toast message is not coming when i select particular button.

i have also tried by removing radiogroup and keeping only radio buttons but still i think isChecked() fucntion is not excuting.

Please help me in solving this issue.

Body:
You need to set OnCheckedChangeListener for radioGroup to find which radiobutton is checked or not. Do like this below

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
   @Override
   public void onCheckedChanged(RadioGroup group, int checkedId)
   {
       RadioButton radioButton = (RadioButton) findViewById(checkedId);
       Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
   }
 });


问:
ClipsToBounds is not working in cells
I have an UITableView with custom cells. The structure of every cell is like that: I have contentView, in this contentView I have backView (simple UIView with white background and cornered radius 16.0), in this backView I have an imageView with some picture.

What I want is to have this imageView cornered (within his parent UIView — backView — borders). And it doesn't work this way.

The code is quite simple (from ImageCell.swift):

```<code>    self.backView = UIView()
    self.backView.backgroundColor = UIColor.white
    self.backView.translatesAutoresizingMaskIntoConstraints = false
    self.backView.layer.cornerRadius = 16.0
    self.contentView.addSubview(backView)

    self.picture = UIImageView()
    self.picture.translatesAutoresizingMaskIntoConstraints = false
    self.picture.contentMode = UIViewContentMode.scaleAspectFill
    self.picture.backgroundColor = UIColor.gray
    self.picture.clipsToBounds = true
    self.backView.addSubview(picture)

    let constraintPicTop = NSLayoutConstraint(item: picture, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .topMargin, multiplier: 1.0, constant: -6)
    let constraintPicLeft = NSLayoutConstraint(item: picture, attribute: .left, relatedBy: .equal, toItem: backView, attribute: .leftMargin, multiplier: 1.0, constant: -8)
    let constraintPicRight = NSLayoutConstraint(item: picture, attribute: .right, relatedBy: .equal, toItem: backView, attribute: .rightMargin, multiplier: 1.0, constant: 8)
    constraintBottomPic = NSLayoutConstraint(item: picture, attribute: .bottom, relatedBy: .lessThanOrEqual, toItem: contentView, attribute: .topMargin, multiplier: 1.0, constant: 150)
</code>```

I don't know the size of the image beforehand, so constraintBottomPic value is updating in cellForRowAt function.

And it's working except this image is not cornered (and I believe it should be).

(It's not possible for me to set cornerRadius for UIImageView unfortunately).

update: Found the solution. It seems I had to set 'clipsToBounds' to true in all the parent views directly (contentView and backView, in my case).

答:
Apply imageView.layer.maskToBounds = YES;

Apply this to view or imageview on which you want to set corner radius.

As you have mentioned corner radius to your view you need to set this for your view

Title: ClipsToBounds is not working in cells

Body:
I have an UITableView with custom cells. The structure of every cell is like that: I have contentView, in this contentView I have backView (simple UIView with white background and cornered radius 16.0), in this backView I have an imageView with some picture.

What I want is to have this imageView cornered (within his parent UIView — backView — borders). And it doesn't work this way.

The code is quite simple (from ImageCell.swift):

    self.backView = UIView()
    self.backView.backgroundColor = UIColor.white
    self.backView.translatesAutoresizingMaskIntoConstraints = false
    self.backView.layer.cornerRadius = 16.0
    self.contentView.addSubview(backView)

    self.picture = UIImageView()
    self.picture.translatesAutoresizingMaskIntoConstraints = false
    self.picture.contentMode = UIViewContentMode.scaleAspectFill
    self.picture.backgroundColor = UIColor.gray
    self.picture.clipsToBounds = true
    self.backView.addSubview(picture)

    let constraintPicTop = NSLayoutConstraint(item: picture, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .topMargin, multiplier: 1.0, constant: -6)
    let constraintPicLeft = NSLayoutConstraint(item: picture, attribute: .left, relatedBy: .equal, toItem: backView, attribute: .leftMargin, multiplier: 1.0, constant: -8)
    let constraintPicRight = NSLayoutConstraint(item: picture, attribute: .right, relatedBy: .equal, toItem: backView, attribute: .rightMargin, multiplier: 1.0, constant: 8)
    constraintBottomPic = NSLayoutConstraint(item: picture, attribute: .bottom, relatedBy: .lessThanOrEqual, toItem: contentView, attribute: .topMargin, multiplier: 1.0, constant: 150)

I don't know the size of the image beforehand, so constraintBottomPic value is updating in cellForRowAt function.

And it's working except this image is not cornered (and I believe it should be).

(It's not possible for me to set cornerRadius for UIImageView unfortunately).

update: Found the solution. It seems I had to set 'clipsToBounds' to true in all the parent views directly (contentView and backView, in my case).


问:
how to import all css of node_modules in vuejs
I am building a Vue.js app starting with the webpack template and vuetify.
To import vuetify css Im doing this in my App.vue

Is this the correct or only way? because it doesn't seem reliable when using multiple UI components.

答:
You can import it in yout main.js

```<code>import 'vuetify/dist/vuetify.min.css'
</code>```

for this to work you should have css-loader in you webpack config

In your webpack

```<code>module: {
  loaders: [
    { test: /\.css$/, loader: "css-loader" }
  ]
}
</code>```

OR

In your App.vue component add two style tags , one for global styles as App.vue  is the entry point and other for scoped styles if you have any with the scoped attribute.See src imports.

```<code><style src='vuetify/dist/vuetify.min.css'>
    /* global styles */
</style>

<style scoped>
    /* local styles */
</style>
</code>```

Body:
You can import it in yout main.js

import 'vuetify/dist/vuetify.min.css'

for this to work you should have css-loader in you webpack config

In your webpack

module: {
  loaders: [
    { test: /\.css$/, loader: "css-loader" }
  ]
}

OR

In your App.vue component add two style tags , one for global styles as App.vue  is the entry point and other for scoped styles if you have any with the scoped attribute.See src imports.

<style src='vuetify/dist/vuetify.min.css'>
    /* global styles */
</style>

<style scoped>
    /* local styles */
</style>

ContentLicense: CC BY-SA 4.0


问:
Why is traversing more time-consuming than merging on two sorted std::list?
I am pretty amazed on the result that traversing takes more time than merging on two sorted std::list by around 12%. Since merging can be considered and implemented as continuous element comparisons, list splice and iterators traversal through two separated sorted linked lists. Hence, traversing should not be slower than merging through them especially when two lists are large enough because the ratio of iterated elements is getting increased.

However, the result seems to not match what I thought, and this is how I test my ideas above:

```<code>std::list<int> list1, list2;

for (int cnt = 0; cnt < 1 << 22; cnt++)
    list1.push_back(rand());
for (int cnt = 0; cnt < 1 << 23; cnt++)
    list2.push_back(rand());

list1.sort();
list2.sort();

auto start = std::chrono::system_clock::now();  // C++ wall clock

// Choose either one option below
list1.merge(list2);         // Option 1
for (auto num : list1);     // Option 2
for (auto num : list2);     // Option 2

std::chrono::duration<double> diff = std::chrono::system_clock::now() - start;
std::cout << std::setprecision(9) << "\n       "
          << diff.count() << " seconds (measured)" << std::endl;  // show elapsed time
</code>```

PS. icc is smart enough to eliminate Option 2. Try sum += num; and print out sum.

This is the output from perf: (the measured time remains the same without using perf)

Option 1: Merge

```<code>       0.904575206 seconds (measured)

 Performance counter stats for './option-1-merge':

    33,395,981,671      cpu-cycles
       149,371,004      cache-misses              #   49.807 % of all cacherefs
       299,898,436      cache-references
    24,254,303,068      cycle-activity.stalls-ldm-pending

       7.678166480 seconds time elapsed
</code>```

Option 2: Traverse

```<code>       1.01401903 seconds (measured)

 Performance counter stats for './option-2-traverse':

    33,844,645,296      cpu-cycles
       138,723,898      cache-misses             #   48.714 % of all cacherefs
       284,770,796      cache-references
    25,141,751,107      cycle-activity.stalls-ldm-pending

       7.806018949 seconds time elapsed
</code>```

Due to the property of horrible spatial locality on these linked lists. The cache miss is the major reason that make CPU stalls, and occupies most of the CPU resources. The strange point is that option 2 has fewer cache misses than option 1, but it has a higher amount of CPU stalls and CPU cycles to accomplish its task. What makes this abnormality happen?

答:
As you know, it is memory that is taking all your time.

Cache misses are bad, but so are stalls.

From this paper:

Applications with irregular memory access patterns, e.g.,dereferencing chains of pointers when traversing linked lists or trees, may not generate enough concurrently outstanding requests to fully utilize the data paths. Nevertheless, such applications are clearly limited by the performance of memory accesses as well. Therefore, considering the bandwidth utilization is not sufficient to detect all memory related performance issues.

Basically, randomly walking pointers can fail to saturate the memory bandwidth.

The tight loop on each is blocked each iteration by waiting on where the next pointer is to be loaded.  If it is not in cache, the cpu can do nothing -- it stalls.

The combined tight loop/merge tries to load two pages into the cache.  When one is loading, sometimes the cpu can advannce on the other.

The result you measured was that the merge has fewer stalls that the naked wasted double iteration.

Or in other words,

```<code>24,254,303,068      cycle-activity.stalls-ldm-pending
</code>```

is a big number and smaller than:

```<code>25,141,751,107      cycle-activity.stalls-ldm-pending
</code>```

I am surprised this is enough to make a 10% difference, but that is why perf is about measuring.

Body:
I am pretty amazed on the result that traversing takes more time than merging on two sorted std::list by around 12%. Since merging can be considered and implemented as continuous element comparisons, list splice and iterators traversal through two separated sorted linked lists. Hence, traversing should not be slower than merging through them especially when two lists are large enough because the ratio of iterated elements is getting increased.

However, the result seems to not match what I thought, and this is how I test my ideas above:

std::list<int> list1, list2;

for (int cnt = 0; cnt < 1 << 22; cnt++)
    list1.push_back(rand());
for (int cnt = 0; cnt < 1 << 23; cnt++)
    list2.push_back(rand());

list1.sort();
list2.sort();

auto start = std::chrono::system_clock::now();  // C++ wall clock

// Choose either one option below
list1.merge(list2);         // Option 1
for (auto num : list1);     // Option 2
for (auto num : list2);     // Option 2

std::chrono::duration<double> diff = std::chrono::system_clock::now() - start;
std::cout << std::setprecision(9) << "\n       "
          << diff.count() << " seconds (measured)" << std::endl;  // show elapsed time

PS. icc is smart enough to eliminate Option 2. Try sum += num; and print out sum.

This is the output from perf: (the measured time remains the same without using perf)

Option 1: Merge

       0.904575206 seconds (measured)

 Performance counter stats for './option-1-merge':

    33,395,981,671      cpu-cycles
       149,371,004      cache-misses              #   49.807 % of all cacherefs
       299,898,436      cache-references
    24,254,303,068      cycle-activity.stalls-ldm-pending

       7.678166480 seconds time elapsed

Option 2: Traverse

       1.01401903 seconds (measured)

 Performance counter stats for './option-2-traverse':

    33,844,645,296      cpu-cycles
       138,723,898      cache-misses             #   48.714 % of all cacherefs
       284,770,796      cache-references
    25,141,751,107      cycle-activity.stalls-ldm-pending

       7.806018949 seconds time elapsed

Due to the property of horrible spatial locality on these linked lists. The cache miss is the major reason that make CPU stalls, and occupies most of the CPU resources. The strange point is that option 2 has fewer cache misses than option 1, but it has a higher amount of CPU stalls and CPU cycles to accomplish its task. What makes this abnormality happen?

Body:
As you know, it is memory that is taking all your time.

Cache misses are bad, but so are stalls.

From this paper:

Applications with irregular memory access patterns, e.g.,dereferencing chains of pointers when traversing linked lists or trees, may not generate enough concurrently outstanding requests to fully utilize the data paths. Nevertheless, such applications are clearly limited by the performance of memory accesses as well. Therefore, considering the bandwidth utilization is not sufficient to detect all memory related performance issues.

Basically, randomly walking pointers can fail to saturate the memory bandwidth.

The tight loop on each is blocked each iteration by waiting on where the next pointer is to be loaded.  If it is not in cache, the cpu can do nothing -- it stalls.

The combined tight loop/merge tries to load two pages into the cache.  When one is loading, sometimes the cpu can advannce on the other.

The result you measured was that the merge has fewer stalls that the naked wasted double iteration.

Or in other words,

24,254,303,068      cycle-activity.stalls-ldm-pending

is a big number and smaller than:

25,141,751,107      cycle-activity.stalls-ldm-pending

I am surprised this is enough to make a 10% difference, but that is why perf is about measuring.


问:
Best way to remove multiple entries from kml file
I have a very large KML file (over 20000 placemarkers). They are named by numbers which go up in increments of 5 starting at about 7000 up to 27000.

```<code><Placemark>
    <name>7750</name>
    <description><![CDATA[converted by:</br><a href="http://gridreferencefinder.com/">GridReferenceFinder.com</a></br>]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>
</code>```

I would like to remove any placemarker that doesnt end in 00 or 50. Having a placemarker every 5 metres is slowing down some of the lower end devices on site.

Is there some script, command or whatever that will check the name and if it doesn't end in 00 or 50 delete from <Placemark> to </Placemark> for that entry?

You would literally be saving me 10 hours work deleting them individually.

答:
```<code>awk '$0 == "<Placemark>" {cnt=cnt+1} {arry[cnt]=arry[cnt]$0"\n";if ($0 ~ /<name>/) {match($0,/[[:digit:]]+/);num=substr($0,RSTART,RLENGTH);numbs[num]=cnt}} END { for ( i in numbs ) {if ( substr(i,length(i)-1,length(i)) == "00" || substr(i,length(i)-1,length(i)) == "50") { print arry[numbs[i]] } } }' filename
</code>```

<p>An alternate awk solution is as above. We first set a counter for an array when $0 = . Then we set the array arry for each Placement element in the file. As we do this we also check for the the name index in the file. When we find this, we pattern match the number within (match function) and then use this to sets another array numbs that tracks the numbers against the counter for each placement element. We finally loop through each elements in numbs, checking the number to ensure it ends in 50 or 00. If it does, the arry index is printed. </p>

Body:
I have a very large KML file (over 20000 placemarkers). They are named by numbers which go up in increments of 5 starting at about 7000 up to 27000.

<Placemark>
    <name>7750</name>
    <description><![CDATA[converted by:
GridReferenceFinder.com
]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>

I would like to remove any placemarker that doesnt end in 00 or 50. Having a placemarker every 5 metres is slowing down some of the lower end devices on site.

Is there some script, command or whatever that will check the name and if it doesn't end in 00 or 50 delete from <Placemark> to </Placemark> for that entry?

You would literally be saving me 10 hours work deleting them individually.

Body:
awk '$0 == "<Placemark>" {cnt=cnt+1} {arry[cnt]=arry[cnt]$0"\n";if ($0 ~ /<name>/) {match($0,/[[:digit:]]+/);num=substr($0,RSTART,RLENGTH);numbs[num]=cnt}} END { for ( i in numbs ) {if ( substr(i,length(i)-1,length(i)) == "00" || substr(i,length(i)-1,length(i)) == "50") { print arry[numbs[i]] } } }' filename

An alternate awk solution is as above. We first set a counter for an array when $0 = . Then we set the array arry for each Placement element in the file. As we do this we also check for the the name index in the file. When we find this, we pattern match the number within (match function) and then use this to sets another array numbs that tracks the numbers against the counter for each placement element. We finally loop through each elements in numbs, checking the number to ensure it ends in 50 or 00. If it does, the arry index is printed.


答:
You have to set listener for your RadioButtons, like below.

```<code>radioButton1 .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

       @Override
       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                if(isChecked)
Toast.makeText(getApplicationContext(), radioButton1.getText(),Toast.LENGTH_LONG).show();
       }
   }
);
</code>```

Title: isChecked function is not working for radio button in android

Body:
You have to set listener for your RadioButtons, like below.

radioButton1 .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

       @Override
       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                if(isChecked)
Toast.makeText(getApplicationContext(), radioButton1.getText(),Toast.LENGTH_LONG).show();
       }
   }
);


问:
how to call stored procedure in EF6 with output parameters
i have a stored procedure which returns a parameter containing string in it i don't know how to call it and get the output parameter to show on my view

```<code>ALTER PROCEDURE [dbo].[sp_test]
@room_type varchar(40)
,@room_price_min float
,@room_price_max    float
,@room_number   varchar(30)
,@new varchar(50) output
as
;
--select @room_no
if exists(select room_number from Rooms_ms where room_number=@room_number)
begin
    set @new='Room Already Exists'
    select @new
    return
end

insert into Rooms_ms(room_type,room_price_min,room_price_max,room_number) values
(@room_type,@room_price_min,@room_price_max,@room_number)

set @new='Successfully'
select  @new
return
</code>```

I'm trying to catch it like below but don't know how to exactly do it.

```<code> var result=   db.sp_test(a, b, 0, c);
</code>```

Thank you

答:
It is one of sample my code</p>

```<code>string sql = string.Format("exec sp_MyTest '" + methods.DateTimeFormat(vmodel.Search.FDate, false, 1) + "','" + methods.DateTimeFormat(vmodel.Search.TDate, false, 1) + "','" + vmodel.Search.LocationId + "',"+ 0"'");

var result = db.(DbSetName(like.Students))SqlQuery(sql).ToString();

if Return List, then
    var result = db.(DbSetName(like.Students))SqlQuery(sql).ToList();
</code>```

Body:
i have a stored procedure which returns a parameter containing string in it i don't know how to call it and get the output parameter to show on my view

ALTER PROCEDURE [dbo].[sp_test]
@room_type varchar(40)
,@room_price_min float
,@room_price_max    float
,@room_number   varchar(30)
,@new varchar(50) output
as
;
--select @room_no
if exists(select room_number from Rooms_ms where room_number=@room_number)
begin
    set @new='Room Already Exists'
    select @new
    return
end

insert into Rooms_ms(room_type,room_price_min,room_price_max,room_number) values
(@room_type,@room_price_min,@room_price_max,@room_number)

set @new='Successfully'
select  @new
return

I'm trying to catch it like below but don't know how to exactly do it.

 var result=   db.sp_test(a, b, 0, c);

Thank you

Body:
It is one of sample my code

string sql = string.Format("exec sp_MyTest '" + methods.DateTimeFormat(vmodel.Search.FDate, false, 1) + "','" + methods.DateTimeFormat(vmodel.Search.TDate, false, 1) + "','" + vmodel.Search.LocationId + "',"+ 0"'");

var result = db.(DbSetName(like.Students))SqlQuery(sql).ToString();

if Return List, then
    var result = db.(DbSetName(like.Students))SqlQuery(sql).ToList();


答: You should set the clipsToBounds property of the higher level container view (like the contentView of your cell.)

Title: ClipsToBounds is not working in cells


问:
Table myapp_tableName already exists
i have created a django app and add some model fields on models.py

1.logo

2.shirt

and their attributes are
pid, name and org
then i added a new attribute price to them. and execute command python manage.py makemigrations and python manage.py migrate i got the error 'Table buapp_dealer already exists.

here is my models.py

```<code>from django.db import models

# Create your models here.

class founder(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=50)
    country=models.CharField(max_length=20)
    email=models.EmailField(null=True)
    headshot=models.ImageField(upload_to='images',null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

class supporter(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=20)
    email=models.EmailField(null=True)
    headshot=models.ImageField(upload_to='images',null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

    class Admin:
        list_display=('name','address','email')

class dealer(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=40)
    #city=models.CharField(max_length=60)
    country=models.CharField(max_length=50)
    website=models.URLField(null=True)
    rep=models.IntegerField(null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

    class Admin:
        list_display=('name','address','country')
        list_filter=('name','country')
        ordering=('rep',)
        search_fields=('name')

class tshirt(models.Model):
    price=models.FloatField(default=0.0)
    name=models.CharField(max_length=50,default='default')
    fontimage=models.ImageField(upload_to='images/tshirts',null=True)
    backimage=models.ImageField(upload_to='images/tshirts',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__
    class Admin:
        list_display=('pid','price','fontimage')
        list_filter=('price')
        ordering=('-pid')
        search_fields=('name')

class logo(models.Model):
    pid=models.IntegerField()
    price=models.FloatField(default=0.0)
    org=models.CharField(max_length=50)
    img=models.ImageField(upload_to='images/tshirts',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__
    class Admin:
        list_display=('pid','price','img')
        list_filter=('price')
        ordering=('-pid')
        search_fields=('org')

class final(models.Model):
    pid=models.IntegerField()
    price=models.FloatField(default=0.00)
    fontimg=models.ImageField(upload_to='images/finals',null=True)
    backimg=models.ImageField(upload_to='images/finals',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__
</code>```

答:
Check if the field you added (price) is actually in the database then make a backup of your database and try running this (for appname buapp_dealer)

```<code>python manage.py migrate --fake buapp_dealer
</code>```

This will mark migrations as complete.

Title: Table myapp_tableName already exists

Body:
i have created a django app and add some model fields on models.py

1.logo

2.shirt

and their attributes are
pid, name and org
then i added a new attribute price to them. and execute command python manage.py makemigrations and python manage.py migrate i got the error 'Table buapp_dealer already exists.

here is my models.py

from django.db import models

# Create your models here.

class founder(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=50)
    country=models.CharField(max_length=20)
    email=models.EmailField(null=True)
    headshot=models.ImageField(upload_to='images',null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

class supporter(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=20)
    email=models.EmailField(null=True)
    headshot=models.ImageField(upload_to='images',null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

    class Admin:
        list_display=('name','address','email')

class dealer(models.Model):
    name=models.CharField(max_length=30)
    address=models.CharField(max_length=40)
    #city=models.CharField(max_length=60)
    country=models.CharField(max_length=50)
    website=models.URLField(null=True)
    rep=models.IntegerField(null=True)
    def __str__(self):
        return self.name
    __repr__=__str__

    class Admin:
        list_display=('name','address','country')
        list_filter=('name','country')
        ordering=('rep',)
        search_fields=('name')

class tshirt(models.Model):
    price=models.FloatField(default=0.0)
    name=models.CharField(max_length=50,default='default')
    fontimage=models.ImageField(upload_to='images/tshirts',null=True)
    backimage=models.ImageField(upload_to='images/tshirts',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__
    class Admin:
        list_display=('pid','price','fontimage')
        list_filter=('price')
        ordering=('-pid')
        search_fields=('name')

class logo(models.Model):
    pid=models.IntegerField()
    price=models.FloatField(default=0.0)
    org=models.CharField(max_length=50)
    img=models.ImageField(upload_to='images/tshirts',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__
    class Admin:
        list_display=('pid','price','img')
        list_filter=('price')
        ordering=('-pid')
        search_fields=('org')

class final(models.Model):
    pid=models.IntegerField()
    price=models.FloatField(default=0.00)
    fontimg=models.ImageField(upload_to='images/finals',null=True)
    backimg=models.ImageField(upload_to='images/finals',null=True)
    def __str__(self):
        return str(self.pid)
    __repr__=__str__

Body:
Check if the field you added (price) is actually in the database then make a backup of your database and try running this (for appname buapp_dealer)

python manage.py migrate --fake buapp_dealer

This will mark migrations as complete.


问:
R: Global assignment of vector element works only inside a function
I'm working on a project where there are some global assignments, and I ran into something sort of odd. I was hoping someone could help me with it.

I wrote this toy example to demonstrate the problem:

```<code>x <-  1:3 ; x <-  c(1, 2, 5) # this works fine
x <-  1:3 ; x[3] <- 5        # this works fine

x <<- 1:3 ; x <<- c(1, 2, 5) # this works fine
x <<- 1:3 ; x[3] <<- 5       # this does not work
# Error in x[3] <<- 5 : object 'x' not found

same.thing.but.in.a.function = function() {
  x <<- 1:3
  x[3] <<- 5
}
same.thing.but.in.a.function(); x
# works just fine
</code>```

So, it seems it's not possible to change part of a vector using a global assignment -- unless that assignment is contained within a function. Can anyone explain why this is the case?

答:
If you change to single arrow assignment then it work

```<code>x <<- 1:3 ; x[3] <- 5
</code>```

BTW - I would suggest these wonderful discussions for better understanding and proper use of <<- operator -

How do you use "<<-" (scoping assignment) in R?

What is the difference between assign() and <<- in R?

Body:
I'm working on a project where there are some global assignments, and I ran into something sort of odd. I was hoping someone could help me with it.

I wrote this toy example to demonstrate the problem:

x <-  1:3 ; x <-  c(1, 2, 5) # this works fine
x <-  1:3 ; x[3] <- 5        # this works fine

x <<- 1:3 ; x <<- c(1, 2, 5) # this works fine
x <<- 1:3 ; x[3] <<- 5       # this does not work
# Error in x[3] <<- 5 : object 'x' not found

same.thing.but.in.a.function = function() {
  x <<- 1:3
  x[3] <<- 5
}
same.thing.but.in.a.function(); x
# works just fine

So, it seems it's not possible to change part of a vector using a global assignment -- unless that assignment is contained within a function. Can anyone explain why this is the case?

Body:
If you change to single arrow assignment then it work

x <<- 1:3 ; x[3] <- 5

BTW - I would suggest these wonderful discussions for better understanding and proper use of <<- operator -

How do you use "<<-" (scoping assignment) in R?

What is the difference between assign() and <<- in R?


问:
CSS not linked to HTML page
Good morning guys,

I am playing around building a small website. In the html I have my link to my CSS file but for some reason the CSS is not being shown on the page.

The link tag looks as follows:

```<code><link rel="stylesheet" href="./styles/style.css" type="text/css">
</code>```

The site does not contain any styles that I have built. Am I doing something wrong here?

答:
```<code><head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
</code>```

Try to include the code to head as I show above for mystyle.css rewrite your own css file make sure to have the same name as your css file is check if a letter is capital .

I saw  also you write text/css instead of test.css which is correct .

Title: CSS not linked to HTML page

Body:
Good morning guys,

I am playing around building a small website. In the html I have my link to my CSS file but for some reason the CSS is not being shown on the page.

The link tag looks as follows:

<link rel="stylesheet" href="./styles/style.css" type="text/css">

The site does not contain any styles that I have built. Am I doing something wrong here?

Body:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

Try to include the code to head as I show above for mystyle.css rewrite your own css file make sure to have the same name as your css file is check if a letter is capital .

I saw  also you write text/css instead of test.css which is correct .


问:
MySQL storing duration time - datatype?
I need to calculate the time a user spends on site. It is difference between logout time and login time to give me something like "Mr X spent 4 hours and 43 minutes online". So to store the4 hours and 43 minutes i declared it like this:
duration time NOT NULL

Is this valid or a better way to store this? I need to store in the DB because I have other calculations I need to use this for + other use cases.

答: I wouldn't use time as you would be limited to 24 hours. The easiest would just to store an integer in minutes (or seconds depending on the resolution you need).</p>

Title: MySQL storing duration time - datatype?


问:
Skipping to "catch" instantly after changing PHP code in Java Android application
So I've been toying around in my mobile app that's supposed to let me register accounts and log in while getting some data from a database I've created. All was fine and dandy until I've changed my register.php file to check if the login is already taken and act accordingly to that. I tought I had a problem with my JSONObject and response, so I've tried using a string instead of boolean but still the program only goes into the try section to JSONObject jsonResponse = new JSONObject(response); and then in instantly goes into the catch part of the code. I didn't change much, honestly i'd say that the code I've written now is cleaner than the one before but it doesn't work properly.

When I click the "Zarejestruj" button (polish for Register) data should be sent to database (which happens, but I can add an infinite amount of same logins for some reason) and the activity should go back to LoginActivity.java but it doesnt, it just sends the credentials into the database and stays there for infinity while allowing me to spam the hell out of the bRegister.

Here's the java code:

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    Log.d("RA", "Zmienne");
    final EditText etName = (EditText) findViewById(R.id.etName);
    final EditText etSurame = (EditText) findViewById(R.id.etSurname);
    final EditText etLogin = (EditText) findViewById(R.id.etLogin);
    final EditText etPassword = (EditText) findViewById(R.id.etPassword);
    final EditText etGroupNumber = (EditText) findViewById(R.id.etGroupNumber);
    final EditText etIndexNumber = (EditText) findViewById(R.id.etIndexNumber);

    final Button bRegister = (Button) findViewById(R.id.bRegister);
    Log.d("RA", "Po zmienncyh");

    bRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final String name = etName.getText().toString().trim();
            final String surname = etSurame.getText().toString().trim();
            final String login = etLogin.getText().toString().trim();
            final String password = etPassword.getText().toString().trim();
            final String groupNumber = etGroupNumber.getText().toString().trim();
            final String indexNumber = etIndexNumber.getText().toString().trim();

            Log.d("RA", "Przed wywołąniem responseListener");
            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("RA", "Response");
                    Log.d("RA", response);
                    Log.d("RA", "onResponse");
                    try {
                        Log.d("RA", "Try");
                        JSONObject jsonResponse = new JSONObject(response);
                        Log.d("RA", "ObiektResponse");
                        String success = jsonResponse.getString(response);
                        if (success == "success") {
                            Log.d("RA", "Success");
                            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);

                        } else {
                            Log.d("RA", "Error");
                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Register Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }
                    } catch (JSONException e) {
                        Log.d("RA", "catch");
                        e.printStackTrace();
                    }
                }
            };
            Log.d("RA", "Wykonało się");
            RegisterRequest registerRequest = new RegisterRequest(name, surname, login, password, groupNumber, indexNumber, responseListener);
            Log.d("RA", "queue");
            RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
            Log.d("RA", "registerRequest");
            queue.add(registerRequest);
            Log.d("RA", "Koniec");
        }
    });
}}
</code>```

And here is my Register.php file:

```<code>require("Password.php");

ini_set('display_errors', 'On');
$mysqli = new mysqli("localhost", "id2147309_javaprojekt123", "javaprojekt321", "id2147309_javaprojekt");

if($mysqli->connect_errno){
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if(isset($_POST["name"]) && isset($_POST["surname"]) && isset($_POST["login"]) && isset($_POST["password"]) && isset($_POST["groupNumber"]) && isset($_POST["indexNumber"]))
{
$name = $_POST["name"];
$surname= $_POST["surname"];
$login = $_POST["login"];
$password = $_POST["password"];
$groupNumber = $_POST["groupNumber"];
$indexNumber = $_POST["indexNumber"];
}

function registerUser(){
    global $mysqli, $name, $surname, $login, $password, $groupNumber, $indexNumber;
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $mysqli->prepare("INSERT INTO user (name, surname, login, password, groupNumber, indexNumber) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssss", $name, $surname, $login, $passwordHash, $groupNumber, $indexNumber);
    $stmt->execute();
    $stmt->close();
}

function usernameAvailable(){
    global $mysqli, $login, $count;
    $sql = "SELECT * FROM users WHERE login = ?";
    if($stmt = $mysqli->prepare($sql)){
    $stmt->bind_param("s", $login);
    $stmt->execute();
    $stmt->store_result();
    $count = $stmt->num_rows;
    $stmt->close();
    }
    if($count < 1){
        return true;
    }
    else
        return false;
}
    $response = "false";

if(usernameAvailable()){
    registerUser();
    $response = "true";
}echo json_encode($response);
$mysqli->close();
</code>```

答:
You might want to try assigning the return from mysqli->prepare() to a variable and testing that is returning true before proceeding to the actual database actions. Using a try/catch method it might help identify if there is a problem in the php.

```<code>ini_set('display_errors', 'On');
require("Password.php");

try{

    $mysqli = new mysqli( "localhost", "id2147309_javaprojekt123", "javaprojekt321", "id2147309_javaprojekt" );

    if( $mysqli->connect_errno ){
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

    if( isset( $_POST["name"], $_POST["surname"], $_POST["login"], $_POST["password"], $_POST["groupNumber"], $_POST["indexNumber"] ) ){
        $name = $_POST["name"];
        $surname= $_POST["surname"];
        $login = $_POST["login"];
        $password = $_POST["password"];
        $groupNumber = $_POST["groupNumber"];
        $indexNumber = $_POST["indexNumber"];
    }

    function registerUser(){
        global $mysqli, $name, $surname, $login, $password, $groupNumber, $indexNumber;
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);

        $stmt = $mysqli->prepare("INSERT INTO `user` ( `name`, `surname`, `login`, `password`, `groupNumber`, `indexNumber` ) VALUES (?, ?, ?, ?, ?, ?)");

        if( $stmt ){
            $stmt->bind_param( "ssssss", $name, $surname, $login, $passwordHash, $groupNumber, $indexNumber );
            $stmt->execute();
            $stmt->close();
            return true;
        } else {
            throw new Exception( 'Failed to prepare sql query in: ' . __FUNCTION__ );
        }
        return false;
    }
    function usernameAvailable(){
        global $mysqli, $login, $count;
        $sql = 'SELECT * FROM `users` WHERE `login` = ?';
        $stmt=$mysqli->prepare( $sql );

        if( $stmt ){
            $stmt->bind_param("s", $login);
            $stmt->execute();
            $stmt->store_result();
            $count = $stmt->num_rows;
            $stmt->close();
        } else {
            throw new Exception( 'Failed to prepare sql query in: ' . __FUNCTION__ );
        }
        return $count==0 ? true : false;
    }

    $available = call_user_func('usernameAvailable');
    $response = $available ? call_user_func('registerUser') : false;
    $mysqli->close();

    echo json_encode( $response );

}catch( Exception $e ){
    echo json_encode( array(
        'success'   =>  false,
        'Exception' =>  $e->getMessage()
    ));
}
</code>```

Body:
So I've been toying around in my mobile app that's supposed to let me register accounts and log in while getting some data from a database I've created. All was fine and dandy until I've changed my register.php file to check if the login is already taken and act accordingly to that. I tought I had a problem with my JSONObject and response, so I've tried using a string instead of boolean but still the program only goes into the try section to JSONObject jsonResponse = new JSONObject(response); and then in instantly goes into the catch part of the code. I didn't change much, honestly i'd say that the code I've written now is cleaner than the one before but it doesn't work properly.

When I click the "Zarejestruj" button (polish for Register) data should be sent to database (which happens, but I can add an infinite amount of same logins for some reason) and the activity should go back to LoginActivity.java but it doesnt, it just sends the credentials into the database and stays there for infinity while allowing me to spam the hell out of the bRegister.

Here's the java code:

public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    Log.d("RA", "Zmienne");
    final EditText etName = (EditText) findViewById(R.id.etName);
    final EditText etSurame = (EditText) findViewById(R.id.etSurname);
    final EditText etLogin = (EditText) findViewById(R.id.etLogin);
    final EditText etPassword = (EditText) findViewById(R.id.etPassword);
    final EditText etGroupNumber = (EditText) findViewById(R.id.etGroupNumber);
    final EditText etIndexNumber = (EditText) findViewById(R.id.etIndexNumber);

    final Button bRegister = (Button) findViewById(R.id.bRegister);
    Log.d("RA", "Po zmienncyh");

    bRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final String name = etName.getText().toString().trim();
            final String surname = etSurame.getText().toString().trim();
            final String login = etLogin.getText().toString().trim();
            final String password = etPassword.getText().toString().trim();
            final String groupNumber = etGroupNumber.getText().toString().trim();
            final String indexNumber = etIndexNumber.getText().toString().trim();

            Log.d("RA", "Przed wywołąniem responseListener");
            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("RA", "Response");
                    Log.d("RA", response);
                    Log.d("RA", "onResponse");
                    try {
                        Log.d("RA", "Try");
                        JSONObject jsonResponse = new JSONObject(response);
                        Log.d("RA", "ObiektResponse");
                        String success = jsonResponse.getString(response);
                        if (success == "success") {
                            Log.d("RA", "Success");
                            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);

                        } else {
                            Log.d("RA", "Error");
                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Register Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }
                    } catch (JSONException e) {
                        Log.d("RA", "catch");
                        e.printStackTrace();
                    }
                }
            };
            Log.d("RA", "Wykonało się");
            RegisterRequest registerRequest = new RegisterRequest(name, surname, login, password, groupNumber, indexNumber, responseListener);
            Log.d("RA", "queue");
            RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
            Log.d("RA", "registerRequest");
            queue.add(registerRequest);
            Log.d("RA", "Koniec");
        }
    });
}}

And here is my Register.php file:

require("Password.php");

ini_set('display_errors', 'On');
$mysqli = new mysqli("localhost", "id2147309_javaprojekt123", "javaprojekt321", "id2147309_javaprojekt");

if($mysqli->connect_errno){
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if(isset($_POST["name"]) && isset($_POST["surname"]) && isset($_POST["login"]) && isset($_POST["password"]) && isset($_POST["groupNumber"]) && isset($_POST["indexNumber"]))
{
$name = $_POST["name"];
$surname= $_POST["surname"];
$login = $_POST["login"];
$password = $_POST["password"];
$groupNumber = $_POST["groupNumber"];
$indexNumber = $_POST["indexNumber"];
}

function registerUser(){
    global $mysqli, $name, $surname, $login, $password, $groupNumber, $indexNumber;
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $mysqli->prepare("INSERT INTO user (name, surname, login, password, groupNumber, indexNumber) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssss", $name, $surname, $login, $passwordHash, $groupNumber, $indexNumber);
    $stmt->execute();
    $stmt->close();
}

function usernameAvailable(){
    global $mysqli, $login, $count;
    $sql = "SELECT * FROM users WHERE login = ?";
    if($stmt = $mysqli->prepare($sql)){
    $stmt->bind_param("s", $login);
    $stmt->execute();
    $stmt->store_result();
    $count = $stmt->num_rows;
    $stmt->close();
    }
    if($count < 1){
        return true;
    }
    else
        return false;
}
    $response = "false";

if(usernameAvailable()){
    registerUser();
    $response = "true";
}echo json_encode($response);
$mysqli->close();

Body:
You might want to try assigning the return from mysqli->prepare() to a variable and testing that is returning true before proceeding to the actual database actions. Using a try/catch method it might help identify if there is a problem in the php.

ini_set('display_errors', 'On');
require("Password.php");

try{

    $mysqli = new mysqli( "localhost", "id2147309_javaprojekt123", "javaprojekt321", "id2147309_javaprojekt" );

    if( $mysqli->connect_errno ){
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

    if( isset( $_POST["name"], $_POST["surname"], $_POST["login"], $_POST["password"], $_POST["groupNumber"], $_POST["indexNumber"] ) ){
        $name = $_POST["name"];
        $surname= $_POST["surname"];
        $login = $_POST["login"];
        $password = $_POST["password"];
        $groupNumber = $_POST["groupNumber"];
        $indexNumber = $_POST["indexNumber"];
    }

    function registerUser(){
        global $mysqli, $name, $surname, $login, $password, $groupNumber, $indexNumber;
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);

        $stmt = $mysqli->prepare("INSERT INTO `user` ( `name`, `surname`, `login`, `password`, `groupNumber`, `indexNumber` ) VALUES (?, ?, ?, ?, ?, ?)");

        if( $stmt ){
            $stmt->bind_param( "ssssss", $name, $surname, $login, $passwordHash, $groupNumber, $indexNumber );
            $stmt->execute();
            $stmt->close();
            return true;
        } else {
            throw new Exception( 'Failed to prepare sql query in: ' . __FUNCTION__ );
        }
        return false;
    }
    function usernameAvailable(){
        global $mysqli, $login, $count;
        $sql = 'SELECT * FROM `users` WHERE `login` = ?';
        $stmt=$mysqli->prepare( $sql );

        if( $stmt ){
            $stmt->bind_param("s", $login);
            $stmt->execute();
            $stmt->store_result();
            $count = $stmt->num_rows;
            $stmt->close();
        } else {
            throw new Exception( 'Failed to prepare sql query in: ' . __FUNCTION__ );
        }
        return $count==0 ? true : false;
    }

    $available = call_user_func('usernameAvailable');
    $response = $available ? call_user_func('registerUser') : false;
    $mysqli->close();

    echo json_encode( $response );

}catch( Exception $e ){
    echo json_encode( array(
        'success'   =>  false,
        'Exception' =>  $e->getMessage()
    ));
}


问:
Select Same Element on Second List By Order of Second List
I have a two list of character arrays:

```<code>char[] charA = new char[] { 'a', 'd', 'd', 'b', 'y', 'c', 'a' };
char[] charB = new char[] { 'a', 'b', 'c', 'd'};
</code>```

Now I want to get all the same element and get the same arrangement like on second list (arrangement is a, b, c, d):

```<code>var final = charA.Where(x => charB.Any(y => y == x)).ToArray();
</code>```

The result of this is:

```<code>'a', 'd', 'd', 'b', 'c', 'a'
</code>```

But what I want is the arrangement on the second list using LINQ:

```<code>'a', 'a', 'b', 'c', 'd', 'd'
</code>```

答:
One way to achieve it is to select from the second array and join to it the first:

```<code>var result = from b in charB
             join a in charA on b equals a into c
             from a in c
             select a;
</code>```

You can also achieve it joining charA to charB and using the Select overload that receives the item's index:

```<code>var result = from a in charA
             join b in charB.Select((item, index) => new { item, index }) on a equals b.item
             orderby b.index
             select a;
</code>```

A little note about your implementation: see you can use Contains instead of Any:

```<code>charA.Where(x => charB.Contains(x))
</code>```

Body:
I have a two list of character arrays:

char[] charA = new char[] { 'a', 'd', 'd', 'b', 'y', 'c', 'a' };
char[] charB = new char[] { 'a', 'b', 'c', 'd'};

Now I want to get all the same element and get the same arrangement like on second list (arrangement is a, b, c, d):

var final = charA.Where(x => charB.Any(y => y == x)).ToArray();

The result of this is:

'a', 'd', 'd', 'b', 'c', 'a'

But what I want is the arrangement on the second list using LINQ:

'a', 'a', 'b', 'c', 'd', 'd'

Body:
One way to achieve it is to select from the second array and join to it the first:

var result = from b in charB
             join a in charA on b equals a into c
             from a in c
             select a;

You can also achieve it joining charA to charB and using the Select overload that receives the item's index:

var result = from a in charA
             join b in charB.Select((item, index) => new { item, index }) on a equals b.item
             orderby b.index
             select a;

A little note about your implementation: see you can use Contains instead of Any:

charA.Where(x => charB.Contains(x))


问:
Scrapy: AttributeError: 'YourCrawler' object has no attribute 'parse_following_urls'
I am writing a scrapy spider. I have been reading this question: Scrapy: scraping a list of links, and I can make it recognise the urls in a listpage, but I cant make it go inside the urls and save the data I want to see.

```<code>from scrapy.contrib.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request

class YourCrawler(CrawlSpider):
    name = "bookstore_2"
    start_urls = [
    'https://example.com/materias/?novedades=LC&p',
    ]

    def parse(self, response):
        # go to the urls in the list
        s = Selector(response)
        page_list_urls = s.xpath('///*[@id="results"]/ul/li/div[1]/h4/a[2]/@href').extract()
        for url in page_list_urls:
            yield Request(url, callback=self.parse_following_urls, dont_filter=True)

            # For the urls in the list, go inside, and in div#main, take the div.ficha > div.caracteristicas > ul > li
            def parse_following_urls(self, response):
                #Parsing rules go here
                for each_book in response.css('div#main'):
                    yield {
                    'book_isbn': each_book.css('div.ficha > div.caracteristicas > ul > li').extract(),
                    }
                    # Return back and go to bext page in div#paginat ul li.next a::attr(href) and begin again
                    next_page = response.css('div#paginat ul li.next a::attr(href)').extract_first()
                    if next_page is not None:
                        next_page = response.urljoin(next_page)
                        yield scrapy.Request(next_page, callback=self.parse)
</code>```

It gives an error:

```<code>AttributeError: 'YourCrawler' object has no attribute 'parse_following_urls'
</code>```

And I don't understand why!

EDIT --

As the response says, I had to close the method with the indentation like here:

```<code>from scrapy.contrib.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request

class YourCrawler(CrawlSpider):
    name = "bookstore_2"
    start_urls = [
    'https://example.com/materias/?novedades=LC&p',
    ]

    def parse(self, response):
        # go to the urls in the list
        s = Selector(response)
        page_list_urls = s.xpath('///*[@id="results"]/ul/li/div[1]/h4/a[2]/@href').extract()
        for url in page_list_urls:
            yield Request(url, callback=self.parse_following_urls, dont_filter=True)

    # For the urls in the list, go inside, and in div#main, take the div.ficha > div.caracteristicas > ul > li
    def parse_following_urls(self, response):
        #Parsing rules go here
        for each_book in response.css('div#main'):
            yield {
            'book_isbn': each_book.css('div.ficha > div.caracteristicas > ul > li').extract(),
            }
            # Return back and go to bext page in div#paginat ul li.next a::attr(href) and begin again
            next_page = response.css('div#paginat ul li.next a::attr(href)').extract_first()
            if next_page is not None:
                next_page = response.urljoin(next_page)
                yield scrapy.Request(next_page, callback=self.parse)
</code>```

But there is another problem, I think related to the urls, and now I am having this traceback:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/scrapy/utils/defer.py", line 102, in iter_errback
    yield next(it)
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/offsite.py", line 29, in process_spider_output
    for x in result:
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/referer.py", line 339, in <genexpr>
    return (_set_referer(r) for r in result or ())
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/urllength.py", line 37, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/depth.py", line 58, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/Users/nikita/scrapy/bookstore_2/bookstore_2/spiders/bookstore_2.py", line 16, in parse
    yield Request(url, callback=self.parse_following_urls, dont_filter=True)
  File "/usr/local/lib/python2.7/site-packages/scrapy/http/request/__init__.py", line 25, in __init__
    self._set_url(url)
  File "/usr/local/lib/python2.7/site-packages/scrapy/http/request/__init__.py", line 58, in _set_url
    raise ValueError('Missing scheme in request url: %s' % self._url)
ValueError: Missing scheme in request url: /book/?id=9780374281083
</code>```

Maybe because I have to tell scrappy what is the base url? Should I add somewhere a urljoin?

EDIT_2 ---

Ok, the problem was with the urls. Adding

```<code>response.urljoin(
</code>```

solved this issue.

答:
In your code,

```<code>  yield Request(url, callback=self.parse_following_urls, dont_filter=True)
</code>```

you used parse_following_urls with self.

But parse_following_urls is defined in parse function, so it isn't a method of YourCrawler.

That's why the error said
AttributeError: 'YourCrawler' object has no attribute 'parse_following_urls'

you should assign it like:

```<code>class YourCrawler(CrawlSpider):
    def parse_following_urls(self, response):
    ....
</code>```

to make it method of the class.

edit
 for a additional question:

In your code s.xpath('///*[@id="results"]/ul/li/div[1]/h4/a[2]/@href') indicates the href attribute of the element a tag of the html page you want to scrap.
 However, it is only '/book/?id=9780374281083', not the full url.
 so, you should make it like : https://lacentral.com/book/?id=9780374281083
 to use it.

Body:
I am writing a scrapy spider. I have been reading this question: Scrapy: scraping a list of links, and I can make it recognise the urls in a listpage, but I cant make it go inside the urls and save the data I want to see.

from scrapy.contrib.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request

class YourCrawler(CrawlSpider):
    name = "bookstore_2"
    start_urls = [
    'https://example.com/materias/?novedades=LC&p',
    ]

    def parse(self, response):
        # go to the urls in the list
        s = Selector(response)
        page_list_urls = s.xpath('///*[@id="results"]/ul/li/div[1]/h4/a[2]/@href').extract()
        for url in page_list_urls:
            yield Request(url, callback=self.parse_following_urls, dont_filter=True)

            # For the urls in the list, go inside, and in div#main, take the div.ficha > div.caracteristicas > ul > li
            def parse_following_urls(self, response):
                #Parsing rules go here
                for each_book in response.css('div#main'):
                    yield {
                    'book_isbn': each_book.css('div.ficha > div.caracteristicas > ul > li').extract(),
                    }
                    # Return back and go to bext page in div#paginat ul li.next a::attr(href) and begin again
                    next_page = response.css('div#paginat ul li.next a::attr(href)').extract_first()
                    if next_page is not None:
                        next_page = response.urljoin(next_page)
                        yield scrapy.Request(next_page, callback=self.parse)

It gives an error:

AttributeError: 'YourCrawler' object has no attribute 'parse_following_urls'

And I don't understand why!

EDIT --

As the response says, I had to close the method with the indentation like here:

from scrapy.contrib.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request

class YourCrawler(CrawlSpider):
    name = "bookstore_2"
    start_urls = [
    'https://example.com/materias/?novedades=LC&p',
    ]

    def parse(self, response):
        # go to the urls in the list
        s = Selector(response)
        page_list_urls = s.xpath('///*[@id="results"]/ul/li/div[1]/h4/a[2]/@href').extract()
        for url in page_list_urls:
            yield Request(url, callback=self.parse_following_urls, dont_filter=True)

    # For the urls in the list, go inside, and in div#main, take the div.ficha > div.caracteristicas > ul > li
    def parse_following_urls(self, response):
        #Parsing rules go here
        for each_book in response.css('div#main'):
            yield {
            'book_isbn': each_book.css('div.ficha > div.caracteristicas > ul > li').extract(),
            }
            # Return back and go to bext page in div#paginat ul li.next a::attr(href) and begin again
            next_page = response.css('div#paginat ul li.next a::attr(href)').extract_first()
            if next_page is not None:
                next_page = response.urljoin(next_page)
                yield scrapy.Request(next_page, callback=self.parse)

But there is another problem, I think related to the urls, and now I am having this traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/scrapy/utils/defer.py", line 102, in iter_errback
    yield next(it)
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/offsite.py", line 29, in process_spider_output
    for x in result:
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/referer.py", line 339, in <genexpr>
    return (_set_referer(r) for r in result or ())
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/urllength.py", line 37, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/usr/local/lib/python2.7/site-packages/scrapy/spidermiddlewares/depth.py", line 58, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/Users/nikita/scrapy/bookstore_2/bookstore_2/spiders/bookstore_2.py", line 16, in parse
    yield Request(url, callback=self.parse_following_urls, dont_filter=True)
  File "/usr/local/lib/python2.7/site-packages/scrapy/http/request/__init__.py", line 25, in __init__
    self._set_url(url)
  File "/usr/local/lib/python2.7/site-packages/scrapy/http/request/__init__.py", line 58, in _set_url
    raise ValueError('Missing scheme in request url: %s' % self._url)
ValueError: Missing scheme in request url: /book/?id=9780374281083

Maybe because I have to tell scrappy what is the base url? Should I add somewhere a urljoin?

EDIT_2 ---

Ok, the problem was with the urls. Adding

response.urljoin(

solved this issue.

Body:
In your code,

  yield Request(url, callback=self.parse_following_urls, dont_filter=True)

you used parse_following_urls with self.

But parse_following_urls is defined in parse function, so it isn't a method of YourCrawler.

That's why the error said
AttributeError: 'YourCrawler' object has no attribute 'parse_following_urls'

you should assign it like:

class YourCrawler(CrawlSpider):
    def parse_following_urls(self, response):
    ....

to make it method of the class.

edit
 for a additional question:

In your code s.xpath('///*[@id="results"]/ul/li/div[1]/h4/a[2]/@href') indicates the href attribute of the element a tag of the html page you want to scrap.
 However, it is only '/book/?id=9780374281083', not the full url.
 so, you should make it like : https://lacentral.com/book/?id=9780374281083
 to use it.


问:
What does this php code means
Hello I am new to PHP and I don't know exactaly what does this code means

```<code>$de = array('Ä'=>'ae','ä'=>'ae','Ü'=>'ue','ü'=>'ue', 'Ö'=>'oe', 'ö'=>'oe', 'ß'=>'ss');
 strtr($str, ${$de});
</code>```

The only thing that I need to know is what does ${$de} mean?

答:
That's a variable variable.

http://php.net/manual/en/language.variables.variable.php

Title: What does this php code means

Body:
Hello I am new to PHP and I don't know exactaly what does this code means

$de = array('Ä'=>'ae','ä'=>'ae','Ü'=>'ue','ü'=>'ue', 'Ö'=>'oe', 'ö'=>'oe', 'ß'=>'ss');
 strtr($str, ${$de});

The only thing that I need to know is what does ${$de} mean?