问:
Android RecyclerView Adapter : update already drawn item view in the click listener for current itemview
So I have a quiz app, in which I present the user with a question and four options. The 4 options are given in a RecyclerView, so I am passing the 4 options(as string ArrayList) and the correct answer(string) to the RecyclerView adapter constructor.
Now if the chosen answer is correct the itemView is set to green and if wrong it is set to red(up to this is working fine).

My problem is that

when I press the wrong answer I have to set the background color of the itemview(already drawn) with correct answer to turn green along
  with the selected wrong answer turning red

See my code below

```<code>@Override
public void onBindViewHolder(final OptionsAdapter.ViewHolder viewHolder, final int i) {
    viewHolder.tv_name.setText(option.get(i));
    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (option.get(i).equals(correct)){
                Toast.makeText(context,"CORRECT ANSWER :)",Toast.LENGTH_SHORT).show();
                viewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.correctAnswer));
            } else {
                Toast.makeText(context,"SORRY INCORRECT ANSWER :(",Toast.LENGTH_SHORT).show();
                viewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.wrongAnswer));
            }
        }
    });

}
</code>```

In the above snippet of my onBindViewHolder, the arraylist option is having the 4 options and the string correct is the correct answer.

How can i turn the correct answer to turn green when the wrong answer clicked?

Below image shows what iam expecting when wrong answer clicked

答:
Add These methods to your model class:

```<code>private boolean isSelected;

public boolean isSelected() {
    return isSelected;
}

public void setSelected(boolean selected) {
    isSelected = selected;
}
</code>```

Add this code onClick on your adapter:

```<code>if (mArrayList.get(position).isSelected()) {
    mArrayList.get(position).setSelected(false);
} else {
    mArrayList.get(position).setSelected(true);
}
notifyItemChanged(position);
</code>```

Body:
So I have a quiz app, in which I present the user with a question and four options. The 4 options are given in a RecyclerView, so I am passing the 4 options(as string ArrayList) and the correct answer(string) to the RecyclerView adapter constructor.
Now if the chosen answer is correct the itemView is set to green and if wrong it is set to red(up to this is working fine).

My problem is that

when I press the wrong answer I have to set the background color of the itemview(already drawn) with correct answer to turn green along
  with the selected wrong answer turning red

See my code below

@Override
public void onBindViewHolder(final OptionsAdapter.ViewHolder viewHolder, final int i) {
    viewHolder.tv_name.setText(option.get(i));
    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (option.get(i).equals(correct)){
                Toast.makeText(context,"CORRECT ANSWER :)",Toast.LENGTH_SHORT).show();
                viewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.correctAnswer));
            } else {
                Toast.makeText(context,"SORRY INCORRECT ANSWER :(",Toast.LENGTH_SHORT).show();
                viewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.wrongAnswer));
            }
        }
    });

}

In the above snippet of my onBindViewHolder, the arraylist option is having the 4 options and the string correct is the correct answer.

How can i turn the correct answer to turn green when the wrong answer clicked?

Below image shows what iam expecting when wrong answer clicked

Body:
Add These methods to your model class:

private boolean isSelected;

public boolean isSelected() {
    return isSelected;
}

public void setSelected(boolean selected) {
    isSelected = selected;
}

Add this code onClick on your adapter:

if (mArrayList.get(position).isSelected()) {
    mArrayList.get(position).setSelected(false);
} else {
    mArrayList.get(position).setSelected(true);
}
notifyItemChanged(position);


来源: stackexchange

问:
How to control whether Python uses OpenCV2 or OpenCV3?
On Linux with Python 2.7 there is usually /usr/local/lib/python2.7/{dist,site}-packages/cv.{so,py}, but how can I tell which version of OpenCV I have there? Is it possible to install both and switch between them, or to force a particular version?

Note: pip freeze | grep opencv returns nothing at all even though I can use import cv2.

答:
There are 2 options.

1) You can check it with pip. Outputs installed packages in requirements format.

```<code>pip freeze
or
pip freeze | grep opencv
</code>```

2) From within python

```<code>import cv2
print cv2.__version__
>'3.3.0'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There are 2 options.

1) You can check it with pip. Outputs installed packages in requirements format.

pip freeze
or
pip freeze | grep opencv

2) From within python

import cv2
print cv2.__version__
>'3.3.0'


问:
Creating a dictionary with string,string, string,int and string,object
I am just getting started with C# and I'm a little stuck.

How do I create a dictionary that contains a mix of string,string, string,int, and string,object?

this is what it would look like:

```<code>var values = new Dictionary<????>
{
    "key0":
         {
         "key1": "stringValue1",
         "key2": "stringValue2",
         "key3": "stringValue3",
         "key4": 10000
         },
    "key5": "stringValue4",
    "key6": "stringValue5"
};
</code>```

I am using this as the body for a POST request. Sample code from here

```<code>var body = new FormUrlEncodedContent(values);

var url = "http://url.com/endpoint"

var resp = await client.PostAsync(url, body);

var respString = await response.Content.ReadAsStringAsync();
</code>```

答:
You can use dynamic. However, in the end, form post will convert everything into string, so you might wanna convert int and object into string first. Then, you can just use Dictionary<string, string>

```<code>        Dictionary<string, dynamic> Dict = new Dictionary<string, dynamic>();
        Dict.Add("string1", "1");
        Dict.Add("string2", 2);
        Dict.Add("string3", new object());
</code>```

Body:
I am just getting started with C# and I'm a little stuck.

How do I create a dictionary that contains a mix of string,string, string,int, and string,object?

this is what it would look like:

var values = new Dictionary<????>
{
    "key0":
         {
         "key1": "stringValue1",
         "key2": "stringValue2",
         "key3": "stringValue3",
         "key4": 10000
         },
    "key5": "stringValue4",
    "key6": "stringValue5"
};

I am using this as the body for a POST request. Sample code from here

var body = new FormUrlEncodedContent(values);

var url = "http://url.com/endpoint"

var resp = await client.PostAsync(url, body);

var respString = await response.Content.ReadAsStringAsync();

Body:
You can use dynamic. However, in the end, form post will convert everything into string, so you might wanna convert int and object into string first. Then, you can just use Dictionary<string, string>

        Dictionary<string, dynamic> Dict = new Dictionary<string, dynamic>();
        Dict.Add("string1", "1");
        Dict.Add("string2", 2);
        Dict.Add("string3", new object());


问:
The server committed a protocol violation. Section=ResponseStatusLine ERROR
I have created a program, tried to post a string on a site and I get this error:

"The server committed a protocol violation. Section=ResponseStatusLine"

after this line of code:

```<code>gResponse = (HttpWebResponse)gRequest.GetResponse();
</code>```

How can I fix this exception?

答:
I started getting this error from my php JSON/REST services

I started getting the error from relativley rare POST uploads after I added ob_start("ob_gzhandler") to most frequently accessed GET php script

I am able to use just ob_start(), and everything is fine.

Body:
I have created a program, tried to post a string on a site and I get this error:

"The server committed a protocol violation. Section=ResponseStatusLine"

after this line of code:

gResponse = (HttpWebResponse)gRequest.GetResponse();

How can I fix this exception?


问:
Dynamically render a directive from a JSON array
I would like to pass my SPA a JSON array and render controls and directives based on what is in the array.

I have all the controls rendering based on the answer found here; plunker link

However, I also have custom directives that I'd like to render but I don't want to specify each of them in the HTML.  Instead I'd like to just do something like;

```<code><div ng-if="field.type=='directive'" class="form-group {{field.css}}">
  <{{field.directive}}></{{field.directive}}>
