问:
Xamarin Android send Post data to WebApi
I have an Android app created with Xamarin in Visual Studio and I want to send a form data in json format to a Web Api created in C#. I tried a lot of methods from web an none worked.

Sometimes I get 500 Internal Server Error or sometimes I get null.

The last version I tried in WebApi is:

```<code>public HttpResponseMessage Post([FromBody]string value)
{
    if (value == null || value == "") Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read subject/tutor from body");
    var user = JsonConvert.DeserializeObject<UsersModel>(value);
    dynamic json = System.Web.Helpers.Json.Decode(value);
    string newName = json.Name;
    string newSurname = json.Surname;
    string newUsername = json.Username;
    string newPassword = json.Password;

    string insertNewUser = "INSERT INTO USERS(NAME,SURNAME,USERNAME,PASSWORD) VALUES (:name,:surname,:username,:password) ";
    using (OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["Licenta"].ConnectionString))
    {
        OracleCommand cmd = new OracleCommand(insertNewUser, conn);
        cmd.Parameters.Add("name", newName);
        cmd.Parameters.Add("surname", newSurname);
        cmd.Parameters.Add("username", newUsername);
        cmd.Parameters.Add("password", newPassword);
        cmd.ExecuteNonQuery();
    }

    return Request.CreateResponse(HttpStatusCode.OK);
}
catch(Exception ex)
{
    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
</code>```

The message I want to send to Web api is

```<code>{

    "name": "Ionescu",
    "surname": "Ralu",
    "username": "ralucuta",
    "password": "1235555",
    "usertype":1
}
</code>```

This is my Xamarin Android app code:

```<code>public async Task<UserAccount> SaveProduct(UserAccount product)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://blabla:80/test/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StringContent content = new StringContent(JsonConvert.SerializeObject(product), Encoding.UTF8, "application/json");
        // HTTP POST
        HttpResponseMessage response = await client.PostAsync("api/Users/", content);
        if (response.IsSuccessStatusCode)
        {
            string data = await response.Content.ReadAsStringAsync();
            product = JsonConvert.DeserializeObject<UserAccount>(data);
        }
    }
    return product;
}

public class UserAccount
{
    public string name { get; set; }
    public string surname { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public int usertype { get; set; }
}
</code>```

答:
Your rest api won't be called since you are passing UserAccount object and you are expecting string. change your web api signature like this

```<code>[HttpPost]
[Route("api/Users/save")]
public HttpResponseMessage MyMethod(UserAccount userAccount)
{
 //your api code
}
</code>```

And in your android code

```<code>public async Task<UserAccount> SaveProduct(UserAccount product)
{
    try {
        using (var client = new HttpClient ()) {
            client.BaseAddress = new Uri ("http://blabla:80/test/");
            client.DefaultRequestHeaders.Accept.Clear ();
            client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue ("application/json"));
            var uri = new Uri ("http://blabla:80/test/api/Users/save");
            string serializedObject = JsonConvert.SerializeObject (product);
            HttpContent contentPost = new StringContent (serializedObject, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync (uri, contentPost);
            if (response.IsSuccessStatusCode) {
                var data = await response.Content.ReadAsStringAsync ();
                UserAccount product = JsonConvert.DeserializeObject<UserAccount>(data);
                return product;
            }
        }
    }
    catch (Exception) {
        return null;
    }
}
</code>```

Body:
I have an Android app created with Xamarin in Visual Studio and I want to send a form data in json format to a Web Api created in C#. I tried a lot of methods from web an none worked.

Sometimes I get 500 Internal Server Error or sometimes I get null.

The last version I tried in WebApi is:

public HttpResponseMessage Post([FromBody]string value)
{
    if (value == null || value == "") Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read subject/tutor from body");
    var user = JsonConvert.DeserializeObject<UsersModel>(value);
    dynamic json = System.Web.Helpers.Json.Decode(value);
    string newName = json.Name;
    string newSurname = json.Surname;
    string newUsername = json.Username;
    string newPassword = json.Password;

    string insertNewUser = "INSERT INTO USERS(NAME,SURNAME,USERNAME,PASSWORD) VALUES (:name,:surname,:username,:password) ";
    using (OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["Licenta"].ConnectionString))
    {
        OracleCommand cmd = new OracleCommand(insertNewUser, conn);
        cmd.Parameters.Add("name", newName);
        cmd.Parameters.Add("surname", newSurname);
        cmd.Parameters.Add("username", newUsername);
        cmd.Parameters.Add("password", newPassword);
        cmd.ExecuteNonQuery();
    }

    return Request.CreateResponse(HttpStatusCode.OK);
}
catch(Exception ex)
{
    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}

The message I want to send to Web api is

{

    "name": "Ionescu",
    "surname": "Ralu",
    "username": "ralucuta",
    "password": "1235555",
    "usertype":1
}

This is my Xamarin Android app code:

public async Task<UserAccount> SaveProduct(UserAccount product)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://blabla:80/test/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StringContent content = new StringContent(JsonConvert.SerializeObject(product), Encoding.UTF8, "application/json");
        // HTTP POST
        HttpResponseMessage response = await client.PostAsync("api/Users/", content);
        if (response.IsSuccessStatusCode)
        {
            string data = await response.Content.ReadAsStringAsync();
            product = JsonConvert.DeserializeObject<UserAccount>(data);
        }
    }
    return product;
}

public class UserAccount
{
    public string name { get; set; }
    public string surname { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public int usertype { get; set; }
}

Body:
Your rest api won't be called since you are passing UserAccount object and you are expecting string. change your web api signature like this

[HttpPost]
[Route("api/Users/save")]
public HttpResponseMessage MyMethod(UserAccount userAccount)
{
 //your api code
}

And in your android code

public async Task<UserAccount> SaveProduct(UserAccount product)
{
    try {
        using (var client = new HttpClient ()) {
            client.BaseAddress = new Uri ("http://blabla:80/test/");
            client.DefaultRequestHeaders.Accept.Clear ();
            client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue ("application/json"));
            var uri = new Uri ("http://blabla:80/test/api/Users/save");
            string serializedObject = JsonConvert.SerializeObject (product);
            HttpContent contentPost = new StringContent (serializedObject, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync (uri, contentPost);
            if (response.IsSuccessStatusCode) {
                var data = await response.Content.ReadAsStringAsync ();
                UserAccount product = JsonConvert.DeserializeObject<UserAccount>(data);
                return product;
            }
        }
    }
    catch (Exception) {
        return null;
    }
}


来源: stackexchange

问:
C# how to enable button from another class
I have a form1, there's a "download" button, and a "next" button. By default, the "next" button is disabled. When I click "download" button, I will call a method from download.cs, different from form1.cs. After downloading, I want the "next" button to be enabled, so in download.cs, after receiving all files, I put

form1.btnNext.Enabled = true;

But it doesn't work. I also put this in form1.cs

public void enableButton(bool enabled)

{
     btnNext.Enabled = enabled;
  }

and in download.cs I put:

private form1 form1;
  ...

form1.enableButton(true);

but it doesn't work either. Could any1 show me where I'm wrong? thanks in advance.

答:
Your question needs some more information to be sure, but I'm guessing that the instance of form1 in your downloader class is not the same as the instance that's shown on your screen.

If your downloader should be able to call back to the form that started it up, the easiest way would be to pass a reference to that form along to the downloader class.

ContentLicense: CC BY-SA 2.5


问:
Google Analytics Sampling despite low sessions
I'm using Google Analytics Reporting API but I get sampled results even though the sessions in the specified date range are much less than the 500K limit. I have only ~4K sessions in a month.

I have also set "samplingLevel" as "LARGE".

Here's the Python query:

```<code>    response=analytics.reports().batchGet(
  body={
    "reportRequests":[
    {
      "viewId":myViewID,
      "dateRanges":[
        {
          "startDate":"2017-05-01",
          "endDate":"2017-05-30"
        }],
    "samplingLevel":"LARGE",
      "metrics":[
        {
          "expression":"ga:sessions"
        }],
      "dimensions": [
        {
          "name":"ga:browser"

        },
        {
          "name":"ga:city",
        }
        ]
      }]
  }
).execute()
</code>```

As you can see below the sample space is 4365 sessions, much lesser than the 500K limit

```<code>response.get('reports', [])[0].get('data',[]).get('samplesReadCounts',[])
Out[31]: [u'2051']

response.get('reports', [])[0].get('data',[]).get('samplingSpaceSizes',[])
Out[32]: [u'4365']
</code>```

Breaking the request into a smaller date range doesn't help either. I tried this using the GoogleAnalyticsR library in R with anti_sample=TRUE.

```<code>    > web_data <- google_analytics_4(view_id,
+                                 date_range = c("2017-05-01", "2017-05-30"),
+                                 dimensions = c("city","browser"),
+                                 metrics = c("hits"),
+                                samplingLevel="LARGE",
+                                 anti_sample = TRUE)
2017-06-04 11:54:51> anti_sample set to TRUE. Mitigating sampling via multiple API calls.
2017-06-04 11:54:51> Finding how much sampling in data request...
2017-06-04 11:54:52> Downloaded [10] rows from a total of [15].
2017-06-04 11:54:52> Data is sampled, based on 47% of sessions.
2017-06-04 11:54:52> Finding number of sessions for anti-sample calculations...
2017-06-04 11:54:53> Downloaded [30] rows from a total of [30].
2017-06-04 11:54:53> Calculated [3] batches are needed to download approx. [18] rows unsampled.
2017-06-04 11:54:53> Anti-sample call covering 14 days: 2017-05-01, 2017-05-14
2017-06-04 11:54:54> Downloaded [7] rows from a total of [7].
2017-06-04 11:54:54> Data is sampled, based on 53.2% of sessions.
2017-06-04 11:54:54> Anti-sampling failed
2017-06-04 11:54:54> Anti-sample call covering 9 days: 2017-05-15, 2017-05-23
2017-06-04 11:54:54> Downloaded [4] rows from a total of [4].
2017-06-04 11:54:54> Data is sampled, based on 55.7% of sessions.
2017-06-04 11:54:54> Anti-sampling failed
2017-06-04 11:54:54> Anti-sample call covering 7 days: 2017-05-24, 2017-05-30
2017-06-04 11:54:55> Downloaded [10] rows from a total of [10].
2017-06-04 11:54:55> Data is sampled, based on 52.3% of sessions.
2017-06-04 11:54:55> Anti-sampling failed
Joining, by = c("city", "browser")
Joining, by = c("city", "browser")
2017-06-04 11:54:55> Finished unsampled data request, total rows [13]
</code>```

When I check for the same data in a custom request, I see similar sampling

Any idea why I get sampled results even thought the session count is much less than the limit?

答:
The 500k applies to Default Reports

Edit:
500k sessions at the property level for the date range you are using for ad-hoc queries.

Default reports explained:

Analytics has a set of preconfigured, default reports listed in the left pane under Audience, Acquisition, Behavior, and Conversions.

It looks like you are working with an ad-hoc report with secondary dimensions, so the 500k threshold probably doesn't apply anymore and is likely much lower. There is some more information on this in the page you originally linked to here.

ContentLicense: CC BY-SA 3.0

Body:
I'm using Google Analytics Reporting API but I get sampled results even though the sessions in the specified date range are much less than the 500K limit. I have only ~4K sessions in a month.

I have also set "samplingLevel" as "LARGE".

Here's the Python query:

    response=analytics.reports().batchGet(
  body={
    "reportRequests":[
    {
      "viewId":myViewID,
      "dateRanges":[
        {
          "startDate":"2017-05-01",
          "endDate":"2017-05-30"
        }],
    "samplingLevel":"LARGE",
      "metrics":[
        {
          "expression":"ga:sessions"
        }],
      "dimensions": [
        {
          "name":"ga:browser"

        },
        {
          "name":"ga:city",
        }
        ]
      }]
  }
).execute()

As you can see below the sample space is 4365 sessions, much lesser than the 500K limit

response.get('reports', [])[0].get('data',[]).get('samplesReadCounts',[])
Out[31]: [u'2051']

response.get('reports', [])[0].get('data',[]).get('samplingSpaceSizes',[])
Out[32]: [u'4365']

Breaking the request into a smaller date range doesn't help either. I tried this using the GoogleAnalyticsR library in R with anti_sample=TRUE.

    > web_data <- google_analytics_4(view_id,
+                                 date_range = c("2017-05-01", "2017-05-30"),
+                                 dimensions = c("city","browser"),
+                                 metrics = c("hits"),
+                                samplingLevel="LARGE",
+                                 anti_sample = TRUE)
2017-06-04 11:54:51> anti_sample set to TRUE. Mitigating sampling via multiple API calls.
2017-06-04 11:54:51> Finding how much sampling in data request...
2017-06-04 11:54:52> Downloaded [10] rows from a total of [15].
2017-06-04 11:54:52> Data is sampled, based on 47% of sessions.
2017-06-04 11:54:52> Finding number of sessions for anti-sample calculations...
2017-06-04 11:54:53> Downloaded [30] rows from a total of [30].
2017-06-04 11:54:53> Calculated [3] batches are needed to download approx. [18] rows unsampled.
2017-06-04 11:54:53> Anti-sample call covering 14 days: 2017-05-01, 2017-05-14
2017-06-04 11:54:54> Downloaded [7] rows from a total of [7].
2017-06-04 11:54:54> Data is sampled, based on 53.2% of sessions.
2017-06-04 11:54:54> Anti-sampling failed
2017-06-04 11:54:54> Anti-sample call covering 9 days: 2017-05-15, 2017-05-23
2017-06-04 11:54:54> Downloaded [4] rows from a total of [4].
2017-06-04 11:54:54> Data is sampled, based on 55.7% of sessions.
2017-06-04 11:54:54> Anti-sampling failed
2017-06-04 11:54:54> Anti-sample call covering 7 days: 2017-05-24, 2017-05-30
2017-06-04 11:54:55> Downloaded [10] rows from a total of [10].
2017-06-04 11:54:55> Data is sampled, based on 52.3% of sessions.
2017-06-04 11:54:55> Anti-sampling failed
Joining, by = c("city", "browser")
Joining, by = c("city", "browser")
2017-06-04 11:54:55> Finished unsampled data request, total rows [13]

When I check for the same data in a custom request, I see similar sampling

Any idea why I get sampled results even thought the session count is much less than the limit?


问:
Parse JSON String into JSONArray (Android)
i'm trying to parse a json string to a JSONArray element, but when i try i get "cannot be converted to JSONArray"

My string is this way (but way longer):

```<code>{
"mylist": {
    "myinfo": {
        "user_id": 6225804,
        "user_name": "culo",
        "user_watching": 1092,
        "user_completed": 0,
        "user_onhold": 0,
        "user_dropped": 0,
        "user_plantowatch": 0,
        "user_days_spent_watching": 0
    },
    "anime": [{
        "series_animedb_id": 1,
        "series_title": "Cowboy Bebop",
        "series_synonyms": "; Cowboy Bebop",
        "series_type": 1,
        "series_episodes": 26,
        "series_status": 2,
        "series_start": "1998-04-03",
        "series_end": "1999-04-24",
        "series_image": "https:\/\/myanimelist.cdn-dena.com\/images\/anime\/4\/19644.webp",
        "my_id": 0,
        "my_watched_episodes": 0,
        "my_start_date": "0000-00-00",
        "my_finish_date": "0000-00-00",
        "my_score": 0,
        "my_status": 1,
        "my_rewatching": 0,
        "my_rewatching_ep": 0,
        "my_last_updated": 1493924579,
        "my_tags": ""
    }, {
        "series_animedb_id": 5,
        "series_title": "Cowboy Bebop: Tengoku no Tobira",
        "series_synonyms": "Cowboy Bebop: Knockin' on Heaven's Door; Cowboy Bebop: The Movie",
        "series_type": 3,
        "series_episodes": 1,
        "series_status": 2,
        "series_start": "2001-09-01",
        "series_end": "2001-09-01",
        "series_image": "https:\/\/myanimelist.cdn-dena.com\/images\/anime\/6\/14331.webp",
        "my_id": 0,
        "my_watched_episodes": 0,
        "my_start_date": "0000-00-00",
        "my_finish_date": "0000-00-00",
        "my_score": 0,
        "my_status": 1,
        "my_rewatching": 0,
        "my_rewatching_ep": 0,
        "my_last_updated": 1496668154,
        "my_tags": ""
    }, {
        "series_animedb_id": 6,
        "series_title": "Trigun",
        "series_synonyms": "; Trigun",
        "series_type": 1,
        "series_episodes": 26,
        "series_status": 2,
        "series_start": "1998-04-01",
        "series_end": "1998-09-30",
        "series_image": "https:\/\/myanimelist.cdn-dena.com\/images\/anime\/7\/20310.webp",
        "my_id": 0,
        "my_watched_episodes": 0,
        "my_start_date": "0000-00-00",
        "my_finish_date": "0000-00-00",
        "my_score": 0,
        "my_status": 1,
        "my_rewatching": 0,
        "my_rewatching_ep": 0,
        "my_last_updated": 1496668441,
        "my_tags": ""
    }, ETCETERA 1000 more like this one
</code>```

I don't really care about the "mylist" or "myinfo" part, just the "anime" part is needed. There are about 1000 items.

I've validated my JSON and it is valid.

This is my code:

```<code>JSONObject object = new JSONObject(replacedString);
JSONArray replacedResponse = new JSONArray(replacedString);
</code>```

and here is where my issue begins. I've also tried this:

```<code>JSONObject object = new JSONObject(replacedString);
JSONArray replacedResponse = object.getJSONArray("mylist");
</code>```

and
    JSONObject object = new JSONObject(replacedString);
    JSONArray replacedResponse = object.getJSONArray("anime");

with similar results

What i'm I not seeing here? thanks in advance!

答:
Please follow this code.</p>

```<code>    String stringObj = "[YOUR JSON]";

    // first Convert string into JsonObject
    try {
        JSONObject jsonObject = new JSONObject(stringObj);

        // Inside the above object you have "mylist" key and the respective JsonObject so
        JSONObject myListObject = jsonObject.optJSONObject("mylist");

        // Insdide mylist you have myinfo Json and anim JsonArray
        if(myListObject == null) {
            return;
        }

        JSONObject myinfoObject = myListObject.optJSONObject("myinfo");
        JSONArray animeJsonArray = myListObject.optJSONArray("anime");

        // check null for myinfoObject and animeJsonArray and do the operation

    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

Body:
i'm trying to parse a json string to a JSONArray element, but when i try i get "cannot be converted to JSONArray"

My string is this way (but way longer):

{
"mylist": {
    "myinfo": {
        "user_id": 6225804,
        "user_name": "culo",
        "user_watching": 1092,
        "user_completed": 0,
        "user_onhold": 0,
        "user_dropped": 0,
        "user_plantowatch": 0,
        "user_days_spent_watching": 0
    },
    "anime": [{
        "series_animedb_id": 1,
        "series_title": "Cowboy Bebop",
        "series_synonyms": "; Cowboy Bebop",
        "series_type": 1,
        "series_episodes": 26,
        "series_status": 2,
        "series_start": "1998-04-03",
        "series_end": "1999-04-24",
        "series_image": "https:\/\/myanimelist.cdn-dena.com\/images\/anime\/4\/19644.webp",
        "my_id": 0,
        "my_watched_episodes": 0,
        "my_start_date": "0000-00-00",
        "my_finish_date": "0000-00-00",
        "my_score": 0,
        "my_status": 1,
        "my_rewatching": 0,
        "my_rewatching_ep": 0,
        "my_last_updated": 1493924579,
        "my_tags": ""
    }, {
        "series_animedb_id": 5,
        "series_title": "Cowboy Bebop: Tengoku no Tobira",
        "series_synonyms": "Cowboy Bebop: Knockin' on Heaven's Door; Cowboy Bebop: The Movie",
        "series_type": 3,
        "series_episodes": 1,
        "series_status": 2,
        "series_start": "2001-09-01",
        "series_end": "2001-09-01",
        "series_image": "https:\/\/myanimelist.cdn-dena.com\/images\/anime\/6\/14331.webp",
        "my_id": 0,
        "my_watched_episodes": 0,
        "my_start_date": "0000-00-00",
        "my_finish_date": "0000-00-00",
        "my_score": 0,
        "my_status": 1,
        "my_rewatching": 0,
        "my_rewatching_ep": 0,
        "my_last_updated": 1496668154,
        "my_tags": ""
    }, {
        "series_animedb_id": 6,
        "series_title": "Trigun",
        "series_synonyms": "; Trigun",
        "series_type": 1,
        "series_episodes": 26,
        "series_status": 2,
        "series_start": "1998-04-01",
        "series_end": "1998-09-30",
        "series_image": "https:\/\/myanimelist.cdn-dena.com\/images\/anime\/7\/20310.webp",
        "my_id": 0,
        "my_watched_episodes": 0,
        "my_start_date": "0000-00-00",
        "my_finish_date": "0000-00-00",
        "my_score": 0,
        "my_status": 1,
        "my_rewatching": 0,
        "my_rewatching_ep": 0,
        "my_last_updated": 1496668441,
        "my_tags": ""
    }, ETCETERA 1000 more like this one

I don't really care about the "mylist" or "myinfo" part, just the "anime" part is needed. There are about 1000 items.

I've validated my JSON and it is valid.

This is my code:

JSONObject object = new JSONObject(replacedString);
JSONArray replacedResponse = new JSONArray(replacedString);

and here is where my issue begins. I've also tried this:

JSONObject object = new JSONObject(replacedString);
JSONArray replacedResponse = object.getJSONArray("mylist");

and
    JSONObject object = new JSONObject(replacedString);
    JSONArray replacedResponse = object.getJSONArray("anime");

with similar results

What i'm I not seeing here? thanks in advance!

Body:
Please follow this code.

    String stringObj = "[YOUR JSON]";

    // first Convert string into JsonObject
    try {
        JSONObject jsonObject = new JSONObject(stringObj);

        // Inside the above object you have "mylist" key and the respective JsonObject so
        JSONObject myListObject = jsonObject.optJSONObject("mylist");

        // Insdide mylist you have myinfo Json and anim JsonArray
        if(myListObject == null) {
            return;
        }

        JSONObject myinfoObject = myListObject.optJSONObject("myinfo");
        JSONArray animeJsonArray = myListObject.optJSONArray("anime");

        // check null for myinfoObject and animeJsonArray and do the operation

    } catch (JSONException e) {
        e.printStackTrace();
    }


问:
How to reshape a dataframe and paste multiple values in a single cell of a sparse matrix in R?
I have a dataframe like mentioned below. I want to create a sparse matrix whose row names and column names are unique station names and in the cells of sparse matrix I want all the train numbers for that particular station name. Here is the link of whole data

```<code>Train.No. train.Name       isl.no. station.code     Station.Name
'00851'   BNC SUVIDHA SPL   1      BBS              BHUBANESWAR
'00851'   BNC SUVIDHA SPL   2      BAM              BRAHMAPUR
'00851'   BNC SUVIDHA SPL   3      VSKP             VISAKHAPATNAM
'00851'   BNC SUVIDHA SPL   4      BZA              VIJAYAWADA JN
'00851'   BNC SUVIDHA SPL   5      RU               RENIGUNTA JN
'00851'   BNC SUVIDHA SPL   6      JTJ              JOLARPETTAI
'00851'   BNC SUVIDHA SPL   7      BNC              BANGALORE CANT
'00852'   BNC BBS SUVIDHA   1      BNC              BANGALORE CANT
'00852'   BNC BBS SUVIDHA   2      JTJ              JOLARPETTAI
</code>```

I am getting the desired output using the below code but this process is too much time taking as this is not a sparse matrix with dimension 4337*4337.

```<code>r1 <- rail

mat_n <- matrix(data = NA, nrow = length(unique(r1$Station.Name)),
ncol = length(unique(r1$Station.Name)))
rownames(mat_n) <- unique(r1$Station.Name)
colnames(mat_n) <- unique(r1$Station.Name)

a1 <- unique(r1$Train.No.)

for(k in 1:length(a1)){
fd1 <- grep(a1[k], r1$Train.No.)
for(i in 1:nrow(mat_n)){
sta1 <- rownames(mat_n)[i]
for(j in 1:ncol(mat_n)){
  if(i != j){
    sta2 <- colnames(mat_n)[j]
    if(length(grep(sta1, r1$Station.Name[fd1[1]]))>0 & length(grep(sta2, r1$Station.Name[fd1[1]:fd1[length(fd1)]]))>0){
      mat_n[i,j] <-paste(mat_n[i,j], a1[k])}

  }
}
}
}
</code>```

What is the alternate of the same using packages like reshape2, dplyr, tidyr etc? I searched for the same but got nothing which give me the desired output. This is the form of desired output I want.

答:
Starting with your initial dataframe r1, this dplyr/tidyr solution may get you the results you need

```<code>library(dplyr)
library(tidyr)

r1 <- r1 %>%
  arrange(Train.No., isl.no.) %>%
  group_by(Train.No.) %>%
  mutate(Start.Station = first(Station.Name)) %>%
  ungroup() %>%
  mutate(rownum = row_number()) %>%
  spread(Station.Name, Train.No.) %>%
  select(-train.Name, -isl.no., -station.code, -rownum) %>%
  group_by(Start.Station) %>%
  summarise_each(funs(paste(na.omit(.), collapse = " ")))

row.names(r1) <- r1$Start.Station
r1$Start.Station <- NULL
</code>```

Body:
I have a dataframe like mentioned below. I want to create a sparse matrix whose row names and column names are unique station names and in the cells of sparse matrix I want all the train numbers for that particular station name. Here is the link of whole data

Train.No. train.Name       isl.no. station.code     Station.Name
'00851'   BNC SUVIDHA SPL   1      BBS              BHUBANESWAR
'00851'   BNC SUVIDHA SPL   2      BAM              BRAHMAPUR
'00851'   BNC SUVIDHA SPL   3      VSKP             VISAKHAPATNAM
'00851'   BNC SUVIDHA SPL   4      BZA              VIJAYAWADA JN
'00851'   BNC SUVIDHA SPL   5      RU               RENIGUNTA JN
'00851'   BNC SUVIDHA SPL   6      JTJ              JOLARPETTAI
'00851'   BNC SUVIDHA SPL   7      BNC              BANGALORE CANT
'00852'   BNC BBS SUVIDHA   1      BNC              BANGALORE CANT
'00852'   BNC BBS SUVIDHA   2      JTJ              JOLARPETTAI

I am getting the desired output using the below code but this process is too much time taking as this is not a sparse matrix with dimension 4337*4337.

r1 <- rail

mat_n <- matrix(data = NA, nrow = length(unique(r1$Station.Name)),
ncol = length(unique(r1$Station.Name)))
rownames(mat_n) <- unique(r1$Station.Name)
colnames(mat_n) <- unique(r1$Station.Name)

a1 <- unique(r1$Train.No.)

for(k in 1:length(a1)){
fd1 <- grep(a1[k], r1$Train.No.)
for(i in 1:nrow(mat_n)){
sta1 <- rownames(mat_n)[i]
for(j in 1:ncol(mat_n)){
  if(i != j){
    sta2 <- colnames(mat_n)[j]
    if(length(grep(sta1, r1$Station.Name[fd1[1]]))>0 & length(grep(sta2, r1$Station.Name[fd1[1]:fd1[length(fd1)]]))>0){
      mat_n[i,j] <-paste(mat_n[i,j], a1[k])}

  }
}
}
}

What is the alternate of the same using packages like reshape2, dplyr, tidyr etc? I searched for the same but got nothing which give me the desired output. This is the form of desired output I want.

Body:
Starting with your initial dataframe r1, this dplyr/tidyr solution may get you the results you need

library(dplyr)
library(tidyr)

r1 <- r1 %>%
  arrange(Train.No., isl.no.) %>%
  group_by(Train.No.) %>%
  mutate(Start.Station = first(Station.Name)) %>%
  ungroup() %>%
  mutate(rownum = row_number()) %>%
  spread(Station.Name, Train.No.) %>%
  select(-train.Name, -isl.no., -station.code, -rownum) %>%
  group_by(Start.Station) %>%
  summarise_each(funs(paste(na.omit(.), collapse = " ")))

row.names(r1) <- r1$Start.Station
r1$Start.Station <- NULL


问:
Create a MediaWiki template to set font color in pages
I just installed Mediawiki and realized that it is very complicated to configure it for newbie.

As one of my first entry I wanted to change font color with:

```<code>{{ font color | green | green text }}
</code>```

To do that I imported Template:Font color from Wikipedia Special:Export page, but still as the result I don't get coloured text, but:

```<code>{{ safesubst:#if:

| {{ safesubst:#if:
     | {{ safesubst:#ifeq:  | yes
     | [[ {{ safesubst:#if:1|  }}|{{ safesubst:#if:1|  }}]]
     | [[|{{ safesubst:#if:1|  }}]]
     }}
   | {{ safesubst:#if:1|  }}
   }}
| {{ safesubst:#if:
     | {{ safesubst:#ifeq:  | yes
     | [[ {{ safesubst:#if:1|  green text  }} |{{ safesubst:#if:1|  green text  }}]]
     | [[ {{ safesubst:#if:1|  }} |{{ safesubst:#if:1|  green text  }}]]
   }}
 | {{ safesubst:#if:1|  green text  }}
 }}

}}
</code>```

Could you please help me?

答:
MediaWiki sucks for newbies who just want to throw a wiki together. It first needs plenty of extra work to get decent, especially in regard to templates.

Maybe you left out an extension like ParserFunctions or Scribunto? Templates use other templates, did you tick the box "Include templates"?

Here's a helpful blog post on how to import Wikipedia Templates into your own MediaWiki.

Body:
I just installed Mediawiki and realized that it is very complicated to configure it for newbie.

As one of my first entry I wanted to change font color with:

{{ font color | green | green text }}

To do that I imported Template:Font color from Wikipedia Special:Export page, but still as the result I don't get coloured text, but:

{{ safesubst:#if:

| {{ safesubst:#if:
     | {{ safesubst:#ifeq:  | yes
     | [[ {{ safesubst:#if:1|  }}|{{ safesubst:#if:1|  }}]]
     | [[|{{ safesubst:#if:1|  }}]]
     }}
   | {{ safesubst:#if:1|  }}
   }}
| {{ safesubst:#if:
     | {{ safesubst:#ifeq:  | yes
     | [[ {{ safesubst:#if:1|  green text  }} |{{ safesubst:#if:1|  green text  }}]]
     | [[ {{ safesubst:#if:1|  }} |{{ safesubst:#if:1|  green text  }}]]
   }}
 | {{ safesubst:#if:1|  green text  }}
 }}

}}

Could you please help me?


问:
Find dup records with different extensions in SQL Server
I have a subscriptions table. Sample records:

```<code>  SUBS_ID    |   SUBS Name
     1       |   SC FORM 124
     2       |   SC FORM 124-R
</code>```

I need to find both the records, as the subscription name is exactly the same but just with an extension-R.

答:
Based on your latest criteria:

So, in the above example when I query the table I should get all 3
  records ...the first one being the base record and the remaining 2
  being the extensions – SQL User 17 mins ago

```<code>SELECT distinct
    0 as Subs_ID
    , CASE WHEN SUBS_Name like '%-%' THEN left(SUBS_Name,charindex('-',SUBS_Name)-1) ELSE SUBS_Name END AS SUB_NAME_MAIN
    , '' as Extension

FROM
    subs

UNION

SELECT
    Subs_ID
    , CASE WHEN SUBS_Name like '%-%' THEN left(SUBS_Name,charindex('-',SUBS_Name)-1) ELSE SUBS_Name END AS SUB_NAME_MAIN
    , CASE WHEN SUBS_Name like '%-%' THEN RIGHT(SUBS_Name, LEN(SUBS_Name) - charindex('-',SUBS_Name)+1) ELSE '' END AS Extension

FROM
    subs
</code>```

will produce the following result.  A 'Master' row that is given an arbitray ID number of '0' and each row of that master's family and its extension.

```<code>Subs_ID     SUB_NAME_MAIN        Extension
----------- -------------------- --------------------
0           SC FORM 124
1           SC FORM 124
2           SC FORM 124          -R
</code>```

Body:
I have a subscriptions table. Sample records:

  SUBS_ID    |   SUBS Name
     1       |   SC FORM 124
     2       |   SC FORM 124-R

I need to find both the records, as the subscription name is exactly the same but just with an extension-R.

Body:
Based on your latest criteria:

So, in the above example when I query the table I should get all 3
  records ...the first one being the base record and the remaining 2
  being the extensions – SQL User 17 mins ago

SELECT distinct
    0 as Subs_ID
    , CASE WHEN SUBS_Name like '%-%' THEN left(SUBS_Name,charindex('-',SUBS_Name)-1) ELSE SUBS_Name END AS SUB_NAME_MAIN
    , '' as Extension

FROM
    subs

UNION

SELECT
    Subs_ID
    , CASE WHEN SUBS_Name like '%-%' THEN left(SUBS_Name,charindex('-',SUBS_Name)-1) ELSE SUBS_Name END AS SUB_NAME_MAIN
    , CASE WHEN SUBS_Name like '%-%' THEN RIGHT(SUBS_Name, LEN(SUBS_Name) - charindex('-',SUBS_Name)+1) ELSE '' END AS Extension

FROM
    subs

will produce the following result.  A 'Master' row that is given an arbitray ID number of '0' and each row of that master's family and its extension.

Subs_ID     SUB_NAME_MAIN        Extension
----------- -------------------- --------------------
0           SC FORM 124
1           SC FORM 124
2           SC FORM 124          -R


问:
Sending multiple values from servlet to jsp
I have a servlet code where I check for username and password in a helper class and after checking it comes back to servlet and lists users. The username along with the list of users must be displayed in the jsp. How to send both the values? Here is the code which I have tried. It displays nothing
String outp=t.Welcome(name, pwd);</p>

```<code>String Users=t.List_Of_Users();
String User[]=Users.trim().split(" ");
request.setAttribute("name", User);
response.sendRedirect("Welcome_User.jsp?Users="+User+"&outp="+outp);
</code>```

答:
You can set as many attributes as you want , also optimization should be taken care of. ,

```<code>request.setAttribute("key1", Object1);
request.setAttribute("key2", Object2);
request.setAttribute("key3", Object3);
.
.
.
request.setAttribute("keyn", Objectn);
</code>```

then

```<code>String destination = "/WEB-INF/pages/result.jsp";
RequestDispatcher rd = getServletContext().getRequestDispatcher(destination);
rd.forward(request, response);
</code>```

Body:
I have a servlet code where I check for username and password in a helper class and after checking it comes back to servlet and lists users. The username along with the list of users must be displayed in the jsp. How to send both the values? Here is the code which I have tried. It displays nothing
String outp=t.Welcome(name, pwd);

String Users=t.List_Of_Users();
String User[]=Users.trim().split(" ");
request.setAttribute("name", User);
response.sendRedirect("Welcome_User.jsp?Users="+User+"&outp="+outp);

Body:
You can set as many attributes as you want , also optimization should be taken care of. ,

request.setAttribute("key1", Object1);
request.setAttribute("key2", Object2);
request.setAttribute("key3", Object3);
.
.
.
request.setAttribute("keyn", Objectn);

then

String destination = "/WEB-INF/pages/result.jsp";
RequestDispatcher rd = getServletContext().getRequestDispatcher(destination);
rd.forward(request, response);


问:
Is it safe to send credit card details securely over http POST using swift?
The API that I'm using requires me to send Credit Card Details to complete payment through a HTTP POST request (through swift). Is this safe by any means? And moreover, how do I securely store credit card information for repeated payments?

The credit card holder's name, credit card number, cvc, and date of expiry are all sent over a POST request. Then, the API returns whether the payment was successful, and the last four digits of the credit card number.

Simply put, I'm not entirely familiar with payment security, and would like to know if this is safe, and moreover how to save payment information securely using swift, even if that's possible. I don't think I can use stripe for this process, but I would love to know if that's possible as well.

EDIT:
I have confirmed that the API I'm using does in fact employ an HTTPS connection, and not simply a HTTP server. At this point, I know not to save credit card information locally and that I should retrieve it from a third party service before handling it. Thanks All!

答:
Using Swift or any other programming language and sending sensitive information over HTTP is not secure as mentioned in the comments.

Instead you should use an HTTPS connection.


问:
Not all data in a column is being copied to another csv file
So I have two csv files. One is in the following format:

last name, first name, Number
```

<p>The other is in this format:</p>

```number, quiz
```

<p>I want to create a new output file that takes these two csv files and gives me a file in the following format:</p>

```last name, first name, number, quiz.
```

<p>I have tried the follwoing code and it works, but only for the first person listed in the first two input files. I am not sure what I am doing wrong. Also, I do not want to assume that the two input files follow the same order.</p>

```import sys, re
import numpy as np
import smtplib
from random import randint
import csv
import math

col = sys.argv[1]
source = sys.argv[2]
target = sys.argv[3]
newtarg = sys.argv[4]

input_source = csv.DictReader(open(source))
input_target = csv.DictReader(open(target))
data = {}
t = ()

for row in input_target:
    t = row['First Name'], row['number']
    for rows in input_source:
        if rows['number'] == row['number']:
            t = t + (rows[col],)
            name = row['Last Name']
            data[name] = [t]
            rows.next()
        row.next()

with open(newtarg,'w') as out:
    csv_out=csv.writer(out)
    for key, val in data.items():
        csv_out.writerow([key] + list(val))
```

答:
I think the following will work. Note: I've taken out all the stuff in the code in your question that's not being used (as you should have done before posting it). I've also hardcoded the input values for testing.

```<code>import csv

source = 'source1.csv'
target = 'target1.csv'
newtarg = 'new_output.csv'

targets = {}
with open(target) as file:
    for row in csv.DictReader(file):
        targets[row['number']] = row['quiz']

with open(source) as src, open(newtarg, 'w') as out:
    reader = csv.DictReader(src)
    writer = csv.writer(out)
    writer.writerow(reader.fieldnames + ['quiz'])  # create a header row (optional)
    for row in reader:
        row.update({'quiz': targets.get(row['Number'], 'no match')})
        writer.writerow(row.values())
</code>```

Body:
So I have two csv files. One is in the following format:

last name, first name, Number

The other is in this format:

number, quiz

I want to create a new output file that takes these two csv files and gives me a file in the following format:

last name, first name, number, quiz.

I have tried the follwoing code and it works, but only for the first person listed in the first two input files. I am not sure what I am doing wrong. Also, I do not want to assume that the two input files follow the same order.

import sys, re
import numpy as np
import smtplib
from random import randint
import csv
import math

col = sys.argv[1]
source = sys.argv[2]
target = sys.argv[3]
newtarg = sys.argv[4]

input_source = csv.DictReader(open(source))
input_target = csv.DictReader(open(target))
data = {}
t = ()

for row in input_target:
    t = row['First Name'], row['number']
    for rows in input_source:
        if rows['number'] == row['number']:
            t = t + (rows[col],)
            name = row['Last Name']
            data[name] = [t]
            rows.next()
        row.next()

with open(newtarg,'w') as out:
    csv_out=csv.writer(out)
    for key, val in data.items():
        csv_out.writerow([key] + list(val))

Body:
I think the following will work. Note: I've taken out all the stuff in the code in your question that's not being used (as you should have done before posting it). I've also hardcoded the input values for testing.

import csv

source = 'source1.csv'
target = 'target1.csv'
newtarg = 'new_output.csv'

targets = {}
with open(target) as file:
    for row in csv.DictReader(file):
        targets[row['number']] = row['quiz']

with open(source) as src, open(newtarg, 'w') as out:
    reader = csv.DictReader(src)
    writer = csv.writer(out)
    writer.writerow(reader.fieldnames + ['quiz'])  # create a header row (optional)
    for row in reader:
        row.update({'quiz': targets.get(row['Number'], 'no match')})
        writer.writerow(row.values())


问:
Gitlab CI - SSH Permission denied (publickey,password)
I've been trying to setup CD for my project. My Gitlab CI runner and my project will be on same server. I've followed https://docs.gitlab.com/ee/ci/examples/deployment/composer-npm-deploy.html but I keep getting SSH Permission denied (publickey,password). error. All my variables, private key and other variables set correctly in project settings.

I've created my ssh key with ssh-keygen -t rsa -C "my.email@example.com" -b 4096 command with no passphrase and set my PRODUCTION_PRIVATE_KEY variable with content of ~/.ssh/id_rsa file.

This is my gitlab-ci.yml:

```<code>stages:
  - deploy

deploy_production:
  stage: deploy
  image: tetraweb/php
  before_script:
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - eval $(ssh-agent -s)
    - ssh-add <(echo "$PRODUCTION_PRIVATE_KEY")
    - mkdir -p ~/.ssh
    - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
    - apt-get install rsync
  script:
    - ssh $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER
    - hostname
  only:
    - master
</code>```

And this is output from Gitlab CI runner:

```<code>Running with gitlab-ci-multi-runner 9.2.0 (adfc387)
  on ci-test (1eada8d0)
Using Docker executor with image tetraweb/php ...
Using docker image sha256:17692e06e6d33d8a421441bbe9adfda5b65c94831c6e64d7e69197e0b51833f8 for predefined container...
Pulling docker image tetraweb/php ...
Using docker image tetraweb/php ID=sha256:474f639dc349f36716fb98b193e6bae771f048cecc9320a270123ac2966b98c6 for build container...
Running on runner-1eada8d0-project-3287351-concurrent-0 via lamp-512mb-ams2-01...
Fetching changes...
HEAD is now at dfdb499 Update .gitlab-ci.yml
Checking out dfdb4992 as master...
Skipping Git submodules setup
$ which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )
/usr/bin/ssh-agent
$ eval $(ssh-agent -s)
Agent pid 12
$ ssh-add <(echo "$PRODUCTION_PRIVATE_KEY")
Identity added: /dev/fd/63 (rsa w/o comment)
$ mkdir -p ~/.ssh
$ echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
$ apt-get install rsync
Reading package lists...
Building dependency tree...
Reading state information...
rsync is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
$ ssh $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER
Pseudo-terminal will not be allocated because stdin is not a terminal.
Warning: Permanently added '{MY_SERVER_IP}' (ECDSA) to the list of known hosts.
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,password).
ERROR: Job failed: exit code 1
</code>```

Thanks in advance.

答: You need to add the public key to the server so it would be recognized as an authentication key. This is, paste the content of the public key corresponding to the private key you are using to the ~/.ssh/authorized_keys on the $PRODUCTION_SERVER.

Body:
I've been trying to setup CD for my project. My Gitlab CI runner and my project will be on same server. I've followed https://docs.gitlab.com/ee/ci/examples/deployment/composer-npm-deploy.html but I keep getting SSH Permission denied (publickey,password). error. All my variables, private key and other variables set correctly in project settings.

I've created my ssh key with ssh-keygen -t rsa -C "my.email@example.com" -b 4096 command with no passphrase and set my PRODUCTION_PRIVATE_KEY variable with content of ~/.ssh/id_rsa file.

This is my gitlab-ci.yml:

stages:
  - deploy

deploy_production:
  stage: deploy
  image: tetraweb/php
  before_script:
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - eval $(ssh-agent -s)
    - ssh-add <(echo "$PRODUCTION_PRIVATE_KEY")
    - mkdir -p ~/.ssh
    - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
    - apt-get install rsync
  script:
    - ssh $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER
    - hostname
  only:
    - master

And this is output from Gitlab CI runner:

Running with gitlab-ci-multi-runner 9.2.0 (adfc387)
  on ci-test (1eada8d0)
Using Docker executor with image tetraweb/php ...
Using docker image sha256:17692e06e6d33d8a421441bbe9adfda5b65c94831c6e64d7e69197e0b51833f8 for predefined container...
Pulling docker image tetraweb/php ...
Using docker image tetraweb/php ID=sha256:474f639dc349f36716fb98b193e6bae771f048cecc9320a270123ac2966b98c6 for build container...
Running on runner-1eada8d0-project-3287351-concurrent-0 via lamp-512mb-ams2-01...
Fetching changes...
HEAD is now at dfdb499 Update .gitlab-ci.yml
Checking out dfdb4992 as master...
Skipping Git submodules setup
$ which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )
/usr/bin/ssh-agent
$ eval $(ssh-agent -s)
Agent pid 12
$ ssh-add <(echo "$PRODUCTION_PRIVATE_KEY")
Identity added: /dev/fd/63 (rsa w/o comment)
$ mkdir -p ~/.ssh
$ echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
$ apt-get install rsync
Reading package lists...
Building dependency tree...
Reading state information...
rsync is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
$ ssh $PRODUCTION_SERVER_USER@$PRODUCTION_SERVER
Pseudo-terminal will not be allocated because stdin is not a terminal.
Warning: Permanently added '{MY_SERVER_IP}' (ECDSA) to the list of known hosts.
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,password).
ERROR: Job failed: exit code 1

Thanks in advance.


问:
swift - cellForRowAt never called
I have a problem with creating a table view in UITableViewController. The number of rows returns non-zero number and height is set in storyboard. But the cellForRowAtis never called.

Here is the code:

ViewController:

```<code>import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath) as! ArticleCell

    cell.title.text = "THIS IS A TESTE"
    cell.desc.text = "THIS IS A TESTE"

    return cell
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}
</code>```

Is anything wrong with my code?

答:
in your viewDidload make

```<code>yourtableView.delegate = self
yourtableView.dataSource = self
</code>```

Don't forget to pull a reference outlet of your tableView.

Title: swift - cellForRowAt never called

Body:
I have a problem with creating a table view in UITableViewController. The number of rows returns non-zero number and height is set in storyboard. But the cellForRowAtis never called.

Here is the code:

ViewController:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath) as! ArticleCell

    cell.title.text = "THIS IS A TESTE"
    cell.desc.text = "THIS IS A TESTE"

    return cell
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

Is anything wrong with my code?

Body:
in your viewDidload make

yourtableView.delegate = self
yourtableView.dataSource = self

Don't forget to pull a reference outlet of your tableView.


问:
Chromecast MediaInfo.Builder can't play shoutcast
I have one problem regarding MediaInfo.Builder of Google Cast. I used following code:

```<code>MediaInfo mediaInfo = new MediaInfo.Builder("http://shoutcast2.index.uz.zgora.pl:8000")
                .setStreamType(MediaInfo.STREAM_TYPE_LIVE)
                .setContentType("audio/mpeg")
                .build();
</code>```

But Cast player is not working at all. The reason is, that URL leads to SHOUTCAST. Apparently, the problem is in content type. Could somebody advise which contentType to use for shoutcast streams, or at least provide some workaround for this?

Thank you.

答:
Brad's solution worked for me. Just added a slash and a semicolon after the port. I also changed the content type from audio/mpeg to audio/mp3. My working code looks like this.

```<code>MediaInfo mediaInfo = new MediaInfo.Builder("http://shoutcast2.index.uz.zgora.pl:8000/;")
                .setStreamType(MediaInfo.STREAM_TYPE_LIVE)
                .setContentType("audio/mp3")
                .build();
</code>```

Body:
I have one problem regarding MediaInfo.Builder of Google Cast. I used following code:

MediaInfo mediaInfo = new MediaInfo.Builder("http://shoutcast2.index.uz.zgora.pl:8000")
                .setStreamType(MediaInfo.STREAM_TYPE_LIVE)
                .setContentType("audio/mpeg")
                .build();

But Cast player is not working at all. The reason is, that URL leads to SHOUTCAST. Apparently, the problem is in content type. Could somebody advise which contentType to use for shoutcast streams, or at least provide some workaround for this?

Thank you.

Body:
Brad's solution worked for me. Just added a slash and a semicolon after the port. I also changed the content type from audio/mpeg to audio/mp3. My working code looks like this.

MediaInfo mediaInfo = new MediaInfo.Builder("http://shoutcast2.index.uz.zgora.pl:8000/;")
                .setStreamType(MediaInfo.STREAM_TYPE_LIVE)
                .setContentType("audio/mp3")
                .build();


问:
unable to fetch data from ejs to controller and client side JS
I am a newbie in node and express. I am working on an app that has a login module. I am able to register a user but am facing some issues while trying to log in a user.

Please find my code below and suggest:

Logincontroller.js

```<code>app.post('/testAction',urlencodedParser,function(req,res){

    var usrnm = req.body.username;
    console.log(" usrnm ::: " + usrnm);
    var passwd = req.body.password;
    console.log(" passwd ::: " + passwd);
    Users.findOne({username:"tstusr1"},function(err,data){ // Users is my schema name
        if(err) throw err;
        console.log(" back from ajax with data in login controller :::; " + data);
        res.json(data);
    });
    console.log("inside index2 post");
});
</code>```

my Login-user.js is

```<code>$(document).ready(function(){

      var items = $('form');
      var user ={username: $('[name=username]', items).val()};
      console.log('user  ' + JSON.stringify(user));

  $('form').on('submit', function(){
      console.log("inside submit login");
      $.ajax({
          type: 'POST',
          url: '/testAction',
          data: user,
          success: function(data, textStatus, jqXHR){
            var resp = JSON.parse(JSON.stringify(jqXHR));
            if(resp["status"]==200){
                console.log("status == 200");
                window.location.href = '/';
            }
              return data;
          },
          error:function (jqXHR, textStatus, errorThrown) {

              console.log('error  ' + JSON.stringify(user));
              console.log("resp1 :::::: " + JSON.stringify(jqXHR));
              var resp = JSON.parse(JSON.stringify(jqXHR));
              console.log("resp :::::: " + resp);
          }
        });
         return false;
  });
});
</code>```

And my ejs file is

```<code><form action="/testAction">
    <label for="username"> Username </label>
    <input type="text" for="username" name="username" />
    <label for="password"> Password </label>
    <input type="password" for="password" name="password" />
    <button type="submit">Log In</button>
</form>
</code>```

My issue is I am not able to fetch the values of username and password to the client side js as well as backend server side js.

Please assist

答:
From the code posted, you don't seem to be updating user at all. Neither are you actually including the password in the request's data parameter.

```<code>$('form').on('submit', function(e) {
  e.preventDefault();
  $.post('/testAction', {
    username: $('[name=username]', $(this)).val(),
    password: ...
  });
});
</code>```

If you want a simpler way to pass all the fields from your form:

```<code>$('form').on('submit', function(e) {
  e.preventDefault();
  $.post('/testAction', (
    $(this).serializeArray().reduce((o, i) => {
      o[i.name] = i.value;
      return o;
    }, {})
  ));
});
</code>```

See How can I get form data with JavaScript/jQuery?

Body:
I am a newbie in node and express. I am working on an app that has a login module. I am able to register a user but am facing some issues while trying to log in a user.

Please find my code below and suggest:

Logincontroller.js

app.post('/testAction',urlencodedParser,function(req,res){

    var usrnm = req.body.username;
    console.log(" usrnm ::: " + usrnm);
    var passwd = req.body.password;
    console.log(" passwd ::: " + passwd);
    Users.findOne({username:"tstusr1"},function(err,data){ // Users is my schema name
        if(err) throw err;
        console.log(" back from ajax with data in login controller :::; " + data);
        res.json(data);
    });
    console.log("inside index2 post");
});

my Login-user.js is

$(document).ready(function(){

      var items = $('form');
      var user ={username: $('[name=username]', items).val()};
      console.log('user  ' + JSON.stringify(user));

  $('form').on('submit', function(){
      console.log("inside submit login");
      $.ajax({
          type: 'POST',
          url: '/testAction',
          data: user,
          success: function(data, textStatus, jqXHR){
            var resp = JSON.parse(JSON.stringify(jqXHR));
            if(resp["status"]==200){
                console.log("status == 200");
                window.location.href = '/';
            }
              return data;
          },
          error:function (jqXHR, textStatus, errorThrown) {

              console.log('error  ' + JSON.stringify(user));
              console.log("resp1 :::::: " + JSON.stringify(jqXHR));
              var resp = JSON.parse(JSON.stringify(jqXHR));
              console.log("resp :::::: " + resp);
          }
        });
         return false;
  });
});

And my ejs file is

<form action="/testAction">
     Username
    <input type="text" for="username" name="username" />
     Password
    <input type="password" for="password" name="password" />
    <button type="submit">Log In</button>
</form>

My issue is I am not able to fetch the values of username and password to the client side js as well as backend server side js.

Please assist

Body:
From the code posted, you don't seem to be updating user at all. Neither are you actually including the password in the request's data parameter.

$('form').on('submit', function(e) {
  e.preventDefault();
  $.post('/testAction', {
    username: $('[name=username]', $(this)).val(),
    password: ...
  });
});

If you want a simpler way to pass all the fields from your form:

$('form').on('submit', function(e) {
  e.preventDefault();
  $.post('/testAction', (
    $(this).serializeArray().reduce((o, i) => {
      o[i.name] = i.value;
      return o;
    }, {})
  ));
});

See How can I get form data with JavaScript/jQuery?


问:
Subsetting data frame with list of times
I have a df with a time index structured as so:

```<code>                     Sensor  UnitNo
Time
2016-07-28 18:34:44    19.0     1.0
2016-07-28 19:27:39    19.0     1.0
2016-07-20 20:45:39    19.0     1.0
2016-07-20 23:05:29    19.0     1.0
2016-07-21 01:23:30    19.0     1.0
...
</code>```

I want to subset this df with a Series with a time index and a boolean column:

```<code>    Time
2016-07-28    False
2016-07-21    False
2016-07-20     True
</code>```

I want to subset the original df for the True dates in the Series:

```<code>                     Sensor  UnitNo
Time
2016-07-20 20:45:39    19.0     1.0
2016-07-20 23:05:29    19.0     1.0
</code>```

UPDATE
Apologies, when I first asked this question I thought I could easily convert the Series into a list of times, but I have found that problematic for several reasons. So, I updated the question above to resemble the current state of my data. Any help would be appreciated! Thanks in advance.

Body:
I have a df with a time index structured as so:

                     Sensor  UnitNo
Time
2016-07-28 18:34:44    19.0     1.0
2016-07-28 19:27:39    19.0     1.0
2016-07-20 20:45:39    19.0     1.0
2016-07-20 23:05:29    19.0     1.0
2016-07-21 01:23:30    19.0     1.0
...

I want to subset this df with a Series with a time index and a boolean column:

    Time
2016-07-28    False
2016-07-21    False
2016-07-20     True

I want to subset the original df for the True dates in the Series:

                     Sensor  UnitNo
Time
2016-07-20 20:45:39    19.0     1.0
2016-07-20 23:05:29    19.0     1.0

UPDATE
Apologies, when I first asked this question I thought I could easily convert the Series into a list of times, but I have found that problematic for several reasons. So, I updated the question above to resemble the current state of my data. Any help would be appreciated! Thanks in advance.

Body:
Try str.contains

List=['2016-07-28','2016-07-20']
List1=('|'.join(List))
df[df.index.to_series().str.contains(List1)]

                       Sensor  UnitNo
Time
2016-07-28 18:34:44      19       1
2016-07-28 19:27:39      19       1
2016-07-20 20:45:39      19       1
2016-07-20 23:05:29      19       1


问:
Workaround for lack of support for array constants?
Go doesn't have array constants.

My application receives messages containing several types of numeric codes which I need to display as phrases.

If array contants existed I could do something like:

func foo() {
   ...
   fmt.Println(facename[f])
   ...
}
const facename [...]string = "top", "bottom", "left", "right", "front", "back"
```

<p>But of course there's no way to do this. The first way around this that occurs to me, and maybe a reasonable efficient one is to use a <code>switch</code></p>

<pre class="lang-golang prettyprint-override"><code>func foo() {
   ...
   name := "unknown"
   switch f {
   case 0:
      name = "top"
   case 1:
      name = "bottom"
   case 2:
      name = "left"
   case 3:
      name = "right"
   case 4:
      name = "front"
   case 5:
      name = "back"
   }
   fmt.Println(name)
   ...
}
</code>```

The above is rather tedious if the number of values gets to be twenty or more.

It seems the most concise way is something like

func foo() {
   ...
   fmt.Println(strings.Split(facenames,",")[f])
   ...
}
const facenames = "top,bottom,left,right,front,back"
```

I will also have to check that the index is in range of course.
Although efficiency isn't a concern at the moment, it bugs me that
I'm using strings.Split() more than I want to.

Is there another way that is either idiomatic or both concise and efficient?

答:
The idiomatic approach is to use a package level variable:

```<code>var facename = []string{"top", "bottom", "left", "right", "front", "back"}

func foo() {
    // ...
    fmt.Println(facename[f])
    // ...
}
</code>```

It's also idiomatic to use a slice instead of an array in this situation.

Body:
Go doesn't have array constants.

My application receives messages containing several types of numeric codes which I need to display as phrases.

If array contants existed I could do something like:

func foo() {
   ...
   fmt.Println(facename[f])
   ...
}
const facename [...]string = "top", "bottom", "left", "right", "front", "back"

But of course there's no way to do this. The first way around this that occurs to me, and maybe a reasonable efficient one is to use a switch

func foo() {
   ...
   name := "unknown"
   switch f {
   case 0:
      name = "top"
   case 1:
      name = "bottom"
   case 2:
      name = "left"
   case 3:
      name = "right"
   case 4:
      name = "front"
   case 5:
      name = "back"
   }
   fmt.Println(name)
   ...
}

The above is rather tedious if the number of values gets to be twenty or more.

It seems the most concise way is something like

func foo() {
   ...
   fmt.Println(strings.Split(facenames,",")[f])
   ...
}
const facenames = "top,bottom,left,right,front,back"

I will also have to check that the index is in range of course.
Although efficiency isn't a concern at the moment, it bugs me that
I'm using strings.Split() more than I want to.

Is there another way that is either idiomatic or both concise and efficient?

Body:
The idiomatic approach is to use a package level variable:

var facename = []string{"top", "bottom", "left", "right", "front", "back"}

func foo() {
    // ...
    fmt.Println(facename[f])
    // ...
}

It's also idiomatic to use a slice instead of an array in this situation.


问:
How to Convert String to Char and Integer in Java ?
I have the following :

String contain 5* ;

char opr ;

int data ;

I would like to store the 5 in the data and * in the opr

any idea how to do it ?
 as i know if the string contain only Integer then I will split and the parse it but in this case the String contain int and char

Input :

String input = 5* ;

I want the Output will be like this :

this.opr = *

this.data = 5

答:
```<code>String input = 5*;
char[] splitted = input.toCharArray();
char opr = splitted[1];
int data = Character.getNumericValue(splitted[0]);
</code>```


问:
Will conditionals that are always false be removed by compiler in C#
Say I have the following code snippet in c#

```<code>static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}
</code>```

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

答:
I ran a bunch of tests with Reflector and Visual Studio 2008 SP1, and this is what I found.

Inside of a false conditional compilation (#if SOMETHING_FALSE...), the code is not only not compiled, but the compiler doesn't even complain about errors

In a code block inside of an always false conditional based on a constant (ie. if(false) { ... or if(constant_declared_false) { ...) variable declarations of both value and reference types are compiled, but no executable code is compiled (method calls, for loops, setting the value of a variable, etc).

If I set a local variable to false and test for the local variable, all code is compiled.

OwnerDisplayName: WindyCityEagle

Body:
Say I have the following code snippet in c#

static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

LastEditorDisplayName: Dana

OwnerDisplayName: Rich


问:
How to pass parameters to callback?
Code callback in C#:

```<code>private void CallbackVisibleButton(IAsyncResult ar)
{
    AsynchronousVisibleButtonDelegate asyncDeleg = (AsynchronousVisibleButtonDelegate)ar.AsyncState;
    b.Visibility = asyncDeleg.EndInvoke(ar);// b - not see!
}
private delegate Visibility AsynchronousVisibleButtonDelegate(Button b);
private Visibility AsynchronousVisibleButton(Button b)
{
    Thread.Sleep(2000);
    return Visibility.Visible;
}
</code>```

and createted  (b is Button, 5 seconds after the button should be visible):

```<code>AsynchronousVisibleButtonDelegate asyncDeleg = new AsynchronousVisibleButtonDelegate(AsynchronousVisibleButton);
AsyncCallback callback = new AsyncCallback(CallbackVisibleButton);
asyncDeleg.BeginInvoke(b, callback, asyncDeleg);
</code>```

problem: CallbackVisibleButton - does not see the button

答:
Maybe the code below will solve your problem.  Remove CallBackVisib... method and do as follows in your main code:</p>

```<code>        AsynchronousVisibleButtonDelegate asyncDeleg = new AsynchronousVisibleButtonDelegate(AsynchronousVisibleButton);
        AsyncCallback callback = new AsyncCallback(p =>
                                                       {
                                                           var anotherState =
                                                               p.AsyncState as AsynchronousVisibleButtonDelegate;
                                                           b.Visible = anotherState.EndInvoke(p);
                                                       });
        asyncDeleg.BeginInvoke(b, callback, asyncDeleg);
</code>```

Title: How to pass parameters to callback?

Body:
Code callback in C#:

private void CallbackVisibleButton(IAsyncResult ar)
{
    AsynchronousVisibleButtonDelegate asyncDeleg = (AsynchronousVisibleButtonDelegate)ar.AsyncState;
    b.Visibility = asyncDeleg.EndInvoke(ar);// b - not see!
}
private delegate Visibility AsynchronousVisibleButtonDelegate(Button b);
private Visibility AsynchronousVisibleButton(Button b)
{
    Thread.Sleep(2000);
    return Visibility.Visible;
}

and createted  (b is Button, 5 seconds after the button should be visible):

AsynchronousVisibleButtonDelegate asyncDeleg = new AsynchronousVisibleButtonDelegate(AsynchronousVisibleButton);
AsyncCallback callback = new AsyncCallback(CallbackVisibleButton);
asyncDeleg.BeginInvoke(b, callback, asyncDeleg);

problem: CallbackVisibleButton - does not see the button

Body:
Maybe the code below will solve your problem.  Remove CallBackVisib... method and do as follows in your main code:

        AsynchronousVisibleButtonDelegate asyncDeleg = new AsynchronousVisibleButtonDelegate(AsynchronousVisibleButton);
        AsyncCallback callback = new AsyncCallback(p =>
                                                       {
                                                           var anotherState =
                                                               p.AsyncState as AsynchronousVisibleButtonDelegate;
                                                           b.Visible = anotherState.EndInvoke(p);
                                                       });
        asyncDeleg.BeginInvoke(b, callback, asyncDeleg);


问:
django display uploaded by user images
I have ImageUploadField
I save images at my_project/forum_attachments directory.

But when I try to display them and see by this link: http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg
I get an error

Page not found (404) Request Method:  GET Request
  URL:  http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg

What do I do?

UPD: urls.py:

```<code>urlpatterns = [
    url(r'^polls/', include('some_app.urls')),
    url(r'^$', views.index, name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^about/', views.about, name='about'),
    url(r'^login/$', auth_views.login, name='login'),

    url(r'^user_logout/$', views.user_logout, name='user_logout'),
    url(r'^index_old/', views.index_old, name='index_old'),
    url(r'^forum/', views.forum, name='forum'),
    url(r'^vip/', views.vip, name='vip'),
    url(r'^test/', views.test, name='test'),
    url(r'^forum_new/', views.forum_new, name='forum_new'),
]
</code>```

答:
First set in settings.py:

```<code>MEDIA_URL = '/forum_attachments/'
</code>```

Then in your main urls.py add following piece of code:

```<code>from django.conf.urls.static import static
from django.conf import settings

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Title: django display uploaded by user images

Body:
I have ImageUploadField
I save images at my_project/forum_attachments directory.

But when I try to display them and see by this link: http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg
I get an error

Page not found (404) Request Method:  GET Request
  URL:  http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg

What do I do?

UPD: urls.py:

urlpatterns = [
    url(r'^polls/', include('some_app.urls')),
    url(r'^$', views.index, name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^about/', views.about, name='about'),
    url(r'^login/$', auth_views.login, name='login'),

    url(r'^user_logout/$', views.user_logout, name='user_logout'),
    url(r'^index_old/', views.index_old, name='index_old'),
    url(r'^forum/', views.forum, name='forum'),
    url(r'^vip/', views.vip, name='vip'),
    url(r'^test/', views.test, name='test'),
    url(r'^forum_new/', views.forum_new, name='forum_new'),
]

Body:
First set in settings.py:

MEDIA_URL = '/forum_attachments/'

Then in your main urls.py add following piece of code:

from django.conf.urls.static import static
from django.conf import settings

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


答:
you may also try this with 3 different inputs as below. It will print 0 for incorrect DATA and blank for incorrect OPERAND.</p>

```<code>    String  input       = "5*";
    //String  input       = "109/";
    //String  input       = "109b3*";

    int     data        = 0;
    char    opr         = ' ';
    int     len         = input.length();

    if  (   len > 1 ) {
        String  data_s  = input.substring(0, len - 1);

        try {
                data    = Integer.valueOf(data_s).intValue();
        } catch(Exception e) {
        }

                opr     = input.substring(len - 1). charAt(0);
        if  (   opr    != '+' && opr != '-' && opr != '*' && opr != '/' ) {
                opr     = ' ';
        }
    }

    System.out.println("Input:" + input + " Data:" + data + " Opr:" + opr);
</code>```

Title: How to Convert String to Char and Integer in Java ?

Body:
I have the following :

String contain 5* ;

char opr ;

int data ;

I would like to store the 5 in the data and * in the opr

any idea how to do it ?
 as i know if the string contain only Integer then I will split and the parse it but in this case the String contain int and char

Input :

String input = 5* ;

I want the Output will be like this :

this.opr = *

this.data = 5

Body:
you may also try this with 3 different inputs as below. It will print 0 for incorrect DATA and blank for incorrect OPERAND.

    String  input       = "5*";
    //String  input       = "109/";
    //String  input       = "109b3*";

    int     data        = 0;
    char    opr         = ' ';
    int     len         = input.length();

    if  (   len > 1 ) {
        String  data_s  = input.substring(0, len - 1);

        try {
                data    = Integer.valueOf(data_s).intValue();
        } catch(Exception e) {
        }

                opr     = input.substring(len - 1). charAt(0);
        if  (   opr    != '+' && opr != '-' && opr != '*' && opr != '/' ) {
                opr     = ' ';
        }
    }

    System.out.println("Input:" + input + " Data:" + data + " Opr:" + opr);


问:
Oracle Query to select only the text between two '-' characters
I would like to replace a column values selecting only the text inside the two '-' character. Example: Case 1 - Deleted - The case is closed.

So, i would like something like this:

Original:

```<code>Description
------------------------------------------
Case 1 - Deleted - The case is closed
</code>```

What I want to have:

```<code>Description
------------------------------------------
Deleted
</code>```

I have this but i dont know how to delete the text after the second '-' and replace that result on the current column Description

```<code>select SUBSTR(description, INSTR(description, '-') + 1) left_value
from (
    select description
    from all_cases
    );
</code>```

答:
I think you're looking for something like this:</p>
```<code>SQL>  variable s1 varchar2(40)
SQL> exec :s1:='Case 1 - Deleted1 - The case is closed';

PL/SQL procedure successfully completed.

SQL> select substr(:s1,instr(:s1,'-')+1,instr(:s1,'-',2)+1) substr_value from dual;

SUBSTR_VALUE
------------------------------
 Deleted1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to replace a column values selecting only the text inside the two '-' character. Example: Case 1 - Deleted - The case is closed.

So, i would like something like this:

Original:

Description
------------------------------------------
Case 1 - Deleted - The case is closed

What I want to have:

Description
------------------------------------------
Deleted

I have this but i dont know how to delete the text after the second '-' and replace that result on the current column Description

select SUBSTR(description, INSTR(description, '-') + 1) left_value
from (
    select description
    from all_cases
    );

Body:
I think you're looking for something like this:

SQL>  variable s1 varchar2(40)
SQL> exec :s1:='Case 1 - Deleted1 - The case is closed';

PL/SQL procedure successfully completed.

SQL> select substr(:s1,instr(:s1,'-')+1,instr(:s1,'-',2)+1) substr_value from dual;

SUBSTR_VALUE
------------------------------
 Deleted1


问:
How to import a trained SVM detector in OpenCV 2.4.13
So I have followed this guide to train my own pedestrian HOG detector. https://github.com/DaHoC/trainHOG/wiki/trainHOG-Tutorial

And it was successful with 4 files generated.

cvHOGClassifier.yaml

descriptorvector.dat

features.dat

svmlightmodel.dat

Does anyone know how to load the descriptorvector.dat file as a vector?
I've tried this but failed.

```<code>    vector<float> detector;
    std::ifstream file;
    file.open("descriptorvector.dat");
    file >> detector;
    file.close();
</code>```

This is something I would like to use eventually.

```<code>    gpu::HOGDescriptor hog(Size(64, 128), Size(16, 16), Size(8, 8), Size(8, 8),9);
    hog.setSVMDetector(detector);
</code>```

Thank you in advance!

答:
If you have already trained your SVM, you could just save the weights and the intercept in a TXT file and then load it in an array/vector. You would then use it as follows:

```<code>std::vector<float> descriptorsValues;   //A vector to store the computed HoG values
std::vector<cv::Point> locations;
hog.compute(image, descriptorsValues, cv::Size(0, 0), cv::Size(0, 0), locations);
double res = 0;
for (int i = 0; i < svmDimension - 1; i++)
{
    res += w[i] * descriptorsValues.at(i);
}
res = res + w[svmDimension - 1];
return res;
</code>```

where svmDimension is the array/vector which contains the SVM weights followed by the SVM intercept, and res is the SVM response

Body:
So I have followed this guide to train my own pedestrian HOG detector. https://github.com/DaHoC/trainHOG/wiki/trainHOG-Tutorial

And it was successful with 4 files generated.

cvHOGClassifier.yaml

descriptorvector.dat

features.dat

svmlightmodel.dat

Does anyone know how to load the descriptorvector.dat file as a vector?
I've tried this but failed.

    vector<float> detector;
    std::ifstream file;
    file.open("descriptorvector.dat");
    file >> detector;
    file.close();

This is something I would like to use eventually.

    gpu::HOGDescriptor hog(Size(64, 128), Size(16, 16), Size(8, 8), Size(8, 8),9);
    hog.setSVMDetector(detector);

Thank you in advance!

Body:
If you have already trained your SVM, you could just save the weights and the intercept in a TXT file and then load it in an array/vector. You would then use it as follows:

std::vector<float> descriptorsValues;   //A vector to store the computed HoG values
std::vector<cv::Point> locations;
hog.compute(image, descriptorsValues, cv::Size(0, 0), cv::Size(0, 0), locations);
double res = 0;
for (int i = 0; i < svmDimension - 1; i++)
{
    res += w[i] * descriptorsValues.at(i);
}
res = res + w[svmDimension - 1];
return res;

where svmDimension is the array/vector which contains the SVM weights followed by the SVM intercept, and res is the SVM response


问:
How do I fix "remote: fatal error in commit_refs" errors trying to push with Git?
When I try to push to master branch that is hosted on https://github.com I get:

remote: fatal error in commit_refs

How can I solve this?

答:
Pulling down latest code from the branch solved it for me:</p>

```<code>git pull origin master
git push origin master
</code>```

Body:
Pulling down latest code from the branch solved it for me:

git pull origin master
git push origin master


问:
Multiple https entrypoints in kubernetes
I'm planning to use traefik as my ingress-controller in kubernetes. I saw that when running alone you can define by yourself the entry points. I would like to know if I can do the same in kubernetes. Basically I would like to define a sort of configuration like this in kubernetes and who it would be.

```<code>[entryPoints]
   [entryPoints.http]
   address = ":80"
     [entryPoints.http.redirect]
       entryPoint = "https"
   [entryPoints.https]
   address = ":443"
     [entryPoints.https.tls]
       [[entryPoints.https.tls.certificates]]
       CertFile = "integration/fixtures/https/first.com.cert"
       KeyFile = "integration/fixtures/https/first.com.key"
   [entryPoints.https]
   address = ":444"
     [entryPoints.https.tls]
       [[entryPoints.https.tls.certificates]]
       CertFile = "integration/fixtures/https/second.com.cert"
       KeyFile = "integration/fixtures/https/second.com.key"
</code>```

And then associate different backends to my different entry points.

答:
Every Traefik configuration consists of two parts: A static and a dynamic one. The former can be provided through multiple means, such as command-line arguments or a configuration file. The latter is updated dynamically, with the concrete implementation being dependent to the specific provider involved.

Since the entry points are part of the static configuration, all you need to do is pass them in a format suitable to your needs. For instance, if you wanted to use a configuration file, just store the TOML configuration you have given in your question into a file and pass it to Traefik via the --configfile switch. (On Kubernetes, chances are you want to do that through a ConfigMap object.)

The complete documentation for the TOML file is given here. Supposedly, you'd be mostly interested in the parts that may apply to all providers (i.e., everything above the Configuration backends heading) and the Kubernetes backend section.

Body:
I'm planning to use traefik as my ingress-controller in kubernetes. I saw that when running alone you can define by yourself the entry points. I would like to know if I can do the same in kubernetes. Basically I would like to define a sort of configuration like this in kubernetes and who it would be.

[entryPoints]
   [entryPoints.http]
   address = ":80"
     [entryPoints.http.redirect]
       entryPoint = "https"
   [entryPoints.https]
   address = ":443"
     [entryPoints.https.tls]
       [[entryPoints.https.tls.certificates]]
       CertFile = "integration/fixtures/https/first.com.cert"
       KeyFile = "integration/fixtures/https/first.com.key"
   [entryPoints.https]
   address = ":444"
     [entryPoints.https.tls]
       [[entryPoints.https.tls.certificates]]
       CertFile = "integration/fixtures/https/second.com.cert"
       KeyFile = "integration/fixtures/https/second.com.key"

And then associate different backends to my different entry points.


问:
Embedded C Array indexing literal vs variable issue
I am in my first embedded C project at work and I have run into a behavior that perplexes me.

I am usind KEILs uVision 5 IDE and have found how to map to special function registers (SFR) memory space via the following link
http://www.keil.com/support/docs/2998.htm

Which I did with my following two file snippets

dataStructures.h

```<code>typedef unsigned char byte;
typedef struct DAC {
    byte loc[15];
} DAC;
extern DAC DAC_MAP;
</code>```

DAC_MAP.a51

```<code>PUBLIC DAC_MAP

DAC_MAP     DATA  0xB9

END
</code>```

Then I have C code which works only when the literal value of 1 is used.

```<code>byte i = 1;
DAC_MAP.loc[i] = value; // Does not write to the SFR
DAC_MAP.loc[1] = value; // Writes to the SFR
</code>```

I really would like to be able to write to a location by index and not have to write large switch cases to solve this problem.

Any thoughts as to why this is happening?

DAC_MAP.a51

```<code>PUBLIC DAC_MAP

DAC_MAP     DATA  0xB9

END
</code>```

driver.c

```<code>#include <DP8051XP.H>

typedef unsigned char byte;

typedef struct DAC {
    byte loc[15];
} DAC;

extern DAC DAC_MAP;

int main(void) {
    byte i = 1;

    DAC_MAP.loc[i] = 0xAA; // Does not write to the SFR
    DAC_MAP.loc[1] = 0xAA; // Writes to the SFR

    return 0;
}
</code>```

When I run this code in KEIL uVision 5 debugger, you can see in the memory map that the when indexing is carried out by a variable, there is no change but when the literal is used the value changes as expected.

答:
The issue is because you are attempting to access the 8051's Special Function Registers  with indirect addressing, which is not supported. You'll have to force the compiler to use direct addressing instead.

From GENERAL PURPOSE SFR INTERFACE:

The SFRs in the 8051 are directly addressable only. That means that
  the address must be a part of the program. There is no way to
  indirectly address the SFRs. So, pointers won't work. Take a look at
  the Intel documentation on the internal data memory and it should
  become clear.

One way to "sort of" do this is to define an SFR for each SFR address
  and use a big switch statement as follows:

```<code>sfr SFR_0x80 = 0x80;
sfr SFR_0x81 = 0x81;
sfr SFR_0x82 = 0x82;
.
.
.
void write_sfr (
  unsigned char sfr_address,
  unsigned char value)
{
switch (sfr_address)
  {
  case 0x80: SFR_0x80 = value; break;
  case 0x81: SFR_0x81 = value; break;
  case 0x82: SFR_0x82 = value; break;
  }
</code>```

Since it looks like your compiler is smart enough to translate DAC_MAP.loc[1] into a direct address, this driver.c would probably work for you:

```<code>#include <DP8051XP.H>

typedef unsigned char byte;
typedef struct DAC {
    byte loc[15];
} DAC;
extern DAC DAC_MAP;

static void write_dac_map(byte i, byte d) {
    switch (i) {
        case 0:  DAC_MAP.loc[0]  = d; break;
        case 1:  DAC_MAP.loc[1]  = d; break;
        case 2:  DAC_MAP.loc[2]  = d; break;
        case 3:  DAC_MAP.loc[3]  = d; break;
        case 4:  DAC_MAP.loc[4]  = d; break;
        case 5:  DAC_MAP.loc[5]  = d; break;
        case 6:  DAC_MAP.loc[6]  = d; break;
        case 7:  DAC_MAP.loc[7]  = d; break;
        case 8:  DAC_MAP.loc[8]  = d; break;
        case 9:  DAC_MAP.loc[9]  = d; break;
        case 10: DAC_MAP.loc[10] = d; break;
        case 11: DAC_MAP.loc[11] = d; break;
        case 12: DAC_MAP.loc[12] = d; break;
        case 13: DAC_MAP.loc[13] = d; break;
        case 14: DAC_MAP.loc[14] = d; break;
        default: //error
    }
}

int main(void) {
    byte i = 1;
    write_dac_map(i, 0xAA);
    return 0;
}
</code>```

If you look at the assembly your code generates (provided by stargateur), the issue is at C:0x0806:

```<code>     9: int main(void) {
    10:     byte i = 1;
    11:
C:0x0800    7F01     MOV      R7,#0x01
    12:     DAC_MAP.loc[i] = 0xAA; // Does not write to the SFR
C:0x0802    74B9     MOV      A,#DAC_MAP(0xB9)
C:0x0804    2F       ADD      A,R7
C:0x0805    F8       MOV      R0,A
C:0x0806    76AA     MOV      @R0,#0xAA
    13:     DAC_MAP.loc[1] = 0xAA; // Writes to the SFR
    14:
C:0x0808    75BAAA   MOV      0xBA,#0xAA
    15:     return 0;
C:0x080B    E4       CLR      A
C:0x080C    FE       MOV      R6,A
C:0x080D    1F       DEC      R7
    16: }
C:0x080E    22       RET
C:0x080F    787F     MOV      R0,#0x7F
C:0x0811    E4       CLR      A
C:0x0812    F6       MOV      @R0,A
C:0x0813    D8FD     DJNZ     R0,C:0812
C:0x0815    758107   MOV      SP(0x81),#0x07
C:0x0818    020800   LJMP     main(C:0800)
</code>```

MOV @R0,#0xAA uses indirect addressing, and will write 0xAA to the internal RAM at address 0xBA (R0 is set to 0xB9 + 1).

The MOV 0xBA,#0xAA instruction at C:0x0808 uses direct addressing and will  write 0xAA to the SFR at address 0xBA. (When using direct addressing, addresses between 0x00 and 0x7F refer to SFRs instead of locations in RAM).

This website has more information on the different addressing modes of the 8051: http://www.8052.com/tutaddr.phtml

Body:
I am in my first embedded C project at work and I have run into a behavior that perplexes me.

I am usind KEILs uVision 5 IDE and have found how to map to special function registers (SFR) memory space via the following link
http://www.keil.com/support/docs/2998.htm

Which I did with my following two file snippets

dataStructures.h

typedef unsigned char byte;
typedef struct DAC {
    byte loc[15];
} DAC;
extern DAC DAC_MAP;

DAC_MAP.a51

PUBLIC DAC_MAP

DAC_MAP     DATA  0xB9

END

Then I have C code which works only when the literal value of 1 is used.

byte i = 1;
DAC_MAP.loc[i] = value; // Does not write to the SFR
DAC_MAP.loc[1] = value; // Writes to the SFR

I really would like to be able to write to a location by index and not have to write large switch cases to solve this problem.

Any thoughts as to why this is happening?

DAC_MAP.a51

PUBLIC DAC_MAP

DAC_MAP     DATA  0xB9

END

driver.c

#include <DP8051XP.H>

typedef unsigned char byte;

typedef struct DAC {
    byte loc[15];
} DAC;

extern DAC DAC_MAP;

int main(void) {
    byte i = 1;

    DAC_MAP.loc[i] = 0xAA; // Does not write to the SFR
    DAC_MAP.loc[1] = 0xAA; // Writes to the SFR

    return 0;
}

When I run this code in KEIL uVision 5 debugger, you can see in the memory map that the when indexing is carried out by a variable, there is no change but when the literal is used the value changes as expected.

Body:
The issue is because you are attempting to access the 8051's Special Function Registers  with indirect addressing, which is not supported. You'll have to force the compiler to use direct addressing instead.

From GENERAL PURPOSE SFR INTERFACE:

The SFRs in the 8051 are directly addressable only. That means that
  the address must be a part of the program. There is no way to
  indirectly address the SFRs. So, pointers won't work. Take a look at
  the Intel documentation on the internal data memory and it should
  become clear.

One way to "sort of" do this is to define an SFR for each SFR address
  and use a big switch statement as follows:

sfr SFR_0x80 = 0x80;
sfr SFR_0x81 = 0x81;
sfr SFR_0x82 = 0x82;
.
.
.
void write_sfr (
  unsigned char sfr_address,
  unsigned char value)
{
switch (sfr_address)
  {
  case 0x80: SFR_0x80 = value; break;
  case 0x81: SFR_0x81 = value; break;
  case 0x82: SFR_0x82 = value; break;
  }

Since it looks like your compiler is smart enough to translate DAC_MAP.loc[1] into a direct address, this driver.c would probably work for you:

#include <DP8051XP.H>

typedef unsigned char byte;
typedef struct DAC {
    byte loc[15];
} DAC;
extern DAC DAC_MAP;

static void write_dac_map(byte i, byte d) {
    switch (i) {
        case 0:  DAC_MAP.loc[0]  = d; break;
        case 1:  DAC_MAP.loc[1]  = d; break;
        case 2:  DAC_MAP.loc[2]  = d; break;
        case 3:  DAC_MAP.loc[3]  = d; break;
        case 4:  DAC_MAP.loc[4]  = d; break;
        case 5:  DAC_MAP.loc[5]  = d; break;
        case 6:  DAC_MAP.loc[6]  = d; break;
        case 7:  DAC_MAP.loc[7]  = d; break;
        case 8:  DAC_MAP.loc[8]  = d; break;
        case 9:  DAC_MAP.loc[9]  = d; break;
        case 10: DAC_MAP.loc[10] = d; break;
        case 11: DAC_MAP.loc[11] = d; break;
        case 12: DAC_MAP.loc[12] = d; break;
        case 13: DAC_MAP.loc[13] = d; break;
        case 14: DAC_MAP.loc[14] = d; break;
        default: //error
    }
}

int main(void) {
    byte i = 1;
    write_dac_map(i, 0xAA);
    return 0;
}

If you look at the assembly your code generates (provided by stargateur), the issue is at C:0x0806:

     9: int main(void) {
    10:     byte i = 1;
    11:
C:0x0800    7F01     MOV      R7,#0x01
    12:     DAC_MAP.loc[i] = 0xAA; // Does not write to the SFR
C:0x0802    74B9     MOV      A,#DAC_MAP(0xB9)
C:0x0804    2F       ADD      A,R7
C:0x0805    F8       MOV      R0,A
C:0x0806    76AA     MOV      @R0,#0xAA
    13:     DAC_MAP.loc[1] = 0xAA; // Writes to the SFR
    14:
C:0x0808    75BAAA   MOV      0xBA,#0xAA
    15:     return 0;
C:0x080B    E4       CLR      A
C:0x080C    FE       MOV      R6,A
C:0x080D    1F       DEC      R7
    16: }
C:0x080E    22       RET
C:0x080F    787F     MOV      R0,#0x7F
C:0x0811    E4       CLR      A
C:0x0812    F6       MOV      @R0,A
C:0x0813    D8FD     DJNZ     R0,C:0812
C:0x0815    758107   MOV      SP(0x81),#0x07
C:0x0818    020800   LJMP     main(C:0800)

MOV @R0,#0xAA uses indirect addressing, and will write 0xAA to the internal RAM at address 0xBA (R0 is set to 0xB9 + 1).

The MOV 0xBA,#0xAA instruction at C:0x0808 uses direct addressing and will  write 0xAA to the SFR at address 0xBA. (When using direct addressing, addresses between 0x00 and 0x7F refer to SFRs instead of locations in RAM).

This website has more information on the different addressing modes of the 8051: http://www.8052.com/tutaddr.phtml