</div>
</code>```

and then in the JSON object specify which directive to render;

```<code>app.directive("testDirective", function(){
    return {
        restrict: 'E',
        scope: {},
        template: '<h2>This is a custom directive to show that we can render these also.</h2>',
        replace: true
    };
})
</code>```

And add that directive to the list of controls to render;

```<code>fields :
        [
          {type: "directive", directive:"test-directive", name: "td1", data: ""},
</code>```

The code I have created simply outputs;

```<code><test-directive>
</code>```

as text and not as the control itself.

Any thoughts?

答:
As @charlietfl and @Saurabh Agrawal, there are easy ways in angular 2 & 4. But, still for your reference, I have made a solution in angular 1. Now the template will render based ion the data type in your JSON.

HTML code :

```<code><body ng-app="dynamicDirective" ng-controller="MyModule">
 <div ng-repeat="field in entity.fields">
   <dynamic-field data='field'> </dynamic-field>
   <br/>
 </div>
</body>
</code>```

Script code:

```<code>app.directive('dynamicField', function() {
  return {
    restrict: 'E',
    scope: {
      data: "="
    },
    templateUrl: 'template.html',
    link: function(scope, element, attrs) {

    }
  }
});
</code>```

And this is the template html file in which the field will be rendering based on the type in the JSON data. Refer the link below

```<code><!-- Text Template -->
<div ng-if="data.type === 'text'">
  {{data.name}} <input type="text"/>
</div>

<!-- Radio Template -->
<div ng-if="data.type === 'radio'">
  {{data.name}}
  <div ng-repeat="option in data.options">
    <input type="radio" value="option.name" />{{option.name}}
  </div>
</div>

<!-- Email Template -->
<div ng-if="data.type === 'email'">
  {{data.name}} <input type="text"/>
</div>

<!-- Password Template -->
<div ng-if="data.type === 'password'">
  {{data.name}} <input type="password"/>
</div>

<!-- Select Template -->
<div ng-if="data.type === 'select'">
  {{data.name}} <select><option ng-repeat="option in data.options">
    {{option.name}}</option></select>
</div>

<!-- Checkbox Template -->
<div ng-if="data.type === 'checkbox'">
  {{data.name}}
  <div ng-repeat="option in data.options">
    <input type="checkbox" value="option.name" />{{option.name}}
  </div>
</div>
</code>```

Plnkr Link

Hope it helps :)

Body:
I would like to pass my SPA a JSON array and render controls and directives based on what is in the array.

I have all the controls rendering based on the answer found here; plunker link

However, I also have custom directives that I'd like to render but I don't want to specify each of them in the HTML.  Instead I'd like to just do something like;

  <{{field.directive}}></{{field.directive}}>

and then in the JSON object specify which directive to render;

app.directive("testDirective", function(){
    return {
        restrict: 'E',
        scope: {},
        template: '
This is a custom directive to show that we can render these also.
',
        replace: true
    };
})

And add that directive to the list of controls to render;

fields :
        [
          {type: "directive", directive:"test-directive", name: "td1", data: ""},

The code I have created simply outputs;

<test-directive>

as text and not as the control itself.

Any thoughts?

Body:
As @charlietfl and @Saurabh Agrawal, there are easy ways in angular 2 & 4. But, still for your reference, I have made a solution in angular 1. Now the template will render based ion the data type in your JSON.

HTML code :

<body ng-app="dynamicDirective" ng-controller="MyModule">
 <div ng-repeat="field in entity.fields">
   <dynamic-field data='field'> </dynamic-field>
   <br/>
 </div>
</body>

Script code:

app.directive('dynamicField', function() {
  return {
    restrict: 'E',
    scope: {
      data: "="
    },
    templateUrl: 'template.html',
    link: function(scope, element, attrs) {

    }
  }
});

And this is the template html file in which the field will be rendering based on the type in the JSON data. Refer the link below

<!-- Text Template -->
<div ng-if="data.type === 'text'">
  {{data.name}} <input type="text"/>
</div>

<!-- Radio Template -->
<div ng-if="data.type === 'radio'">
  {{data.name}}
  <div ng-repeat="option in data.options">
    <input type="radio" value="option.name" />{{option.name}}
  </div>
</div>

<!-- Email Template -->
<div ng-if="data.type === 'email'">
  {{data.name}} <input type="text"/>
</div>

<!-- Password Template -->
<div ng-if="data.type === 'password'">
  {{data.name}} <input type="password"/>
</div>

<!-- Select Template -->
<div ng-if="data.type === 'select'">
  {{data.name}} <select><option ng-repeat="option in data.options">
    {{option.name}}</option></select>
</div>

<!-- Checkbox Template -->
<div ng-if="data.type === 'checkbox'">
  {{data.name}}
  <div ng-repeat="option in data.options">
    <input type="checkbox" value="option.name" />{{option.name}}
  </div>
</div>

Plnkr Link

Hope it helps :)


问:
C# ef second operation started before previous asynchronous operation completed
Just trying to do normal query on ef but getting below error message

"A second operation started on this context before a previous asynchronous operation completed"

I am using await for all aync call but not sure what could be causing this issue.

here' code

```<code>    var sids = await context.Sites.Where(s => slist.Contains(s.JVSiteID)).ToListAsync();

    var header = await context.GenericCsvHeaders.FirstOrDefaultAsync(x => x.Header == csvh) ?? new GenericCsvHeader { Header = csvh };

    context.Entry<GenericCsvHeader>(header).State = (header.GenericCsvHeaderID == 0) ? EntityState.Added : EntityState.Unchanged;

    var sa = await context.SAs.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.SAName)).Select(x => new { x.SAName, x.SACode, x.SAID }).ToListAsync();

    if (sa.Count > 0)
        sasitelist = await context.Site_SA.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();

    var az = await context.Azimuths.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.AzimuthName)).Select(x => new { x.AzimuthName, x.AzimuthID }).ToListAsync();

    if (az.Count > 0)
           azsitelist = await context.Site_Azimuth.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();

    var rows = new List<dynamic>(); //getting this list from csv file via csvHelper

     foreach (var r in rows)
       {
           var s = sids.FirstOrDefault(x => x.JVSiteID == (((IDictionary<String, Object>)r)[siteid]).ToString()) ?? new Site();
            UpdateSite(s, r, map);
       }

    private async void UpdateSite(Site site, dynamic csvSite, IDictionary<string, string> map)
    {

       context.Entry(site).State = (site.StateID == 0) ? EntityState.Added : EntityState.Modified;
       site.SiteForAuditTrail = site;
       if (map.ContainsKey("SiteName") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite,"SiteName")))
             site.SiteName = GetStringOfDynamic(map,csvSite, "SiteName");

       if (map.ContainsKey("State") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite, "State")))
         {
            //getting exception at below line
             var state = (await GetRefTypeList<State>(x => x.StateCode == GetStringOfDynamic(map,csvSite, "State"))) ?? new State { StateCode = GetStringOfDynamic(map,csvSite, "State") };

          context.Entry(state).State = (state.StateID == 0) ? EntityState.Added : EntityState.Unchanged;
           site.State = state;
          state.SiteForAuditTrail = site;
     }

  }

private async Task<T> GetRefTypeList<T>(Func<T, bool> expression) where T : EntityBase
 {
       if (!refTypes.ContainsKey(typeof(T).Name))
              refTypes[typeof(T).Name] = (await context.Set<T>().Where(x => x.StatusID == Data.Enum.Status.Active).ToListAsync());

       return (refTypes[typeof(T).Name] as List<T>)?.FirstOrDefault(expression);
 }

private string GetStringOfDynamic(IDictionary<string, string> map,dynamic obj, string propertyName)
 {
    if (((IDictionary<String, Object>)obj).ContainsKey(map[propertyName]))
          return (((IDictionary<String, Object>)obj)[map[propertyName]]??"").ToString();

         return "";
 }
</code>```

答:
found problem, was missing await when calling UpdateSite </p>

```<code> foreach (var r in rows)
       {
           var s = sids.FirstOrDefault(x => x.JVSiteID == (((IDictionary<String, Object>)r)[siteid]).ToString()) ?? new Site();
          **await**  UpdateSite(s, r, map);
       }
</code>```

Body:
Just trying to do normal query on ef but getting below error message

"A second operation started on this context before a previous asynchronous operation completed"

I am using await for all aync call but not sure what could be causing this issue.

here' code

    var sids = await context.Sites.Where(s => slist.Contains(s.JVSiteID)).ToListAsync();

    var header = await context.GenericCsvHeaders.FirstOrDefaultAsync(x => x.Header == csvh) ?? new GenericCsvHeader { Header = csvh };

    context.Entry<GenericCsvHeader>(header).State = (header.GenericCsvHeaderID == 0) ? EntityState.Added : EntityState.Unchanged;

    var sa = await context.SAs.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.SAName)).Select(x => new { x.SAName, x.SACode, x.SAID }).ToListAsync();

    if (sa.Count > 0)
        sasitelist = await context.Site_SA.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();

    var az = await context.Azimuths.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.AzimuthName)).Select(x => new { x.AzimuthName, x.AzimuthID }).ToListAsync();

    if (az.Count > 0)
           azsitelist = await context.Site_Azimuth.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();

    var rows = new List<dynamic>(); //getting this list from csv file via csvHelper

     foreach (var r in rows)
       {
           var s = sids.FirstOrDefault(x => x.JVSiteID == (((IDictionary<String, Object>)r)[siteid]).ToString()) ?? new Site();
            UpdateSite(s, r, map);
       }

    private async void UpdateSite(Site site, dynamic csvSite, IDictionary<string, string> map)
    {

       context.Entry(site).State = (site.StateID == 0) ? EntityState.Added : EntityState.Modified;
       site.SiteForAuditTrail = site;
       if (map.ContainsKey("SiteName") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite,"SiteName")))
             site.SiteName = GetStringOfDynamic(map,csvSite, "SiteName");

       if (map.ContainsKey("State") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite, "State")))
         {
            //getting exception at below line
             var state = (await GetRefTypeList<State>(x => x.StateCode == GetStringOfDynamic(map,csvSite, "State"))) ?? new State { StateCode = GetStringOfDynamic(map,csvSite, "State") };

          context.Entry(state).State = (state.StateID == 0) ? EntityState.Added : EntityState.Unchanged;
           site.State = state;
          state.SiteForAuditTrail = site;
     }

  }

private async Task<T> GetRefTypeList<T>(Func<T, bool> expression) where T : EntityBase
 {
       if (!refTypes.ContainsKey(typeof(T).Name))
              refTypes[typeof(T).Name] = (await context.Set<T>().Where(x => x.StatusID == Data.Enum.Status.Active).ToListAsync());

       return (refTypes[typeof(T).Name] as List<T>)?.FirstOrDefault(expression);
 }

private string GetStringOfDynamic(IDictionary<string, string> map,dynamic obj, string propertyName)
 {
    if (((IDictionary<String, Object>)obj).ContainsKey(map[propertyName]))
          return (((IDictionary<String, Object>)obj)[map[propertyName]]??"").ToString();

         return "";
 }

Body:
found problem, was missing await when calling UpdateSite

 foreach (var r in rows)
       {
           var s = sids.FirstOrDefault(x => x.JVSiteID == (((IDictionary<String, Object>)r)[siteid]).ToString()) ?? new Site();
          **await**  UpdateSite(s, r, map);
       }


问:
Will MSSQL 2012 database work on MSSQL 2008 server?
I have MsSQL database which is created in MSSQL 2012 SQL server.

On my local machine I have installed MSSQL 2008 SQL server.

Will the 2012 database work in MSSQL 2008?

Also,I have installed MSSQL 2012 SQL server on my local system.Do I need to install MSSQL management studio for 2012 SQL server?

Is it required for user interface?

答:
A full database backup and restore to the new server will not work. SQL server does not allow that to a previous version.

You can however create the schema and load the data in manually through SSIS or BCP.

For SSMS you can connect to a previous version.


问:
Ternary operator is not a statement
I've the following ternary expression:

```<code>((!f.exists()) ? (f.createNewFile() ? printFile() : throw new Exception("Error in creating file")) : printFile());
</code>```

For one, or more, reason that I don't know idea IDE say to me that it isn't a statement. Why?

答:
The statements in the ternary operator need to be non-void. They need to return something.

Example:

Consider a case, where count variable gets incremented and I am checking for its value and return true or false above certain threshold.

System.out.println((count >10 ? true: false));

As compared to, count >10 ? true: false where compiler will complain that this is not a statement.

Title: Ternary operator is not a statement

Body:
I've the following ternary expression:

((!f.exists()) ? (f.createNewFile() ? printFile() : throw new Exception("Error in creating file")) : printFile());

For one, or more, reason that I don't know idea IDE say to me that it isn't a statement. Why?


问:
develop Web sites for mobiles
I want to implement "mobile website provider" tool. Basically, It intake desktop website url and generate a mobile version of website without edit/add additional content to the desktop website. I am planning to design a product like (what mofuse.com does. This website create mobile websites). This tool should be hassle free to client(who are not tech savvy.)

1.Q) I want to know kind of functionality involved in this process.

2.Q) In Java Technology, I need the tool set and functionality of this actitity.

As I am new to this mobile application environment. Any information(web links) regarding this will be appreciated.

Update:

its not like skweezer.com.

I had a website and I want to "mobile"ize it. 1) What kind of java tool set I have to use to create mobile web site? 2) How to test in multiple mobile devices 3) How the domain name will be created for mobile websites.

答:
Check out our Wapple Architect tech (http://wapple.net) - we allow you to use the same content from web to mobile, but if it's mobile, instead of outputting the html, use a web service to turn it into the right content for that particular handset.

Mobilizes the same domain, no need for m.yourdomain.com or anything like that.

Check http://wapple.net on a mobile for example!

ContentLicense: CC BY-SA 2.5

Title: develop Web sites for mobiles


问:
v-model is not updated in when using radio button in vue js?
I went through the documentation and I tried the following code. I can get the data for enquiryDesc but I'm always getting value 5 for rating. I also tried changing the radio group to a checkbox but it did not work.

My html form:

```<code><form id="enquiryBox" method="POST" data-parsley-validate="true" v-on:submit.prevent="handelSubmit()">
  <div class="modal-body brbottom-20">
    <div class="clearfix">
      <div class="col-lg-6">
        <div class="form-group required">
      <fieldset class="rating">
                <input v-model="rating" type="radio" id="rating" name="rating" value="5" ><label class = "full" for="star5" title="Awesome">5</label>
                <input v-model="rating" type="radio" id="rating" name="rating" value="4" ><label class="half" for="star4half" title="Pretty good">4</label>
    </fieldset>
        </div>
      </div>
      <div class="col-lg-6">
        <div class="form-group required">
          <label>Enquiry</label>
          <textarea placeholder="Write your enquiry here" rows="7" id="enquiryDesc" name="enquiryDesc" class="form-control required" title="Desc" v-model="enquiryDesc" required="required"></textarea>
        </div>
      </div>
    </div>
  </div>
  <div class="">
    <button id="btn-submit-enquiry" class="btn whiteButton" type="submit">Post Enquiry</button>
  </div>
</form>
</code>```

My Vue.js script:

```<code>enquiryBox = new Vue({
   el: "#enquiryBox",
   data: {
     rating: '',
     enquiryDesc: '',
   },
   methods: {
     handelSubmit: function(e) {
       var vm = this;
       data = {};
       data['rating'] = this.rating;
       data['enquiryDesc'] = this.enquiryDesc;
       console.log(data);

       $.ajax({
         url: 'https://api/post/add_review/',
         data: data,
         type: "POST",
         dataType: 'json',
         success: function(e) {
           if (e.status) {
             alert("Success")

           } else {
             vm.response = e;

             alert(" Failed")
           }
         }
       });
       return false;
     }
   },
 });
</code>```

My response for console.log(data)

{rating: "", enquiryDesc: "hello how are you"}

The value of rating never changes, it always stays 5.

答:
You should not bind the value to radio as you don't need to modify them so,

v-bind:value="5" and v-bind:value="4" just remove this lines instead use normal value="4" and value="5"

and in data you don't need to set rating : 5  just use rating :''
  as user will select and then this data will be filled.

checkout this snippet.

enquiryBox = new Vue({
   el: "#enquiryBox",
   data: {
     rating: '',
     enquiryDesc: '',
   },
   methods: {
     handelSubmit: function(e) {
       var vm = this;
       data = {};
       data['rating'] = this.rating;
       data['enquiryDesc'] = this.enquiryDesc;
       console.log(data);

       return false;
     }
   },
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>

        <form id="enquiryBox" method="POST" data-parsley-validate="true" v-on:submit.prevent="handelSubmit()">
  <div class="modal-body brbottom-20">
    <div class="clearfix">
      <div class="col-lg-6">
        <div class="form-group required">
      <fieldset class="rating">
                <input v-model="rating" type="radio" id="rating" name="rating" value="5" ><label class = "full" for="star5" title="Awesome">5</label>
                <input v-model="rating" type="radio" id="rating" name="rating" value="4" ><label class="half" for="star4half" title="Pretty good">4</label>
    </fieldset>
        </div>
      </div>
      <div class="col-lg-6">
        <div class="form-group required">
          <label>Enquiry</label>
          <textarea placeholder="Write your enquiry here" rows="7" id="enquiryDesc" name="enquiryDesc" class="form-control required" title="Desc" v-model="enquiryDesc" required="required"></textarea>
        </div>
      </div>
    </div>
  </div>
  <div class="">
    <button id="btn-submit-enquiry" class="btn whiteButton" type="submit">Post Enquiry</button>
  </div>
</form>

</body>

</html></code>```

other way click on number then press submit you can see its updated:

var enquiryBox = new Vue({
   el: "#enquiryBox",
   data: {
     rating: '',
     enquiryDesc: '',
   },
   methods: {
     handelSubmit: function(e) {
       var vm = this;
       data = {};
       data['rating'] = this.rating;
       data['enquiryDesc'] = this.enquiryDesc;
       console.log(data);
       return false;
     }
   },
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>
    <div id="enquiryBox">
        <form method="POST" data-parsley-validate="true" v-on:submit.prevent="handelSubmit()">
          <div class="modal-body brbottom-20">
            <div class="clearfix">
              <div class="col-lg-6">
                <div class="form-group required">
                  <fieldset class="rating">
                    <span @click="rating = 1">1</span>
                    <span @click="rating = 2">2</span>
                    <span @click="rating = 3">3</span>
                  </fieldset>
                </div>
              </div>

            </div>
          </div>
          <div class="">
            <button id="btn-submit-enquiry" class="btn whiteButton" type="submit">Post Enquiry</button>
          </div>
        </form>
    </div>

</body>

</html></code>```

ContentLicense: CC BY-SA 4.0

Body:
I went through the documentation and I tried the following code. I can get the data for enquiryDesc but I'm always getting value 5 for rating. I also tried changing the radio group to a checkbox but it did not work.

My html form:

<form id="enquiryBox" method="POST" data-parsley-validate="true" v-on:submit.prevent="handelSubmit()">

      <fieldset class="rating">
                <input v-model="rating" type="radio" id="rating" name="rating" value="5" >5
                <input v-model="rating" type="radio" id="rating" name="rating" value="4" >4
    </fieldset>

          Enquiry
          <textarea placeholder="Write your enquiry here" rows="7" id="enquiryDesc" name="enquiryDesc" class="form-control required" title="Desc" v-model="enquiryDesc" required="required"></textarea>

    <button id="btn-submit-enquiry" class="btn whiteButton" type="submit">Post Enquiry</button>

</form>

My Vue.js script:

enquiryBox = new Vue({
   el: "#enquiryBox",
   data: {
     rating: '',
     enquiryDesc: '',
   },
   methods: {
     handelSubmit: function(e) {
       var vm = this;
       data = {};
       data['rating'] = this.rating;
       data['enquiryDesc'] = this.enquiryDesc;
       console.log(data);

       $.ajax({
         url: 'https://api/post/add_review/',
         data: data,
         type: "POST",
         dataType: 'json',
         success: function(e) {
           if (e.status) {
             alert("Success")

           } else {
             vm.response = e;

             alert(" Failed")
           }
         }
       });
       return false;
     }
   },
 });

My response for console.log(data)

{rating: "", enquiryDesc: "hello how are you"}

The value of rating never changes, it always stays 5.

Body:
You should not bind the value to radio as you don't need to modify them so,

v-bind:value="5" and v-bind:value="4" just remove this lines instead use normal value="4" and value="5"

and in data you don't need to set rating : 5  just use rating :''
  as user will select and then this data will be filled.

checkout this snippet.

enquiryBox = new Vue({
   el: "#enquiryBox",
   data: {
     rating: '',
     enquiryDesc: '',
   },
   methods: {
     handelSubmit: function(e) {
       var vm = this;
       data = {};
       data['rating'] = this.rating;
       data['enquiryDesc'] = this.enquiryDesc;
       console.log(data);

       return false;
     }
   },
 });

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>

        <form id="enquiryBox" method="POST" data-parsley-validate="true" v-on:submit.prevent="handelSubmit()">
  <div class="modal-body brbottom-20">
    <div class="clearfix">
      <div class="col-lg-6">
        <div class="form-group required">
      <fieldset class="rating">
                <input v-model="rating" type="radio" id="rating" name="rating" value="5" ><label class = "full" for="star5" title="Awesome">5</label>
                <input v-model="rating" type="radio" id="rating" name="rating" value="4" ><label class="half" for="star4half" title="Pretty good">4</label>
    </fieldset>
        </div>
      </div>
      <div class="col-lg-6">
        <div class="form-group required">
          <label>Enquiry</label>
          <textarea placeholder="Write your enquiry here" rows="7" id="enquiryDesc" name="enquiryDesc" class="form-control required" title="Desc" v-model="enquiryDesc" required="required"></textarea>
        </div>
      </div>
    </div>
  </div>
  <div class="">
    <button id="btn-submit-enquiry" class="btn whiteButton" type="submit">Post Enquiry</button>
  </div>
</form>

</body>

</html>

other way click on number then press submit you can see its updated:

var enquiryBox = new Vue({
   el: "#enquiryBox",
   data: {
     rating: '',
     enquiryDesc: '',
   },
   methods: {
     handelSubmit: function(e) {
       var vm = this;
       data = {};
       data['rating'] = this.rating;
       data['enquiryDesc'] = this.enquiryDesc;
       console.log(data);
       return false;
     }
   },
 });

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>
    <div id="enquiryBox">
        <form method="POST" data-parsley-validate="true" v-on:submit.prevent="handelSubmit()">
          <div class="modal-body brbottom-20">
            <div class="clearfix">
              <div class="col-lg-6">
                <div class="form-group required">
                  <fieldset class="rating">
                    <span @click="rating = 1">1</span>
                    <span @click="rating = 2">2</span>
                    <span @click="rating = 3">3</span>
                  </fieldset>
                </div>
              </div>

            </div>
          </div>
          <div class="">
            <button id="btn-submit-enquiry" class="btn whiteButton" type="submit">Post Enquiry</button>
          </div>
        </form>
    </div>

</body>

</html>


问:
Troubles using fragment with RecyclerView and Retrofit
I have this error, actually I don't know about fragments.

CreatView

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_inicio, container,
                false);
        getActivity().setTitle(R.string.inicio);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        loadJSON();
        return rootView;
    }
</code>```

loadJSON void

```<code>private void loadJSON(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.1.42:3000/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RequestInterface request = retrofit.create(RequestInterface.class);
    Call<JSONResponse> call = request.getJSON();
    call.enqueue(new Callback<JSONResponse>() {
        @Override
        public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
            JSONResponse jsonResponse = response.body();
            data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
            adapter = new CuponAdapter(data);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<JSONResponse> call, Throwable t) {
            Log.d("Error", t.getMessage());
        }
    });
}
</code>```

Adapter

```<code>public class CuponAdapter extends RecyclerView.Adapter<CuponAdapter.ViewHolder> {
private ArrayList<Cupon> cupon;

public CuponAdapter(ArrayList<Cupon> cupon) {
    this.cupon = cupon;
}

@Override
public CuponAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int i) {
    holder.tv_titulo.setText(cupon.get(i).getTitulo());
    holder.tv_empresa.setText(cupon.get(i).getEmpresa());
    holder.tv_descripcion.setText(cupon.get(i).getDescripcion());
}

@Override
public int getItemCount() {
    return cupon.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    private TextView tv_titulo, tv_descripcion, tv_empresa;

    public ViewHolder(View view) {
        super(view);
        tv_titulo = (TextView) view.findViewById(R.id.tv_titulo);
        tv_descripcion = (TextView) view.findViewById(R.id.tv_descripcion);
        tv_empresa = (TextView) view.findViewById(R.id.tv_empresa);
    }
}
}
</code>```

The Error

12-08 00:00:05.727 1784-1784/com.mighty.cupoferta E/RecyclerView: No
  adapter attached; skipping layout

This code is based on this link .
But he explains how to put in an activity, how can I put in a fragment?

答:
```<code>  call.enqueue(new Callback<JSONResponse>() {
    @Override
    public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
        JSONResponse jsonResponse = response.body();
        data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
        adapter = new CuponAdapter(data);
        recyclerView.setAdapter(adapter);
    }
</code>```

Do not depend on network response to set your adapter.

```<code>RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
</code>```

You can do it right here.

Then after the network response you can add data to the adapter and call notifyDataSetChanged()

Body:
I have this error, actually I don't know about fragments.

CreatView

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_inicio, container,
                false);
        getActivity().setTitle(R.string.inicio);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        loadJSON();
        return rootView;
    }

loadJSON void

private void loadJSON(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.1.42:3000/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RequestInterface request = retrofit.create(RequestInterface.class);
    Call<JSONResponse> call = request.getJSON();
    call.enqueue(new Callback<JSONResponse>() {
        @Override
        public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
            JSONResponse jsonResponse = response.body();
            data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
            adapter = new CuponAdapter(data);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<JSONResponse> call, Throwable t) {
            Log.d("Error", t.getMessage());
        }
    });
}

Adapter

public class CuponAdapter extends RecyclerView.Adapter<CuponAdapter.ViewHolder> {
private ArrayList<Cupon> cupon;

public CuponAdapter(ArrayList<Cupon> cupon) {
    this.cupon = cupon;
}

@Override
public CuponAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int i) {
    holder.tv_titulo.setText(cupon.get(i).getTitulo());
    holder.tv_empresa.setText(cupon.get(i).getEmpresa());
    holder.tv_descripcion.setText(cupon.get(i).getDescripcion());
}

@Override
public int getItemCount() {
    return cupon.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    private TextView tv_titulo, tv_descripcion, tv_empresa;

    public ViewHolder(View view) {
        super(view);
        tv_titulo = (TextView) view.findViewById(R.id.tv_titulo);
        tv_descripcion = (TextView) view.findViewById(R.id.tv_descripcion);
        tv_empresa = (TextView) view.findViewById(R.id.tv_empresa);
    }
}
}

The Error

12-08 00:00:05.727 1784-1784/com.mighty.cupoferta E/RecyclerView: No
  adapter attached; skipping layout

This code is based on this link .
But he explains how to put in an activity, how can I put in a fragment?

Body:
  call.enqueue(new Callback<JSONResponse>() {
    @Override
    public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
        JSONResponse jsonResponse = response.body();
        data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
        adapter = new CuponAdapter(data);
        recyclerView.setAdapter(adapter);
    }

Do not depend on network response to set your adapter.

RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);

You can do it right here.

Then after the network response you can add data to the adapter and call notifyDataSetChanged()


问:
repeating rnorm 20 times but not able to get 20 random outputs
I am currently programming a loop and have made a vector called growth_rate. I want to use the rnorm function to draw a random number for this vector 20 times. The code I am using to do this is

```<code>growth_rate <- rep((rnorm(n = 1, mean = 1, sd = 0.4)), times = 20)
</code>```

I have also made a vector called

```<code>rate <- rnorm(n = 1, mean = 1, sd = 0.4)
</code>```

Making a vector called

```<code>grate <- rep(rate, 20)
</code>```

it still outputs the same number 20 times instead of 20 random numbers e.g.

[1] 1.304936 1.304936 1.304936 1.304936 1.304936 1.304936 1.304936 1.304936 1.304936

and so on...

Is there anyway I can output 20 random numbers in one vector and not make 20 separate vectors using rnorm instead? Thank you!

Body:
I am currently programming a loop and have made a vector called growth_rate. I want to use the rnorm function to draw a random number for this vector 20 times. The code I am using to do this is

growth_rate <- rep((rnorm(n = 1, mean = 1, sd = 0.4)), times = 20)

I have also made a vector called

rate <- rnorm(n = 1, mean = 1, sd = 0.4)

Making a vector called

grate <- rep(rate, 20)

it still outputs the same number 20 times instead of 20 random numbers e.g.

[1] 1.304936 1.304936 1.304936 1.304936 1.304936 1.304936 1.304936 1.304936 1.304936

and so on...

Is there anyway I can output 20 random numbers in one vector and not make 20 separate vectors using rnorm instead? Thank you!

Body:
If you want to draw 20 samples from the same normal distribution, just use rnorm(20, ...).

set.seed(2017);
rnorm(20, mean = 1, sd = 0.4);
#[1] 1.1843665 0.4939755 0.7252589 0.8217352 1.4896327 1.1439255 1.1603086
#[8] 1.0442731 0.7776635 1.7147653 1.1991402 0.2133531 1.2805424 0.8108834
#[15] 0.5728705 0.9128100 0.5895982 0.7084435 0.7499843 0.3253227

In your approach, you first draw one sample from a normal distribution, and then replicate the same number 20 times.


问:
Changing GitHub Account Swift Project
I would like to change a swift project from one GitHub account to another account. I want to commit the project to another account but I get an error - I assume I need to remove the .git file from the project but the answer here is not working for me. </p>

答:
Why do that?? No, all you have to do is define the new repo, push to it, then remove the other one. Each Git repo is on a local machine. That repository can be synced with one or more remote repositories. Right now, you probably have GitHub (account 1) setup as origin (a remote). What I would do is:

rename origin to oldrepo or something

create origin with the new url

push to it

Then you can remove the old one.

To edit your remotes, you can either do commands:

git remote remove origin, get remote add origin <newUrl>

or you can edit the .git/config file with an editor.

Git: Working with Remotes

Title: Changing GitHub Account Swift Project


问:
Azure linked services with data factory custom activity
Can't able to create linked services using Azure data factory (ADF),
I have read/write permission for linked services at ADF level.

```<code>using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.DataFactory;
using Microsoft.Azure.Management.DataFactory.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

LinkedServiceResource storageLinkedService = new
LinkedServiceResource(
new AzureStorageLinkedService
{
ConnectionString = new
SecureString("DefaultEndpointsProtocol=https;AccountName=" +
storageAccount + ";AccountKey=" + storageKey)
}
);
client.LinkedServices.CreateOrUpdate(resourceGroup,
dataFactoryName, storageLinkedServiceName, storageLinkedService);
</code>```

BTW I used both client credential as well as user credential

```<code>ClientCredential cc = new ClientCredential(applicationId,
authenticationKey);
var cc = new UserPasswordCredential(userName, password);
</code>```

Error Response for using Client credential:

```<code>Microsoft.Azure.Management.DataFactory.Models.ErrorResponseException:
Operation returned an invalid status code 'Forbidden'
at Microsoft.Azure.Management.DataFactory.LinkedServicesOperations.
<CreateOrUpdateWithHttpMessagesAsync>d__6.MoveNext() --- End of stack
trace from previous location where exception was thrown ---
</code>```

Error Response for using User credential:

```<code>System.Net.Http.HttpRequestException:  Response status code does not
indicate success: 401 (Unauthorized). --->
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException:
{"error":"invalid_client","error_description":"AADSTS70002: The
request body must contain the following parameter: 'client_secret or
client_assertion'.\r\nTrace ID: 2264d637-8786-4a40-96d4-
5d27b0670300\r\nCorrelation ID: fec688c8-bb92-49c2-86d3-
1e091181fe10\r\nTimestamp: 2017-11-29 05:30:23Z","error_codes":
[70002],"timestamp":"2017-11-29 05:30:23Z","trace_id":"2264d637-8786-
4a40-96d4-5d27b0670300","correlation_id":"fec688c8-bb92-49c2-86d3-
1e091181fe10"}: Unknown error
--- End of inner exception stack trace ---
</code>```

答:
Accoring to your exception, it seems that you use the resource owner flow from a a web client. A confidential client, such as a web App client, cannot use direct user credentials.

You would need to invoke it as a public client (native client app), not as a confidential client (web app/API). Please refer to this document for more about how to use ADAL,especially the Constraints & Limitations section

No web sites/confidential clients
  This is not an ADAL limitation, but an AAD setting. You can only use those flows from a native client. A confidential client, such as a web site, cannot use direct user credentials.

To access resources in your subscription, you need to assign role to the registried App.

Please have a try to use the following to get TokenCredentials, The following is the demo code to create inked services. It works correctly on my side. We also could refer to this document.

```<code> private static async Task<string> GetToken(string tenantId, string clientId, string secretKey)
        {
            var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
            ClientCredential clientCredential = new ClientCredential(clientId, secretKey);
            var tokenResponse = await context.AcquireTokenAsync("https://management.azure.com/", clientCredential);
            var accessToken = tokenResponse.AccessToken;
            return accessToken;
        }

        var token = GetToken(_tenantId, _clientId, _screctKey).Result;
        TokenCredentials credentials = new TokenCredentials(token);
        DataFactoryManagementClient client = new
        DataFactoryManagementClient(credentials) { SubscriptionId = subscriptionId };
        DataFactoryManagementClient client = new DataFactoryManagementClient(credentials) { SubscriptionId = subscriptionId };
        LinkedServiceResource storageLinkedService = new LinkedServiceResource(new AzureStorageLinkedService{
                     ConnectionString = new SecureString("DefaultEndpointsProtocol=https;AccountName=" + storageAccount + ";AccountKey=" + storageKey)});

       var result =client.LinkedServices.CreateOrUpdateWithHttpMessagesAsync(resourceGroup, factoryName, storageLinkedServiceName, storageLinkedService).Result;
</code>```

Body:
Can't able to create linked services using Azure data factory (ADF),
I have read/write permission for linked services at ADF level.

using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.DataFactory;
using Microsoft.Azure.Management.DataFactory.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

LinkedServiceResource storageLinkedService = new
LinkedServiceResource(
new AzureStorageLinkedService
{
ConnectionString = new
SecureString("DefaultEndpointsProtocol=https;AccountName=" +
storageAccount + ";AccountKey=" + storageKey)
}
);
client.LinkedServices.CreateOrUpdate(resourceGroup,
dataFactoryName, storageLinkedServiceName, storageLinkedService);

BTW I used both client credential as well as user credential

ClientCredential cc = new ClientCredential(applicationId,
authenticationKey);
var cc = new UserPasswordCredential(userName, password);

Error Response for using Client credential:

Microsoft.Azure.Management.DataFactory.Models.ErrorResponseException:
Operation returned an invalid status code 'Forbidden'
at Microsoft.Azure.Management.DataFactory.LinkedServicesOperations.
<CreateOrUpdateWithHttpMessagesAsync>d__6.MoveNext() --- End of stack
trace from previous location where exception was thrown ---

Error Response for using User credential:

System.Net.Http.HttpRequestException:  Response status code does not
indicate success: 401 (Unauthorized). --->
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException:
{"error":"invalid_client","error_description":"AADSTS70002: The
request body must contain the following parameter: 'client_secret or
client_assertion'.\r\nTrace ID: 2264d637-8786-4a40-96d4-
5d27b0670300\r\nCorrelation ID: fec688c8-bb92-49c2-86d3-
1e091181fe10\r\nTimestamp: 2017-11-29 05:30:23Z","error_codes":
[70002],"timestamp":"2017-11-29 05:30:23Z","trace_id":"2264d637-8786-
4a40-96d4-5d27b0670300","correlation_id":"fec688c8-bb92-49c2-86d3-
1e091181fe10"}: Unknown error
--- End of inner exception stack trace ---

Body:
Accoring to your exception, it seems that you use the resource owner flow from a a web client. A confidential client, such as a web App client, cannot use direct user credentials.

You would need to invoke it as a public client (native client app), not as a confidential client (web app/API). Please refer to this document for more about how to use ADAL,especially the Constraints & Limitations section

No web sites/confidential clients
  This is not an ADAL limitation, but an AAD setting. You can only use those flows from a native client. A confidential client, such as a web site, cannot use direct user credentials.

To access resources in your subscription, you need to assign role to the registried App.

Please have a try to use the following to get TokenCredentials, The following is the demo code to create inked services. It works correctly on my side. We also could refer to this document.

 private static async Task<string> GetToken(string tenantId, string clientId, string secretKey)
        {
            var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
            ClientCredential clientCredential = new ClientCredential(clientId, secretKey);
            var tokenResponse = await context.AcquireTokenAsync("https://management.azure.com/", clientCredential);
            var accessToken = tokenResponse.AccessToken;
            return accessToken;
        }

        var token = GetToken(_tenantId, _clientId, _screctKey).Result;
        TokenCredentials credentials = new TokenCredentials(token);
        DataFactoryManagementClient client = new
        DataFactoryManagementClient(credentials) { SubscriptionId = subscriptionId };
        DataFactoryManagementClient client = new DataFactoryManagementClient(credentials) { SubscriptionId = subscriptionId };
        LinkedServiceResource storageLinkedService = new LinkedServiceResource(new AzureStorageLinkedService{
                     ConnectionString = new SecureString("DefaultEndpointsProtocol=https;AccountName=" + storageAccount + ";AccountKey=" + storageKey)});

       var result =client.LinkedServices.CreateOrUpdateWithHttpMessagesAsync(resourceGroup, factoryName, storageLinkedServiceName, storageLinkedService).Result;


问:
Pros and cons of CUDA on Linux vs Windows?
I'm using both operating systems (Fedora 13 and Windows 7) for different purposes, but I'm going into GPU computing using CUDA C/C++. I've read about the Parallel Nsight plugin for Visual Studio and it seems like an amazing environment to develop in. However, Linux has always had a greater range of of tools and GPU supercomputers usually do use Linux. Anyway, I'd like to know the pros and cons from anyone whose used either or both of the platforms. In case anyone is wondering, it's a dual-boot system and I'm going to install a GTX 470 for GPU debugging into my extra PCI express slot. Please no flame wars...</p>

答:
If you are going to be using cuda code for production software, you might as well do it in the environment you are most friendly with.

But if you are looking at a performance point of view, and the time taken for a build, it would be best to use Linux (if you are comfortable with Make).


问:
This code compress a SQL file to zip using Php. I need to set password for the zip file produced
This code helps to make SQL file to a zip file in Php.

Here a SQL file is compressed to a zip file.

All I need is to set password for this.

Can I use PHP-java bridge to make this happen?

```<code>function dumpOutput() {
    if (!class_exists('ZipArchive')) {
        return array();
    }
    return array('zip' => 'ZIP');
}

function _zip($string, $state) {
    // ZIP can be created without temporary file by gzcompress - see PEAR File_Archive
    $this->data .= $string;
    if ($state & PHP_OUTPUT_HANDLER_END) {
        $zip = new ZipArchive;
        $zipFile = tempnam("", "zip");
        $zip->open($zipFile, ZipArchive::OVERWRITE); // php://output is not supported
        $zip->addFromString($this->filename, $this->data);
        $zip->close();
        $return = file_get_contents($zipFile);
        unlink($zipFile);
        return $return;
    }
    return "";
}
</code>```

答:
It seems that the ZipArchive Class doesn't support password setting. It only supports to open a password protected zip file.

See the following page for more details.
http://php.net/manual/zh/ziparchive.setpassword.php

Body:
This code helps to make SQL file to a zip file in Php.

Here a SQL file is compressed to a zip file.

All I need is to set password for this.

Can I use PHP-java bridge to make this happen?

function dumpOutput() {
    if (!class_exists('ZipArchive')) {
        return array();
    }
    return array('zip' => 'ZIP');
}

function _zip($string, $state) {
    // ZIP can be created without temporary file by gzcompress - see PEAR File_Archive
    $this->data .= $string;
    if ($state & PHP_OUTPUT_HANDLER_END) {
        $zip = new ZipArchive;
        $zipFile = tempnam("", "zip");
        $zip->open($zipFile, ZipArchive::OVERWRITE); // php://output is not supported
        $zip->addFromString($this->filename, $this->data);
        $zip->close();
        $return = file_get_contents($zipFile);
        unlink($zipFile);
        return $return;
    }
    return "";
}


问:
Netty Nio read the upcoming messages from ChannelFuture in Java
I am trying to use the following code which is an implementation of web sockets in Netty Nio. I have implment a JavaFx Gui and from the Gui I want to read the messages that are received from the Server or from other clients. The NettyClient code is like the following:

```<code>public static ChannelFuture callBack () throws Exception{

    String host = "localhost";
    int port = 8080;
    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new RequestDataEncoder(), new ResponseDataDecoder(),
                        new ClientHandler(i -> {
                            synchronized (lock) {
                                connectedClients = i;
                                lock.notifyAll();
                            }
                        }));
            }
        });
        ChannelFuture f = b.connect(host, port).sync();
        //f.channel().closeFuture().sync();

        return f;
    }
    finally {
        //workerGroup.shutdownGracefully();
    }
}

public static void main(String[] args) throws Exception {

    ChannelFuture ret;
    ClientHandler obj = new ClientHandler(i -> {
        synchronized (lock) {
            connectedClients = i;
            lock.notifyAll();
        }
    });
   ret = callBack();
        int connected = connectedClients;
    if (connected != 2) {
        System.out.println("The number if the connected clients is not two before locking");
        synchronized (lock) {
            while (true) {
                connected = connectedClients;
                if (connected == 2)
                    break;
                System.out.println("The number if the connected clients is not two");
                lock.wait();
            }
        }
    }
    System.out.println("The number if the connected clients is two: " + connected );
    ret.channel().read(); // can I use that from other parts of the code in order to read the incoming messages?
}
</code>```

How can I use the returned channelFuture from the callBack from other parts of my code in order to read the incoming messages? Do I need to call again callBack, or how can I received the updated message of the channel? Could I possible use from my code (inside a button event) something like ret.channel().read() (so as to take the last message)?

答:
By reading that code,the NettyClient is used to create connection(ClientHandler ),once connect done,ClientHandler.channelActive is called by Netty,if you want send data to server,you should put some code here. if this connection get message form server,  ClientHandler.channelRead is called by Netty, put your code to handle message.

You also need to read doc to know how netty encoder/decoder works.

How can I use the returned channelFuture from the callBack from other parts of my code in order to read the incoming messages?

share those ClientHandler created by NettyClient(NettyClient.java line 29)

Do I need to call again callBack, or how can I received the updated message of the channel?

if server message come,ClientHandler.channelRead is called.

Could I possible use from my code (inside a button event) something like ret.channel().read() (so as to take the last message)?

yes you could,but not a netty way,to play with netty,you write callbacks(when message come,when message sent ...),wait netty call your code,that is : the driver is netty,not you.

last,do you really need such a heavy library to do network?if not ,try This code,it simple,easy to understanding

Body:
I am trying to use the following code which is an implementation of web sockets in Netty Nio. I have implment a JavaFx Gui and from the Gui I want to read the messages that are received from the Server or from other clients. The NettyClient code is like the following:

public static ChannelFuture callBack () throws Exception{

    String host = "localhost";
    int port = 8080;
    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new RequestDataEncoder(), new ResponseDataDecoder(),
                        new ClientHandler(i -> {
                            synchronized (lock) {
                                connectedClients = i;
                                lock.notifyAll();
                            }
                        }));
            }
        });
        ChannelFuture f = b.connect(host, port).sync();
        //f.channel().closeFuture().sync();

        return f;
    }
    finally {
        //workerGroup.shutdownGracefully();
    }
}

public static void main(String[] args) throws Exception {

    ChannelFuture ret;
    ClientHandler obj = new ClientHandler(i -> {
        synchronized (lock) {
            connectedClients = i;
            lock.notifyAll();
        }
    });
   ret = callBack();
        int connected = connectedClients;
    if (connected != 2) {
        System.out.println("The number if the connected clients is not two before locking");
        synchronized (lock) {
            while (true) {
                connected = connectedClients;
                if (connected == 2)
                    break;
                System.out.println("The number if the connected clients is not two");
                lock.wait();
            }
        }
    }
    System.out.println("The number if the connected clients is two: " + connected );
    ret.channel().read(); // can I use that from other parts of the code in order to read the incoming messages?
}

How can I use the returned channelFuture from the callBack from other parts of my code in order to read the incoming messages? Do I need to call again callBack, or how can I received the updated message of the channel? Could I possible use from my code (inside a button event) something like ret.channel().read() (so as to take the last message)?


答:
Well it is because you are setting adapter after delay, try to set an empty adapter to recyclerview before you return rootView, then update adapter on Retrofit callback as in

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_inicio, container,
                false);
        getActivity().setTitle(R.string.inicio);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyvlerView.setAdapter(new CuponAdapter(new ArrayList<Cupon>()));
        loadJSON();
        return rootView;
    }
</code>```

Title: Troubles using fragment with RecyclerView and Retrofit

Body:
Well it is because you are setting adapter after delay, try to set an empty adapter to recyclerview before you return rootView, then update adapter on Retrofit callback as in

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_inicio, container,
                false);
        getActivity().setTitle(R.string.inicio);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyvlerView.setAdapter(new CuponAdapter(new ArrayList<Cupon>()));
        loadJSON();
        return rootView;
    }


问:
Error "The authenticity of host 'github.com' can't be established. RSA key fingerprint "
I use my project at work, but I would like to work with him from home as I can log into my home machine to work with my project.

However, from home, I see the following message:

```<code>The authenticity of host 'github.com (ip)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)?
</code>```

How can I get past it?

答:
You should simply be able to answer 'yes', which will update your ~/.ssh/known_hosts file.

A better approach, to avoid any MITM (Man-In-The-Middle) attack, would be (as commented below by Mamsds) to verify GitHub's public key first (see "GitHub's SSH key fingerprints") and, if you find a match, then you can answer 'yes'.

Example:

ssh-keyscan -t ecdsa github.com 2>&1 |ssh-keygen -lf -
256 SHA256:uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s github.com (ECDSA)
```
<hr />
<p>After that, you can use a GitHub SSH URL (provided you have generated the SSH public/private keys, and registered the public one to your GitHub profile)</p>
<p>Note: the ssh key generation should use the base64 old PEM format (option <code>-m PEM</code>), rather than the new current 70 chars OpenSSH one.<br />
See "What is the correct format for private key in Credentials":</p>
```ssh-keygen -m PEM -t rsa -P "" -f afile
```
<p>That or you can switch to an HTTPS URL.</p>
<hr />
<p>Update March 2023:</p>
<h1>GitHub updated their RSA SSH host key</h1>
<blockquote>
<p>At approximately 05:00 UTC on March 24, out of an abundance of caution, we replaced our RSA SSH host key used to secure Git operations for GitHub.com.</p>
<p>We did this to protect our users from any chance of an adversary impersonating GitHub or eavesdropping on their Git operations over SSH. This key does not grant access to GitHub’s infrastructure or customer data. This change only impacts Git operations over SSH using RSA.<br />
Web traffic to GitHub.com and HTTPS Git operations are not affected.</p>
<p>Only GitHub.com’s RSA SSH key was replaced. No change is required for ECDSA or Ed25519 users</p>
<p>If you see the following message when connecting to GitHub.com via SSH, then read onward.</p>
```@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
SHA256:uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s.
Please contact your system administrator.
Add correct host key in ~/.ssh/known_hosts to get rid of this message.
Host key for github.com has changed and you have requested strict > checking.
Host key verification failed.
```
<p>If you see the above message, you’ll need to remove the old key by running this command:</p>
```$ ssh-keygen -R github.com
```
<p>Or manually updating your ~/.ssh/known_hosts file to remove the old entry.</p>
<p>Then, you can manually add the following line to add the new RSA SSH public key entry to your <code>~/.ssh/known_hosts</code> file:</p>
```github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=
```
<p>Or automatically update GitHub.com’s RSA SSH key in your <code>~/.ssh/known_hosts</code>, by running the following in your terminal:</p>
<pre class="lang-bash prettyprint-override"><code>$ ssh-keygen -R github.com
$ curl -L https://api.github.com/meta | jq -r '.ssh_keys | .[]' | sed -e 's/^/github.com /' >> ~/.ssh/known_hosts
</code>```

You can verify that your hosts are connecting via our new RSA SSH key by confirming that you see the following fingerprint:

```<code>SHA256:uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s
</code>```

GitHub Actions users may see failed workflow runs if they are using actions/checkout with the ssh-key option.

We are updating the actions/checkout action in all our supported tags, including @v2, @v3, and @main.

If you pin the action to a commit SHA and use the ssh-key option, you’ll need to update your workflow. You can read more about this process in our official documentation for Actions security hardening.

For more information, please visit our official documentation on GitHub’s SSH public key fingerprints.

So:

What happened and what actions have we taken?

This week, we discovered that GitHub.com’s RSA SSH private key was briefly exposed in a public GitHub repository.

We immediately acted to contain the exposure and began investigating to understand the root cause and impact.

We have now completed the key replacement, and users will see the change propagate over the next thirty minutes.

Some users may have noticed that the new key was briefly present beginning around 02:30 UTC during preparations for this change.

Please note that this issue was not the result of a compromise of any GitHub systems or customer information.

Instead, the exposure was the result of what we believe to be an inadvertent publishing of private information. We have no reason to believe that the exposed key was abused, and took this action out of an abundance of caution.

As noted by bk2204'sanswer:

Some versions of OpenSSH include the host key for the IP address as well as for the hostname.

This is rather unhelpful, as IP addresses can change with DNS, but hostname tend to be more stable.

To remove the old key entirely:

# linux
sed -i -e '/AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31\/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi\/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==/d' ~/.ssh/known_hosts

# MacOS
sed -i '' -e '/AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31\/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi\/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==/d' ~/.ssh/known_hosts

# Windows
sed -i -e "/AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31\/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi\/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==/d" %USERPROFILE%\.ssh\known_hosts
```
<p>The last command (for Windows) can be done with the <code>%PATH%</code> modified with:</p>
<pre class="lang-bash prettyprint-override"><code>set "GH=%ProgramFiles%\Git"
set "PATH=%GH%\bin;%GH%\cmd;%GH%\usr\bin;%GH%\mingw64\bin;%GH%\mingw64\libexec\git-core;%PATH%"
</code>```

To remove any GitHub IP address from your known_hosts file, see discussion 50878:

For anyone running into repeated ECDSA host key for 'github.com' differs from the key for the IP address / Offending key for IP issues and you can't grep IPs in known_hosts because you have hashed entries, I have created a Gist listing all Github git IPv4 addresses (as of Fri Mar 24 16:33:22 UTC 2023), generated from CIDRs listed in https://api.github.com/meta:

https://gist.github.com/a-abella/fb31a028943b804e8ada6cda4efbe9b6

You can loop over these and feed them to ssh-keygen -R.

A script with optional known_hosts file path argument is available here: https://gist.github.com/a-abella/9d6c91a56a892e4c74933d17d380aa01. The only dependency is curl.

If you want a one-liner (though the standard you-shouldn't-pipe-scripts-from-the-internet warnings apply):

```<code>curl -s https://gist.githubusercontent.com/a-abella/9d6c91a56a892e4c74933d17d380aa01/raw/0bcaef131f94e4938cb659d744c3019fd814643e/strip_github.sh | bash -s -- $HOME/.ssh/known_hosts
</code>```

Body:
I use my project at work, but I would like to work with him from home as I can log into my home machine to work with my project.

However, from home, I see the following message:

The authenticity of host 'github.com (ip)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)?

How can I get past it?

Body:
You should simply be able to answer 'yes', which will update your ~/.ssh/known_hosts file.

A better approach, to avoid any MITM (Man-In-The-Middle) attack, would be (as commented below by Mamsds) to verify GitHub's public key first (see "GitHub's SSH key fingerprints") and, if you find a match, then you can answer 'yes'.

Example:

ssh-keyscan -t ecdsa github.com 2>&1 |ssh-keygen -lf -
256 SHA256:uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s github.com (ECDSA)

After that, you can use a GitHub SSH URL (provided you have generated the SSH public/private keys, and registered the public one to your GitHub profile)

Note: the ssh key generation should use the base64 old PEM format (option -m PEM), rather than the new current 70 chars OpenSSH one.

See "What is the correct format for private key in Credentials":

ssh-keygen -m PEM -t rsa -P "" -f afile

That or you can switch to an HTTPS URL.

Update March 2023:

GitHub updated their RSA SSH host key

At approximately 05:00 UTC on March 24, out of an abundance of caution, we replaced our RSA SSH host key used to secure Git operations for GitHub.com.

We did this to protect our users from any chance of an adversary impersonating GitHub or eavesdropping on their Git operations over SSH. This key does not grant access to GitHub’s infrastructure or customer data. This change only impacts Git operations over SSH using RSA.

Web traffic to GitHub.com and HTTPS Git operations are not affected.

Only GitHub.com’s RSA SSH key was replaced. No change is required for ECDSA or Ed25519 users

If you see the following message when connecting to GitHub.com via SSH, then read onward.

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
SHA256:uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s.
Please contact your system administrator.
Add correct host key in ~/.ssh/known_hosts to get rid of this message.
Host key for github.com has changed and you have requested strict > checking.
Host key verification failed.

If you see the above message, you’ll need to remove the old key by running this command:

$ ssh-keygen -R github.com

Or manually updating your ~/.ssh/known_hosts file to remove the old entry.

Then, you can manually add the following line to add the new RSA SSH public key entry to your ~/.ssh/known_hosts file:

github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=

Or automatically update GitHub.com’s RSA SSH key in your ~/.ssh/known_hosts, by running the following in your terminal:

$ ssh-keygen -R github.com
$ curl -L https://api.github.com/meta | jq -r '.ssh_keys | .[]' | sed -e 's/^/github.com /' >> ~/.ssh/known_hosts

You can verify that your hosts are connecting via our new RSA SSH key by confirming that you see the following fingerprint:

SHA256:uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s

GitHub Actions users may see failed workflow runs if they are using actions/checkout with the ssh-key option.

We are updating the actions/checkout action in all our supported tags, including @v2, @v3, and @main.

If you pin the action to a commit SHA and use the ssh-key option, you’ll need to update your workflow. You can read more about this process in our official documentation for Actions security hardening.

For more information, please visit our official documentation on GitHub’s SSH public key fingerprints.

So:

What happened and what actions have we taken?

This week, we discovered that GitHub.com’s RSA SSH private key was briefly exposed in a public GitHub repository.

We immediately acted to contain the exposure and began investigating to understand the root cause and impact.

We have now completed the key replacement, and users will see the change propagate over the next thirty minutes.

Some users may have noticed that the new key was briefly present beginning around 02:30 UTC during preparations for this change.

Please note that this issue was not the result of a compromise of any GitHub systems or customer information.

Instead, the exposure was the result of what we believe to be an inadvertent publishing of private information. We have no reason to believe that the exposed key was abused, and took this action out of an abundance of caution.

As noted by bk2204'sanswer:

Some versions of OpenSSH include the host key for the IP address as well as for the hostname.

This is rather unhelpful, as IP addresses can change with DNS, but hostname tend to be more stable.

To remove the old key entirely:

# linux
sed -i -e '/AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31\/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi\/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==/d' ~/.ssh/known_hosts

# MacOS
sed -i '' -e '/AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31\/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi\/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==/d' ~/.ssh/known_hosts

# Windows
sed -i -e "/AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31\/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi\/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==/d" %USERPROFILE%\.ssh\known_hosts

The last command (for Windows) can be done with the %PATH% modified with:

set "GH=%ProgramFiles%\Git"
set "PATH=%GH%\bin;%GH%\cmd;%GH%\usr\bin;%GH%\mingw64\bin;%GH%\mingw64\libexec\git-core;%PATH%"

To remove any GitHub IP address from your known_hosts file, see discussion 50878:

For anyone running into repeated ECDSA host key for 'github.com' differs from the key for the IP address / Offending key for IP issues and you can't grep IPs in known_hosts because you have hashed entries, I have created a Gist listing all Github git IPv4 addresses (as of Fri Mar 24 16:33:22 UTC 2023), generated from CIDRs listed in https://api.github.com/meta:

https://gist.github.com/a-abella/fb31a028943b804e8ada6cda4efbe9b6

You can loop over these and feed them to ssh-keygen -R.

A script with optional known_hosts file path argument is available here: https://gist.github.com/a-abella/9d6c91a56a892e4c74933d17d380aa01. The only dependency is curl.

If you want a one-liner (though the standard you-shouldn't-pipe-scripts-from-the-internet warnings apply):

curl -s https://gist.githubusercontent.com/a-abella/9d6c91a56a892e4c74933d17d380aa01/raw/0bcaef131f94e4938cb659d744c3019fd814643e/strip_github.sh | bash -s -- $HOME/.ssh/known_hosts


问:
What Perl modules are useful for validating subroutine arguments?
I'm looking for a general-purpose module to take the drudgery out of validating subroutine and method arguments. I've scanned through various possibilities on CPAN: Params::Validate, Params::Smart, Getargs::Mixed, Getargs::Long, and a few others.

Any information regarding pros and cons of these or other modules would be appreciated. Thanks.

答:
I am currently researching the same question as the O.P.

I noticed that Dave Rolsky - hyper-productive programmer of Moose fame - has recently (2009) taken over maintenance of Params::Validate, so I think this a good sign. The module has not been upgraded since 2003. So I guess, it still can be used again for checking subroutine params.


问:
scrape data from into dataframe with BeautifulSoup

I'm working on a project to scrape and parse data from California lottery into a dataframe

Here's my code so far, it produces no error but also no output:

```<code>import requests
from bs4 import BeautifulSoup as bs4

draw = 'http://www.calottery.com/play/draw-games/superlotto-plus/winning-numbers/?page=1'
page = requests.get(draw)
soup = bs4(page.text)

drawing_list = []

for table_row in soup.select("table.tag_even_numbers tr"):
    cells = table_row.findAll('td')

    if len(cells) > 0:
        draw_date = cells[0].text.strip()
        numbers = cells[1].text.strip()
        mega = cells[2].text.strip()

        drawings = {'dates': draw_date, 'winning_numbers': numbers, 'mega_number': mega}
        drawing_list.append(drawings)
        print "added {0} {1} {2}, to the list".format(draw_date, numbers, mega)
</code>```

Expected Output: I'd love to scrape the table rows into a dataframe

```<code>draw_date  | numbers        | mega
-----------|----------------|-----
12/06/2017 | 12 24 07 01 02 | 23
12/02/2017 | 33 18 07 42 40 | 7
</code>```

Thanks for any revision or assistance into the right direction.

答:
This expression "table.tag_even_numbers tr" selects nothing because the table has no 'tag_even_numbers' class, but has a 'tag_even' class and a 'numbers' class.

So if you change this:

```<code>soup.select("table.tag_even_numbers tr")
</code>```

to:

```<code>soup.select("table.tag_even.numbers tr")
</code>```

you should have 20 items in drawing_list.

Also by using .text to select numbers you get all the numbers joined side by side in a string.

If you want a list of numbers you should use .stripped_strings instead, eg:

```<code>numbers = list(cells[1].stripped_strings)
</code>```

Then you can create a dataframe from drawing_list, eg:

```<code>df = pd.DataFrame(drawing_list)
print(df.head())
</code>```

```<code>                 dates mega_number       winning_numbers
0   Dec 6, 2017 - 3201          23  [12, 24, 07, 01, 02]
1   Dec 2, 2017 - 3200           7  [33, 18, 07, 42, 40]
2  Nov 29, 2017 - 3199           6  [03, 33, 26, 27, 07]
3  Nov 25, 2017 - 3198          19  [21, 46, 13, 25, 17]
4  Nov 22, 2017 - 3197           3  [32, 40, 27, 42, 08]
</code>```

Body:
I'm working on a project to scrape and parse data from California lottery into a dataframe

Here's my code so far, it produces no error but also no output:

import requests
from bs4 import BeautifulSoup as bs4

draw = 'http://www.calottery.com/play/draw-games/superlotto-plus/winning-numbers/?page=1'
page = requests.get(draw)
soup = bs4(page.text)

drawing_list = []

for table_row in soup.select("table.tag_even_numbers tr"):
    cells = table_row.findAll('td')

    if len(cells) > 0:
        draw_date = cells[0].text.strip()
        numbers = cells[1].text.strip()
        mega = cells[2].text.strip()

        drawings = {'dates': draw_date, 'winning_numbers': numbers, 'mega_number': mega}
        drawing_list.append(drawings)
        print "added {0} {1} {2}, to the list".format(draw_date, numbers, mega)

Expected Output: I'd love to scrape the table rows into a dataframe

draw_date  | numbers        | mega
-----------|----------------|-----
12/06/2017 | 12 24 07 01 02 | 23
12/02/2017 | 33 18 07 42 40 | 7

Thanks for any revision or assistance into the right direction.

Body:
This expression "table.tag_even_numbers tr" selects nothing because the table has no 'tag_even_numbers' class, but has a 'tag_even' class and a 'numbers' class.

So if you change this:

soup.select("table.tag_even_numbers tr")

to:

soup.select("table.tag_even.numbers tr")

you should have 20 items in drawing_list.

Also by using .text to select numbers you get all the numbers joined side by side in a string.

If you want a list of numbers you should use .stripped_strings instead, eg:

numbers = list(cells[1].stripped_strings)

Then you can create a dataframe from drawing_list, eg:

df = pd.DataFrame(drawing_list)
print(df.head())

                 dates mega_number       winning_numbers
0   Dec 6, 2017 - 3201          23  [12, 24, 07, 01, 02]
1   Dec 2, 2017 - 3200           7  [33, 18, 07, 42, 40]
2  Nov 29, 2017 - 3199           6  [03, 33, 26, 27, 07]
3  Nov 25, 2017 - 3198          19  [21, 46, 13, 25, 17]
4  Nov 22, 2017 - 3197           3  [32, 40, 27, 42, 08]


问:
PLS-00103: Encountered the symbol ";" when expecting one of the following: <an identifier> <a d
I am trying to change the value of "TOTAL_TM_R_PT" where all the times a certain player shows up.

```<code>create or replace PROCEDURE CalculatePlayerTMPoints(Player IN NUMBER,PointNum IN NUMBER)
DECLARE PtValue INT;
UserNM TABLE;
BEGIN
    SELECT POINT_VALUE INTO PtValue FROM POINTS WHERE POINTS.POINT_ID = PointNum;
    SELECT ACCT_USERNAME INTO UserNM FROM ROSTERS WHERE ROSTERS.PLAYER_ID = Player;
    for i in 1..UserNM.count
    loop
        UPDATE TEAM_MANAGER_POINTS
        SET TOTAL_TM_R_PT = TOTAL_TM_R_PT + PtValue
        WHERE TEAM_MANAGER_POINTS.ACCT_USERNAME = UserNM;
    End loop;
END;
</code>```

This is my error:

```<code>Error(3,1): PLS-00103: Encountered the symbol "DECLARE" when expecting one of
the following:     ; is with authid as cluster order using external
deterministic parallel_enable pipelined result_cache    accessible
</code>```

Any ideas?

答:
You need to define a collection type and use BULK COLLECT INTO for storing query results in a collection. AS keyword was also missing in your code and using Declare is not valid.

```<code>create or replace PROCEDURE CalculatePlayerTMPoints(Player IN NUMBER,PointNum IN NUMBER) AS
PtValue INT;
TYPE usertype IS TABLE OF ROSTERS.ACCT_USERNAME%TYPE;
UserNM usertype ;
BEGIN
    SELECT POINT_VALUE INTO PtValue FROM POINTS WHERE POINTS.POINT_ID = PointNum;
    SELECT ACCT_USERNAME BULK COLLECT INTO UserNM FROM ROSTERS WHERE ROSTERS.PLAYER_ID = Player;
    for i in 1..UserNM.count
    loop
        UPDATE TEAM_MANAGER_POINTS
        SET TOTAL_TM_R_PT = TOTAL_TM_R_PT + PtValue
        WHERE  ACCT_USERNAME = UserNM(i);
    End loop;
END;
</code>```

Body:
I am trying to change the value of "TOTAL_TM_R_PT" where all the times a certain player shows up.

create or replace PROCEDURE CalculatePlayerTMPoints(Player IN NUMBER,PointNum IN NUMBER)
DECLARE PtValue INT;
UserNM TABLE;
BEGIN
    SELECT POINT_VALUE INTO PtValue FROM POINTS WHERE POINTS.POINT_ID = PointNum;
    SELECT ACCT_USERNAME INTO UserNM FROM ROSTERS WHERE ROSTERS.PLAYER_ID = Player;
    for i in 1..UserNM.count
    loop
        UPDATE TEAM_MANAGER_POINTS
        SET TOTAL_TM_R_PT = TOTAL_TM_R_PT + PtValue
        WHERE TEAM_MANAGER_POINTS.ACCT_USERNAME = UserNM;
    End loop;
END;

This is my error:

Error(3,1): PLS-00103: Encountered the symbol "DECLARE" when expecting one of
the following:     ; is with authid as cluster order using external
deterministic parallel_enable pipelined result_cache    accessible

Any ideas?

Body:
You need to define a collection type and use BULK COLLECT INTO for storing query results in a collection. AS keyword was also missing in your code and using Declare is not valid.

create or replace PROCEDURE CalculatePlayerTMPoints(Player IN NUMBER,PointNum IN NUMBER) AS
PtValue INT;
TYPE usertype IS TABLE OF ROSTERS.ACCT_USERNAME%TYPE;
UserNM usertype ;
BEGIN
    SELECT POINT_VALUE INTO PtValue FROM POINTS WHERE POINTS.POINT_ID = PointNum;
    SELECT ACCT_USERNAME BULK COLLECT INTO UserNM FROM ROSTERS WHERE ROSTERS.PLAYER_ID = Player;
    for i in 1..UserNM.count
    loop
        UPDATE TEAM_MANAGER_POINTS
        SET TOTAL_TM_R_PT = TOTAL_TM_R_PT + PtValue
        WHERE  ACCT_USERNAME = UserNM(i);
    End loop;
END;


问:
Recursively cycle every path of an array
I have the following(json) object:

```<code>$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);
</code>```

I'm trying to figure out how to recursively travel through it so I can see all the different paths that is in the array.

It could be 4 separate echo's or a 4 line string. The > could be replaced with anything or nothing at all. If each line was echo'd separately or pushed to an array that would probably give the most flexibility.

```<code>Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)
</code>```

I can't wrap my head around it so any help would be appreciated.

I'm thinking I can somehow cycle through each like:

```<code>foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}
</code>```

答:
This works for different depth of the array, check the live demo.

```<code>while(count($array) != count($array, 1))    // stop when $array is one dimension
{
    $temp = [];
    foreach($array as $k => $v)
    {
        if(is_array($v))
        {
            if(count($v) != count($v, 1))  // check if reached the inner most array
            {
                foreach($v as $kk => $vv)
                {
                    $temp[$k . ' - ' . $kk] = $vv;
                }
            }
            else
                $temp[$k] = '(' . implode($v, ', ') . ')';
        }else
            $temp[$k] = $v;
    }
    $array = $temp;
}

foreach($array as $k => $v)
    echo $k . ' - ' . $v . "\n";
</code>```

Note：

traverse array from outer to inner

traverse array from inner to outer

Body:
I have the following(json) object:

$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);

I'm trying to figure out how to recursively travel through it so I can see all the different paths that is in the array.

It could be 4 separate echo's or a 4 line string. The > could be replaced with anything or nothing at all. If each line was echo'd separately or pushed to an array that would probably give the most flexibility.

Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)

I can't wrap my head around it so any help would be appreciated.

I'm thinking I can somehow cycle through each like:

foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}

Body:
This works for different depth of the array, check the live demo.

while(count($array) != count($array, 1))    // stop when $array is one dimension
{
    $temp = [];
    foreach($array as $k => $v)
    {
        if(is_array($v))
        {
            if(count($v) != count($v, 1))  // check if reached the inner most array
            {
                foreach($v as $kk => $vv)
                {
                    $temp[$k . ' - ' . $kk] = $vv;
                }
            }
            else
                $temp[$k] = '(' . implode($v, ', ') . ')';
        }else
            $temp[$k] = $v;
    }
    $array = $temp;
}

foreach($array as $k => $v)
    echo $k . ' - ' . $v . "\n";

Note：

traverse array from outer to inner

traverse array from inner to outer


问:
Creating a dictionary with string,string, string,int and string,object
I am just getting started with C# and I'm a little stuck.

How do I create a dictionary that contains a mix of string,string, string,int, and string,object?

this is what it would look like:

```<code>var values = new Dictionary<????>
{
    "key0":
         {
         "key1": "stringValue1",
         "key2": "stringValue2",
         "key3": "stringValue3",
         "key4": 10000
         },
    "key5": "stringValue4",
    "key6": "stringValue5"
};
</code>```

I am using this as the body for a POST request. Sample code from here

```<code>var body = new FormUrlEncodedContent(values);

var url = "http://url.com/endpoint"

var resp = await client.PostAsync(url, body);

var respString = await response.Content.ReadAsStringAsync();
</code>```

答:
Check this link:

HttpClient PostAsJsonAsync request

You can cast it as

```<code>var myData = await response.Content.PostAsJsonAsync<Dictionary<string, dynamic>>(...);
</code>```

Then you can use it as:

```<code>string myStr = myData["key5"];
</code>```

Although I would recommend you make a class with the structure and use the class name within <>

Sample class:

```<code>class MyData {
    public MyData2 key0 { get; set; }
    public string key5 { get; set; }
    public string key6 { get; set; }
}

class MyData2 {
    public string key1 { get; set; }
    public string key2 { get; set; }
    public string key3 { get; set; }
    public int key4 { get; set; }
}
</code>```

Now you can use this as:

```<code> var myData = await response.Content.PostAsJsonAsync<MyData>(...);
</code>```

Body:
I am just getting started with C# and I'm a little stuck.

How do I create a dictionary that contains a mix of string,string, string,int, and string,object?

this is what it would look like:

var values = new Dictionary<????>
{
    "key0":
         {
         "key1": "stringValue1",
         "key2": "stringValue2",
         "key3": "stringValue3",
         "key4": 10000
         },
    "key5": "stringValue4",
    "key6": "stringValue5"
};

I am using this as the body for a POST request. Sample code from here

var body = new FormUrlEncodedContent(values);

var url = "http://url.com/endpoint"

var resp = await client.PostAsync(url, body);

var respString = await response.Content.ReadAsStringAsync();

Body:
Check this link:

HttpClient PostAsJsonAsync request

You can cast it as

var myData = await response.Content.PostAsJsonAsync<Dictionary<string, dynamic>>(...);

Then you can use it as:

string myStr = myData["key5"];

Although I would recommend you make a class with the structure and use the class name within <>

Sample class:

class MyData {
    public MyData2 key0 { get; set; }
    public string key5 { get; set; }
    public string key6 { get; set; }
}

class MyData2 {
    public string key1 { get; set; }
    public string key2 { get; set; }
    public string key3 { get; set; }
    public int key4 { get; set; }
}

Now you can use this as:

 var myData = await response.Content.PostAsJsonAsync<MyData>(...);


问:
CloudKit subscriptions and UNNotificationServiceExtension
So in iOS 10 you can now write notification service extensions that "intercept" push notifications so that you can download stuff and handle them before displaying them to the user.

However they require that the push payload has the 'mutable-content' key in aps set to 1. CloudKit subscriptions do not seem to return this key in the userInfo dictionary (At least CKDatabaseSubscription doesn't), and so the service extension doesn't get called.

Is there a way to get CloudKit subscription notifications to work with UNNotificationServiceExtensions?

答: This is now possible in iOS 11, look for the shouldSendMutableContent property in CKNotificationInfo