问:
Attempted to dequeue multiple cells for the same index path, which is not allowed
I have a very simple UITableView that has worked just fine since iOS6....I have recently tried to make a new build going from iOS10-iOS11 and now I am getting this new NSInternalConsistency Exception that I have never seen before, it literally came out of left field with the new iOS build....

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempted to dequeue
  multiple cells for the same index path, which is not allowed. If you
  really need to dequeue more cells than the table view is requesting,
  use the -dequeueReusableCellWithIdentifier: method (without an index
  path). Cell identifier: WorkOrderCell, index path:  {length = 2, path = 0 - 0}'

I have reviewed numerous tutorials and I feel like there is nothing exceptionally wrong with this code..in fact normal grid load works fine, here is my code:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"WorkOrderCell" forIndexPath:indexPath];

    // Configure the cell...  do some work, return it

    return cell;
}
</code>```

Has anyone else experienced this issue and what have you done to resolve it?

I should be a bit more specific, the normal UITableView does load fine, this specific issues is that I have a SearchBar, and when the user types into the search, I am filtering the results and displaying a results grid:

```<code>//Start Search/Filter Code
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"Job contains[cd] %@ or Address contains[cd] %@ or WorkOrderId contains[cd] %@ or Supervisor contains[cd] %@", searchText, searchText, searchText, searchText];
    self.filteredWorkOrders = [self.workOrders filteredArrayUsingPredicate:resultPredicate];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];

    return YES;
}
</code>```

The filter code itself works fine, it's just that it triggers the UITableView delegates to fire, which starts dequeuing cells (which should be empty right in the search results grid??)

In any event I could use some help with this one please.....

答:
Don't use self.tableView in your cellForRowAtIndexPath method (or any of the other data source and delegate methods). Use the tableView parameter.

This is really important when your data source and delegate methods are being used for more than one table view.

Body:
I have a very simple UITableView that has worked just fine since iOS6....I have recently tried to make a new build going from iOS10-iOS11 and now I am getting this new NSInternalConsistency Exception that I have never seen before, it literally came out of left field with the new iOS build....

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempted to dequeue
  multiple cells for the same index path, which is not allowed. If you
  really need to dequeue more cells than the table view is requesting,
  use the -dequeueReusableCellWithIdentifier: method (without an index
  path). Cell identifier: WorkOrderCell, index path:  {length = 2, path = 0 - 0}'

I have reviewed numerous tutorials and I feel like there is nothing exceptionally wrong with this code..in fact normal grid load works fine, here is my code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"WorkOrderCell" forIndexPath:indexPath];

    // Configure the cell...  do some work, return it

    return cell;
}

Has anyone else experienced this issue and what have you done to resolve it?

I should be a bit more specific, the normal UITableView does load fine, this specific issues is that I have a SearchBar, and when the user types into the search, I am filtering the results and displaying a results grid:

//Start Search/Filter Code
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"Job contains[cd] %@ or Address contains[cd] %@ or WorkOrderId contains[cd] %@ or Supervisor contains[cd] %@", searchText, searchText, searchText, searchText];
    self.filteredWorkOrders = [self.workOrders filteredArrayUsingPredicate:resultPredicate];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];

    return YES;
}

The filter code itself works fine, it's just that it triggers the UITableView delegates to fire, which starts dequeuing cells (which should be empty right in the search results grid??)

In any event I could use some help with this one please.....


来源: stackexchange

问:
Object is not being produced on calling [Symbol.iterator]()
This is this source code:

```<code>const james = {
    name: 'James',
    height: `5'10"`,
    weight: 185,
    [Symbol.iterator]:function*(){
    yield Object.keys(this) ;
    }
};
const iterator = james[Symbol.iterator]();
//
console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185
</code>```

The first call to iterator.next().value is supposed to print

```<code>{"value":"James","key":"name","done":false}
</code>```

but it is printing {"value":["name","height","weight"],"done":false}. How to resolve this?

答:
You yield all keys at once. Means that your first next do all work. All you need is to iterate over the keys and yield them in sequence.

const james = {
    name: 'James',
    height: `5'10"`,
    weight: 185,
    [Symbol.iterator]:function*(){
       for(let key of Object.keys(this)) {
          yield  { propValue: this[key], propName: key};
       }
    }
};

const iterator = james[Symbol.iterator]();

console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());```

ContentLicense: CC BY-SA 3.0

Body:
This is this source code:

const james = {
    name: 'James',
    height: `5'10"`,
    weight: 185,
    [Symbol.iterator]:function*(){
    yield Object.keys(this) ;
    }
};
const iterator = james[Symbol.iterator]();
//
console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185

The first call to iterator.next().value is supposed to print

{"value":"James","key":"name","done":false}

but it is printing {"value":["name","height","weight"],"done":false}. How to resolve this?


问:
Laravel policy for editing
So I have created a policy and registered it in the AuthServicePRovider, but it always returns false. It is my first time working with policies so I am sure I am doing it wrong, but following a few examples, nothing has worked for me.

I am logged in with user that has an id of 1. I try to edit a label that has a user_id of 1, returns false, and also when trying to edit a label that has a user_id of 2. This last one works as expected, but f the user_id and label->user_id match, I should ave a form displayed. Instead, I get this each time:

```<code>This action is unauthorized.
</code>```

Any ideas?

AuthServiceProvider: (Tried both but both don't work):

```<code>protected $policies = [
    'App\Label' => 'App\Policies\LabelPolicy'
];

And this one also did not do the trick:

protected $policies = [
    Label::class => LabelPolicy::class
];
</code>```

LabelsController@edit:

```<code>public function edit(Label $label)
{
    // $this->authorize('edit', $label); // This also returns false

    if (auth()->user()->cannot('edit', $label)) {
        dd('NO'); // This is always shown
    }
}
</code>```

LabelPolicy:

```<code>public function edit(Label $label)
{
    dd('test'); // This is never shown anywhere
    return auth()->user()->id === $label->user_id;
}
</code>```

答: if your $this->authorize inside Controllers always returns false, then double check if your model and model policy namespace was imported in AuthServiceProvider and also your model has been imported into your controller.</p>

Title: Laravel policy for editing

Body:
So I have created a policy and registered it in the AuthServicePRovider, but it always returns false. It is my first time working with policies so I am sure I am doing it wrong, but following a few examples, nothing has worked for me.

I am logged in with user that has an id of 1. I try to edit a label that has a user_id of 1, returns false, and also when trying to edit a label that has a user_id of 2. This last one works as expected, but f the user_id and label->user_id match, I should ave a form displayed. Instead, I get this each time:

This action is unauthorized.

Any ideas?

AuthServiceProvider: (Tried both but both don't work):

protected $policies = [
    'App\Label' => 'App\Policies\LabelPolicy'
];

And this one also did not do the trick:

protected $policies = [
    Label::class => LabelPolicy::class
];

LabelsController@edit:

public function edit(Label $label)
{
    // $this->authorize('edit', $label); // This also returns false

    if (auth()->user()->cannot('edit', $label)) {
        dd('NO'); // This is always shown
    }
}

LabelPolicy:

public function edit(Label $label)
{
    dd('test'); // This is never shown anywhere
    return auth()->user()->id === $label->user_id;
}


问:
GitHub fetch update the local repository but code results still for old code
I fetch the code from GitHub. The local repository is updated and same as one on the upstream. But when I run the code it brings the results of code before update? I am using git on eclipse  </p>

答:
When you have connected to a remote repository and you want the current files from the repo, you would do a pull.

For example, you have repository named "ClueGameDevelopment", and you want files from the "dev" branch, you would do:
git pull ClueGameDevelopment dev.

This would put all of the current files from the remote repository into your local repository.


问:
How to monitor GPS updates ONLY when Android device is moving
Once device has started to move, I want to start gps updates:

```<code>locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
</code>```

and as soon as device has stopped, I want to stop gps updates.

```<code>locationManager.removeUpdates(locationListener);
</code>```

How can I do it? What best approach?

答: While creating LocationRequest object add setSmallestDisplacement(10) where 10 meters is the minimum displacement that the device must travel to get location update.

Body:
Once device has started to move, I want to start gps updates:

locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

and as soon as device has stopped, I want to stop gps updates.

locationManager.removeUpdates(locationListener);

How can I do it? What best approach?

ContentLicense: CC BY-SA 4.0


问:
Can someone help with a rewrite rule for IIS?
I am using Helicon ISAPI_Rewrite and have entered the following Rewrite Rule:

RewriteRule /([^/?.]+) /MemberPages/OrderSupplies.aspx\?Name=$1 [NC,L]

However, I have little regex knowledge, and this rule almost works. However, here is my situation:

I want my visitors to be able to enter the following on the URL:

http://www.somedomain.com/UserName

and when they do, they get redirected to:

http://www.somedomain.com/MemberPages/OrderSupplies.aspx

The above rule, works, but I do not want the rule to fire if the UserName is a file.

For example the rule should NOT fire if the following is entered:

```
http://www.somedomain.com/Default.aspx
http://www.somedomain.com/login.aspx
http://www.somedomain.com/otherpage.aspx
```

The rule above strips out the '.' but I want to ignore any filenames, or any text with a '.'.

答:
I came up with the following:

```<code>RewriteEngine On
RewriteRule ^([^/?.]+)$ MemberPages/OrderSupplies.aspx?Name=$1 [NC,L]
</code>```

I'm not sure if you can specify the preceding / after the hostname or not in mod_rewrite. Also, you don't need to escape the ? in the replace string from what I know. But in any case if that doesn't work, try it the way you had it:

```<code>RewriteEngine On
RewriteRule ^([^/?.]+)$ /MemberPages/OrderSupplies.aspx\?Name=$1 [NC,L]
</code>```

So the general ^([^/?.]+)$ pattern states that from begin to end there can not be any ? or . or / characters.

ContentLicense: CC BY-SA 2.5

Body:
I am using Helicon ISAPI_Rewrite and have entered the following Rewrite Rule:

RewriteRule /([^/?.]+) /MemberPages/OrderSupplies.aspx\?Name=$1 [NC,L]

However, I have little regex knowledge, and this rule almost works. However, here is my situation:

I want my visitors to be able to enter the following on the URL:

http://www.somedomain.com/UserName

and when they do, they get redirected to:

http://www.somedomain.com/MemberPages/OrderSupplies.aspx

The above rule, works, but I do not want the rule to fire if the UserName is a file.

For example the rule should NOT fire if the following is entered:

http://www.somedomain.com/Default.aspx
http://www.somedomain.com/login.aspx
http://www.somedomain.com/otherpage.aspx

The rule above strips out the '.' but I want to ignore any filenames, or any text with a '.'.

Body:
I came up with the following:

RewriteEngine On
RewriteRule ^([^/?.]+)$ MemberPages/OrderSupplies.aspx?Name=$1 [NC,L]

I'm not sure if you can specify the preceding / after the hostname or not in mod_rewrite. Also, you don't need to escape the ? in the replace string from what I know. But in any case if that doesn't work, try it the way you had it:

RewriteEngine On
RewriteRule ^([^/?.]+)$ /MemberPages/OrderSupplies.aspx\?Name=$1 [NC,L]

So the general ^([^/?.]+)$ pattern states that from begin to end there can not be any ? or . or / characters.


问:
Bad request error 400 when submitting a form
I am getting Error Response 400 when submitting the form. I have a form which was working fine before i added a drop down list which displays gender to the user from DB. The Drop down is displaying the data correctly but when i am submitting the form i am getting an error. This only happened when i added the drop down list.

RegistrationController.java :-

```<code>@Controller
public class RegistrationController {
    final static Logger logger = Logger.getLogger(RegistrationController.class);
    private StaffService staffService;

    @Autowired
    private GenderDao genderDao;

    @Autowired
    public RegistrationController(StaffService staffService) {
        this.staffService = staffService;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/register")
    public String registerStaffPage(Model model) {
        List<Gender> genders = genderDao.findAll();
        Iterator<Gender> genderIterators = genders.iterator();
        Map<Gender, String> genderMap = new LinkedHashMap<Gender, String>();
        while (genderIterators.hasNext()) {
            Gender gender = genderIterators.next();
            genderMap.put(gender, gender.getGender());
        }
        model.addAttribute("gendersMap",genderMap);
        model.addAttribute("staffRegistrationBean", new StaffRegistrationBean());
        return "register";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/registerStaff")
    public String registerStaff(@ModelAttribute("staffRegistrationBean") StaffRegistrationBean staffRegistrationBean,
            @Valid StaffRegistrationBean staffRegistrationBeans, Errors errors, Model model) {
        // if (errors.hasErrors())
        // return "register";
        staffService.createStaff(staffRegistrationBean);
        return "RegistrationDone";
    }

    @PostConstruct
    public void init() {
        logger.debug("RegistrationController Bean has been Initialized.");
    }

    @PreDestroy
    public void destroy() {
        logger.debug("RegistrationController Bean has been Destroyed.");
    }
}
</code>```

StaffRegistrationBean.java

```<code>public class StaffRegistrationBean {
private String userName;
    private String password;
    private String firstName;
    private String lastName;
    private String email;
    private String Organization;
    private String phoneNo;
    private Gender gender;
    // getter and setter follows
}
</code>```

regsiter.jsp

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page isELIgnored="false"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration</title>
</head>
<body>
    <h1>Registration Form</h1>
    <form:form id="regForm" modelAttribute="staffRegistrationBean"
        action="registerStaff" method="post">
        <table>
            <tr>
                <td><form:label path="userName" cssErrorClass="error">
                        <spring:message code="userName" /> :
                    </form:label> <form:input path="userName" name="username" id="username"
                        cssErrorClass="error" /></td>
            </tr>
            <tr>
                <td>Gender: <form:select path="gender">
                        <form:options items="${gendersMap}" />
                    </form:select>
                </td>
            </tr>
            <tr>
                <td><form:label path="organization" cssErrorClass="error">
                        <spring:message code="organizationName" /> :
                    </form:label> <form:input path="organization" name="username" id="organization"
                        cssErrorClass="error" /></td>
            </tr>
            <tr>
                <td><form:label path="password" cssErrorClass="error">
                        <spring:message code="password" /> :
                    </form:label> <form:input path="password" name="password" id="password"
                        cssErrorClass="error" /></td>
            </tr>
            <tr>
                <td><form:label path="firstName" cssErrorClass="error">
                        <spring:message code="firstName" /> :
                    </form:label> <form:input path="firstName" name="firstname" id="firstname"
                        cssErrorClass="error" /></td>
            </tr>
            <tr>
                <td><form:label path="lastName" cssErrorClass="error">
                        <spring:message code="lastName" /> :
                    </form:label> <form:input path="lastName" name="lastname" id="lastname"
                        cssErrorClass="error" /></td>
            </tr>
            <%-- <tr>
                <td><form:label path="gender">
                        <spring:message code="gender" /> : </form:label>
                <td><form:select path="${gender}">
                        <form:options items="${genderList}" id="id" itemValue="gender">
                        </form:options>
                    </form:select></td>
            </tr> --%>
            <tr>
                <td><form:label path="email" cssErrorClass="error">
                        <spring:message code="email" /> :
                    </form:label> <form:input path="email" name="email" id="email"
                        cssErrorClass="error" /></td>
            </tr>
            <tr>
                <td><form:label path="phoneNo" cssErrorClass="error">
                        <spring:message code="phoneNo" /> :
                    </form:label> <form:input path="phoneNo" name="phoneNo" id="phoneNo"
                        cssErrorClass="error" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="register"></td>
            </tr>
        </table>
    </form:form>
</body>
</html>
</code>```

**

Error :-

**

HTTP Status 400 – Bad Request

Type Status Report

Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

GenderMap is a map that has the model to display on the screen. The key is Gender class and value is the gender description. The user will select a gender which will be referring to an id in the gender table.

The Entire code is available at - https://github.com/iftekharkhan09/ExpenseCalculator_Nex_Gen/tree/DevBranch

Go to the URL - localhost:8080/ExpenseCalculator/register

Any help will be highly appreciated.

答:
It happens when spring can't populate the ModelAttribute from HTML form.

staffRegistrationBean ModelAttribute can't convert Html's Gender attribute to your Gender object

Body:
I am getting Error Response 400 when submitting the form. I have a form which was working fine before i added a drop down list which displays gender to the user from DB. The Drop down is displaying the data correctly but when i am submitting the form i am getting an error. This only happened when i added the drop down list.

RegistrationController.java :-

@Controller
public class RegistrationController {
    final static Logger logger = Logger.getLogger(RegistrationController.class);
    private StaffService staffService;

    @Autowired
    private GenderDao genderDao;

    @Autowired
    public RegistrationController(StaffService staffService) {
        this.staffService = staffService;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/register")
    public String registerStaffPage(Model model) {
        List<Gender> genders = genderDao.findAll();
        Iterator<Gender> genderIterators = genders.iterator();
        Map<Gender, String> genderMap = new LinkedHashMap<Gender, String>();
        while (genderIterators.hasNext()) {
            Gender gender = genderIterators.next();
            genderMap.put(gender, gender.getGender());
        }
        model.addAttribute("gendersMap",genderMap);
        model.addAttribute("staffRegistrationBean", new StaffRegistrationBean());
        return "register";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/registerStaff")
    public String registerStaff(@ModelAttribute("staffRegistrationBean") StaffRegistrationBean staffRegistrationBean,
            @Valid StaffRegistrationBean staffRegistrationBeans, Errors errors, Model model) {
        // if (errors.hasErrors())
        // return "register";
        staffService.createStaff(staffRegistrationBean);
        return "RegistrationDone";
    }

    @PostConstruct
    public void init() {
        logger.debug("RegistrationController Bean has been Initialized.");
    }

    @PreDestroy
    public void destroy() {
        logger.debug("RegistrationController Bean has been Destroyed.");
    }
}

StaffRegistrationBean.java

public class StaffRegistrationBean {
private String userName;
    private String password;
    private String firstName;
    private String lastName;
    private String email;
    private String Organization;
    private String phoneNo;
    private Gender gender;
    // getter and setter follows
}

regsiter.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page isELIgnored="false"%>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration</title>

Registration Form

    <form:form id="regForm" modelAttribute="staffRegistrationBean"
        action="registerStaff" method="post">

                <form:label path="userName" cssErrorClass="error">
                        <spring:message code="userName" /> :
                    </form:label> <form:input path="userName" name="username" id="username"
                        cssErrorClass="error" />

                Gender: <form:select path="gender">
                        <form:options items="${gendersMap}" />
                    </form:select>

                <form:label path="organization" cssErrorClass="error">
                        <spring:message code="organizationName" /> :
                    </form:label> <form:input path="organization" name="username" id="organization"
                        cssErrorClass="error" />

                <form:label path="password" cssErrorClass="error">
                        <spring:message code="password" /> :
                    </form:label> <form:input path="password" name="password" id="password"
                        cssErrorClass="error" />

                <form:label path="firstName" cssErrorClass="error">
                        <spring:message code="firstName" /> :
                    </form:label> <form:input path="firstName" name="firstname" id="firstname"
                        cssErrorClass="error" />

                <form:label path="lastName" cssErrorClass="error">
                        <spring:message code="lastName" /> :
                    </form:label> <form:input path="lastName" name="lastname" id="lastname"
                        cssErrorClass="error" />

            <%--

                <form:label path="gender">
                        <spring:message code="gender" /> : </form:label>
                <form:select path="${gender}">
                        <form:options items="${genderList}" id="id" itemValue="gender">
                        </form:options>
                    </form:select>

 --%>

                <form:label path="email" cssErrorClass="error">
                        <spring:message code="email" /> :
                    </form:label> <form:input path="email" name="email" id="email"
                        cssErrorClass="error" />

                <form:label path="phoneNo" cssErrorClass="error">
                        <spring:message code="phoneNo" /> :
                    </form:label> <form:input path="phoneNo" name="phoneNo" id="phoneNo"
                        cssErrorClass="error" />

                <input type="submit" value="register">

    </form:form>

**

Error :-

**

HTTP Status 400 – Bad Request

Type Status Report

Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

GenderMap is a map that has the model to display on the screen. The key is Gender class and value is the gender description. The user will select a gender which will be referring to an id in the gender table.

The Entire code is available at - https://github.com/iftekharkhan09/ExpenseCalculator_Nex_Gen/tree/DevBranch

Go to the URL - localhost:8080/ExpenseCalculator/register

Any help will be highly appreciated.


问:
What is the correct way to take string from textarea and render it as html (email template preview)?
So in my app I'm trying to implement a component which allows the user to write html into a textarea. This html will be used for email templates, thus a preview of what the email would look like should be rendered below. I have a few ideas of how I can implement this, like simply taking the string and rendering it as innerHTML or I could also pass the html to the srcdoc property of an . Both solutions seem very crude to me, so I'm assuming there's a much better/cleaner way of implementing this kind of requirement that I'm simply not aware of. Could anyone guide me on how to do this correctly?

I'm working with Angular if that's of any help.

答:
You can add text area change event onchange and apply your input html to div as
html, refer below example.

html

```<code><textarea id='txtArea'> </textarea>
  <div id='preview'></div>
</code>```

Javascript

```<code> $(document).ready(function(){
      $('#txtArea').change(function(){
        $('#preview').html(this.value);
      });
    })
</code>```

here is jsbin demo https://jsbin.com/bojalo/edit?html,console,output

Body:
You can add text area change event onchange and apply your input html to div as
html, refer below example.

html

<textarea id='txtArea'> </textarea>
  <div id='preview'></div>

Javascript

 $(document).ready(function(){
      $('#txtArea').change(function(){
        $('#preview').html(this.value);
      });
    })

here is jsbin demo https://jsbin.com/bojalo/edit?html,console,output


问:
Iterating javascript object synchronously
I have an object like so:

```<code>let myObject = {
'db1': [db1_file1Id,db1_file2Id,db_1file3Id],
'db2': [db2_file1Id, db2_file2Id]
...
}
</code>```

I iterate through through this object and on each iteration: I connect to the database, retrieve the file, do some stuff and save the file back. Basically asynchronous stuff.

```<code>  for (let prop in myObject) {
    if (myObject.hasOwnProperty(prop)) {
      doStuff(prop, myObject[prop]);
    }
  }
</code>```

Now the doStuff function makes sure I have a local scope so there is no inconsistencies. But still, the execution is not synchronous due to the asynchronous operations inside each loop. I basically need one db to be completely processed before moving on to the next. How do I fix this?

One approach that I thought of was to have recursive loop. But as per my understanding, this would require me to change my data structure extensively which is sub-optimal imo.

```<code>let arr; //containing my data

process(x) {
 if (x < arr.length){
   //process(x+1) is called inside doStuff after asynchronous operations are complete
   doStuff(arr[x]);
 }
}
</code>```

答:
One solution would be to make doStuff return a Promise which you can use to build a chain of promises using calls to then.

The Bluebird promise library provides this functionality with .each and .mapSeries.

You could implement it as:

```<code>Promise.forEachSeries = function(array, action) {
  return array.reduce(function(prevPromise, value, index, array) {
    return prevPromise.then(function() {
      return action(value, index, array);
    });
  }, Promise.resolve());
}
</code>```

You would use it like this:

```<code>Promise.forEachSeries(arr, doStuff);
</code>```

Body:
I have an object like so:

let myObject = {
'db1': [db1_file1Id,db1_file2Id,db_1file3Id],
'db2': [db2_file1Id, db2_file2Id]
...
}

I iterate through through this object and on each iteration: I connect to the database, retrieve the file, do some stuff and save the file back. Basically asynchronous stuff.

  for (let prop in myObject) {
    if (myObject.hasOwnProperty(prop)) {
      doStuff(prop, myObject[prop]);
    }
  }

Now the doStuff function makes sure I have a local scope so there is no inconsistencies. But still, the execution is not synchronous due to the asynchronous operations inside each loop. I basically need one db to be completely processed before moving on to the next. How do I fix this?

One approach that I thought of was to have recursive loop. But as per my understanding, this would require me to change my data structure extensively which is sub-optimal imo.

let arr; //containing my data

process(x) {
 if (x < arr.length){
   //process(x+1) is called inside doStuff after asynchronous operations are complete
   doStuff(arr[x]);
 }
}

Body:
One solution would be to make doStuff return a Promise which you can use to build a chain of promises using calls to then.

The Bluebird promise library provides this functionality with .each and .mapSeries.

You could implement it as:

Promise.forEachSeries = function(array, action) {
  return array.reduce(function(prevPromise, value, index, array) {
    return prevPromise.then(function() {
      return action(value, index, array);
    });
  }, Promise.resolve());
}

You would use it like this:

Promise.forEachSeries(arr, doStuff);


问:
How to rotate an image before uploading, rotation not working as a variable
This function works perfectly when defining the rotation degrees in text such as "-90" but when I try to us the degrees parameter as a $variable the image does not rotate.  Any ideas? thanks in advance.</p>

```<code> function compress_image($source_url, $destination_url, $quality) {

    $info = getimagesize($source_url);

        if ($info['mime'] == 'image/jpeg')
                $image = imagecreatefromjpeg($source_url);

        elseif ($info['mime'] == 'image/gif')
                $image = imagecreatefromgif($source_url);

    elseif ($info['mime'] == 'image/png')
                $image = imagecreatefrompng($source_url);

                $rotate = imagerotate($image,"-90",0); //Does Work
                $degrees = "-90"
                $rotate = imagerotate($image,$degrees,0); //Does Not Work
                $image = $rotate;

        imagejpeg($image, $destination_url, $quality);
    return $destination_url;
}
</code>```

答:
I tried you code. You code works fine totally except there is a mistake at:

```<code>$degrees = "-90"
</code>```

It should be:

```<code>$degrees = "-90";
</code>```

Hope it helps.

Body:
This function works perfectly when defining the rotation degrees in text such as "-90" but when I try to us the degrees parameter as a $variable the image does not rotate.  Any ideas? thanks in advance.

 function compress_image($source_url, $destination_url, $quality) {

    $info = getimagesize($source_url);

        if ($info['mime'] == 'image/jpeg')
                $image = imagecreatefromjpeg($source_url);

        elseif ($info['mime'] == 'image/gif')
                $image = imagecreatefromgif($source_url);

    elseif ($info['mime'] == 'image/png')
                $image = imagecreatefrompng($source_url);

                $rotate = imagerotate($image,"-90",0); //Does Work
                $degrees = "-90"
                $rotate = imagerotate($image,$degrees,0); //Does Not Work
                $image = $rotate;

        imagejpeg($image, $destination_url, $quality);
    return $destination_url;
}

Body:
I tried you code. You code works fine totally except there is a mistake at:

$degrees = "-90"

It should be:

$degrees = "-90";

Hope it helps.


问:
Jenkins Pipeline building all branches simultaneously
I setup a simple Jenkinsfile that just echo a few steps.
I setup a new repo on Bitbucket (git) and two branches called master and develop.

When I commit something to master then both branches checkout and build in jenkins. Same behaviour on the develop branch.

Is it possible to limit only master to build in Jenkins once there is a commit to master branch? Similar behaviour to develop?

答:
I think you can use a temporary text file to save last successful build SHA ($LAST_SUCCESSFUL_BUILD_SHA) of each branch. Then, when having a new commit from the repo, we'll check which branch the commit comes from.

```<code>CURRENT_SHA=$(git rev-parse HEAD)

if [ $FORCE_REBUILD = true ] || [ $CURRENT_SHA != $LAST_SUCCESSFUL_BUILD_SHA ]; then
    echo "New commits available OR it was forced to build."
else
    echo "Already up-to-date. Skip build."
    curl -v -X POST --data "description=no changes, skip." ${JENKINS_BUILD_URL}submitDescription --user <username>:<password>
    curl -v -X POST ${BUILD_URL}stop --user <username>:<password>
    echo "Waiting for abort to take effect :D"
fi
</code>```

If the new commit comes from another branch, it's good to use Jenkins open API to skip the build.

I have applied this for my freestyle jobs but haven't tried with Jenkinsfile.

Body:
I think you can use a temporary text file to save last successful build SHA ($LAST_SUCCESSFUL_BUILD_SHA) of each branch. Then, when having a new commit from the repo, we'll check which branch the commit comes from.

CURRENT_SHA=$(git rev-parse HEAD)

if [ $FORCE_REBUILD = true ] || [ $CURRENT_SHA != $LAST_SUCCESSFUL_BUILD_SHA ]; then
    echo "New commits available OR it was forced to build."
else
    echo "Already up-to-date. Skip build."
    curl -v -X POST --data "description=no changes, skip." ${JENKINS_BUILD_URL}submitDescription --user <username>:<password>
    curl -v -X POST ${BUILD_URL}stop --user <username>:<password>
    echo "Waiting for abort to take effect :D"
fi

If the new commit comes from another branch, it's good to use Jenkins open API to skip the build.

I have applied this for my freestyle jobs but haven't tried with Jenkinsfile.


问:
Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path
net project in vs2010 i have a db and table inside the app_data folder, i have created a deployment package and have imported the package into an iis server that is installed on my local mechine.
now i get this error message while trying to preform an insertion.

Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path. Please make sure the user has a local user profile on the computer. The connection will be closed

the connection string is:

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\survey.mdf;Integrated Security=True;User Instance=True

when running it inside VS2010 it`s working fine.

how can i solve this probelm ?

答:
Remove the User Instance=True. You don't need RANU instances. Next, make sure the SQL Server Express service account had the proper needed rights on your app_data:

```<code>cacls <path\app_data> /E /T /G SQLServerMSSQLUser$<ComputerName>$SQLEXPRESS:F
</code>```

Body:
Remove the User Instance=True. You don't need RANU instances. Next, make sure the SQL Server Express service account had the proper needed rights on your app_data:

cacls <path\app_data> /E /T /G SQLServerMSSQLUser$<ComputerName>$SQLEXPRESS:F


问:
Azure pre-compiled Functions not available to Logic Apps
We are utilising visual studio 2017 and azure precompiled functions in VB.NET. All functions run successfully locally using the func.exe CLI tool. We can publish the Function App to Azure where we can see and test within the portal.

The problem exists when we try to use the functions as part of a logic app. We can add an action selecting Azure Functions and can see our function app, but none of the underlying functions are available/missing.

What am i missing?

Edit
I am using http triggers and web hooks.

Edit
It was indeed the custom routes

答:
I had a similar issue with logic app. some of my HttpTrigger functions worked fine and others not. I figured out that the only difference was the routing. functions that used custom routes did not show up in the logic app action selector. I've just removed the custom routes and everything work fines.

I've openned an issue here :

Discover HttpTrigger Functions from Logic App does not work with custom routes

**EDIT: **
Here is the answer from the Azure Team:

This is by design. As Functions with routes as the way the Azure Function is invoked from Logic Apps is via calling an API "list invoke URL." That URL will look something like https://function.azurewebsites.net/api/my/{custom}/route?code=123 and Logic App doesn't have a way to parse the route template. In other words we don't know what is static, and what should be replaced, and don't have a way to "replace" that with the native action.

You can get around it by providing an OpenAPI definition for the function and we will render the card based on the path parameters specified in swagger. Can also not use route if need to show in Logic Apps.


问:
How to display block an element and display in another div?
I have the youtube video and the video thumbnail. By default, videos are hidden.

I want to display related video on click the video thumbnail and display in the another div.

Below is my HTML:

```<code><ul id="result">
    <div class="testt-1">
        <h2 class="t1"> Name Tags </h2>
        <iframe id="video-1" width="220" height="115" src="http://www.youtube.com/embed/2vwBkTRDczc" style="display:none;"></iframe>
        <img id="img-1" src="https://img.youtube.com/vi/2vwBkTRDczc/0.jpg">
    </div>

    <div class="testt-2">
        <h2 class="t1"> Yak Chews </h2>
        <iframe id="video-2" width="220" height="115" src="http://www.youtube.com/embed/JQgFDi-vu1w" style="display:none;"></iframe>
        <img id="img-2" src="https://img.youtube.com/vi/JQgFDi-vu1w/0.jpg">
    </div>

    <div class="testt-3">
        <h2 class="t1"> tags </h2>
        <iframe id="video-3" width="220" height="115" src="http://www.youtube.com/embed/I1K3lrSsde4" style="display:none;"></iframe>
        <img id="img-3" src="https://img.youtube.com/vi/I1K3lrSsde4/0.jpg">
    </div>

    <div class="testt-4">
        <h2 class="t1"> Yak Chews Bone </h2>
        <iframe id="video-4" width="220" height="115" src="http://www.youtube.com/embed/yah872hDA8I" style="display:none;"></iframe>
        <img id="img-4" src="https://img.youtube.com/vi/yah872hDA8I/0.jpg">
    </div>

    <div class="testt-5">
        <h2 class="t1"> test </h2>
        <iframe id="video-5" width="220" height="115" src="http://www.youtube.com/embed/PJQbuIarVgA" style="display:none;"></iframe>
        <img id="img-5" src="https://img.youtube.com/vi/PJQbuIarVgA/0.jpg">
    </div>
</ul>

<div class="large-video" data-id="large-video"></div>
</code>```

Video and thumbnail are listing using for-each loop by PHP code.

答:
If you want to show the video if the image is clicked.

You can use:

```<code>$( "#result>div>img" ).click(function(){
    var vid = $(this).prev().attr( "src" );
    $( ".large-video" ).html( '<iframe width="220" height="115" src="' + vid + '"></iframe>' );
});
</code>```

Here is complete sample code:

$(document).ready(function(){
    $( "#result>div>img" ).click(function(){
     var vid = $(this).prev().attr( "src" );
     $( ".large-video" ).html( '' );
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul id="result">
    <div class="testt-1">
        <h2 class="t1"> Name Tags </h2>
        <iframe id="video-1" width="220" height="115" src="http://www.youtube.com/embed/2vwBkTRDczc" style="display:none;"></iframe>
        <img id="img-1" src="https://img.youtube.com/vi/2vwBkTRDczc/0.jpg">
    </div>

    <div class="testt-2">
        <h2 class="t1"> Yak Chews </h2>
        <iframe id="video-2" width="220" height="115" src="http://www.youtube.com/embed/JQgFDi-vu1w" style="display:none;"></iframe>
        <img id="img-2" src="https://img.youtube.com/vi/JQgFDi-vu1w/0.jpg">
    </div>

    <div class="testt-3">
        <h2 class="t1"> tags </h2>
        <iframe id="video-3" width="220" height="115" src="http://www.youtube.com/embed/I1K3lrSsde4" style="display:none;"></iframe>
        <img id="img-3" src="https://img.youtube.com/vi/I1K3lrSsde4/0.jpg">
    </div>

    <div class="testt-4">
        <h2 class="t1"> Yak Chews Bone </h2>
        <iframe id="video-4" width="220" height="115" src="http://www.youtube.com/embed/yah872hDA8I" style="display:none;"></iframe>
        <img id="img-4" src="https://img.youtube.com/vi/yah872hDA8I/0.jpg">
    </div>

    <div class="testt-5">
        <h2 class="t1"> test </h2>
        <iframe id="video-5" width="220" height="115" src="http://www.youtube.com/embed/PJQbuIarVgA" style="display:none;"></iframe>
        <img id="img-5" src="https://img.youtube.com/vi/PJQbuIarVgA/0.jpg">
    </div>
</ul>
<div class="large-video" data-id="large-video"></div></code>```

Body:
I have the youtube video and the video thumbnail. By default, videos are hidden.

I want to display related video on click the video thumbnail and display in the another div.

Below is my HTML:

 Name Tags

 Yak Chews

 tags

 Yak Chews Bone

 test

Video and thumbnail are listing using for-each loop by PHP code.

Body:
If you want to show the video if the image is clicked.

You can use:

$( "#result>div>img" ).click(function(){
    var vid = $(this).prev().attr( "src" );
    $( ".large-video" ).html( '<iframe width="220" height="115" src="' + vid + '"></iframe>' );
});

Here is complete sample code:

$(document).ready(function(){
    $( "#result>div>img" ).click(function(){
     var vid = $(this).prev().attr( "src" );
     $( ".large-video" ).html( '<iframe width="220" height="115" src="' + vid + '"></iframe>' );
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul id="result">
    <div class="testt-1">
        <h2 class="t1"> Name Tags </h2>
        <iframe id="video-1" width="220" height="115" src="http://www.youtube.com/embed/2vwBkTRDczc" style="display:none;"></iframe>
        <img id="img-1" src="https://img.youtube.com/vi/2vwBkTRDczc/0.jpg">
    </div>

    <div class="testt-2">
        <h2 class="t1"> Yak Chews </h2>
        <iframe id="video-2" width="220" height="115" src="http://www.youtube.com/embed/JQgFDi-vu1w" style="display:none;"></iframe>
        <img id="img-2" src="https://img.youtube.com/vi/JQgFDi-vu1w/0.jpg">
    </div>

    <div class="testt-3">
        <h2 class="t1"> tags </h2>
        <iframe id="video-3" width="220" height="115" src="http://www.youtube.com/embed/I1K3lrSsde4" style="display:none;"></iframe>
        <img id="img-3" src="https://img.youtube.com/vi/I1K3lrSsde4/0.jpg">
    </div>

    <div class="testt-4">
        <h2 class="t1"> Yak Chews Bone </h2>
        <iframe id="video-4" width="220" height="115" src="http://www.youtube.com/embed/yah872hDA8I" style="display:none;"></iframe>
        <img id="img-4" src="https://img.youtube.com/vi/yah872hDA8I/0.jpg">
    </div>

    <div class="testt-5">
        <h2 class="t1"> test </h2>
        <iframe id="video-5" width="220" height="115" src="http://www.youtube.com/embed/PJQbuIarVgA" style="display:none;"></iframe>
        <img id="img-5" src="https://img.youtube.com/vi/PJQbuIarVgA/0.jpg">
    </div>
</ul>
<div class="large-video" data-id="large-video"></div>


问:
How Do I Prevent Reload of UICollectionViewCells in cellForItemAt?
I have a CollectionViewController in which I contact an API to download images based on a set of coordinates. I call this code in the cellForItemAt function at which time it updates the cell's images in realtime with images from Flickr. This works fine.

However, when scrolling up or down, it recalls this code and updates the cells again, when I'd prefer that it look at the existing cells, identify if they have been filled, and simply not run this code.

I have tried implementing logic before the networking code that checks to see if the imageView.images already exist in a local struct I assign them to, but that doesn't seem to work correctly.

Is there a simple method to tell cellForItemAt "for cells where you already have images, don't look for more"?

Here is my current code:

```<code>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath as IndexPath) as! CollectionViewCell

        // Get images = using the URL
        FlickrClient.sharedInstance().getImagesFromFlickr(latitude: selectedPin.lat, longitude: selectedPin.lon, page: pageCount) { (pin, error) in

            if let pin = pin {
                let url = pin.images[indexPath.item].imageURL
                let data = try? Data(contentsOf: url)
                performUIUpdatesOnMain {
                    cell.imageView.image = UIImage(data: data!)
                    cell.imageView.contentMode = .scaleAspectFill
                }
            }
        }
    return cell
}
</code>```

答:
Use SDwebImage libray for loading images from url.

https://github.com/rs/SDWebImage

Call Something like this on cell for row :

```<code>let url = pin.images[indexPath.item].imageURL
cell.imageView.sd_setImage(with: url, placeholderImage: UIImage(named: "placeholder.png"))
</code>```

Body:
I have a CollectionViewController in which I contact an API to download images based on a set of coordinates. I call this code in the cellForItemAt function at which time it updates the cell's images in realtime with images from Flickr. This works fine.

However, when scrolling up or down, it recalls this code and updates the cells again, when I'd prefer that it look at the existing cells, identify if they have been filled, and simply not run this code.

I have tried implementing logic before the networking code that checks to see if the imageView.images already exist in a local struct I assign them to, but that doesn't seem to work correctly.

Is there a simple method to tell cellForItemAt "for cells where you already have images, don't look for more"?

Here is my current code:

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath as IndexPath) as! CollectionViewCell

        // Get images = using the URL
        FlickrClient.sharedInstance().getImagesFromFlickr(latitude: selectedPin.lat, longitude: selectedPin.lon, page: pageCount) { (pin, error) in

            if let pin = pin {
                let url = pin.images[indexPath.item].imageURL
                let data = try? Data(contentsOf: url)
                performUIUpdatesOnMain {
                    cell.imageView.image = UIImage(data: data!)
                    cell.imageView.contentMode = .scaleAspectFill
                }
            }
        }
    return cell
}

Body:
Use SDwebImage libray for loading images from url.

https://github.com/rs/SDWebImage

Call Something like this on cell for row :

let url = pin.images[indexPath.item].imageURL
cell.imageView.sd_setImage(with: url, placeholderImage: UIImage(named: "placeholder.png"))


问:
How to create a PDF of images stored in Google Cloud Storage?
I am sorry if this is a stupid question. I am very new to GCP.

For a web app, I need to create a PDF from images stored in Cloud Storage.

First, I tried to use a python package fpdf with files which are stored in Cloud Storage and see if this is possible.
Because images are stored online, I am using urllib2to fetch images.

Code:

```<code>from fpdf import FPDF
import urllib2
import os

imagelist = ["https://storage.googleapis.com/seventh-terrain-179700.appspot.com/excuses.jpg", "https://storage.googleapis.com/seventh-terrain-179700.appspot.com/excuses2.jpg"]

pdf = FPDF()
i = 0
for image in imagelist:
    image = urllib2.urlopen(image)

    # writing image files in current folder
    with open('image'+str(i)+'.jpg','wb') as output:
        output.write(image.read())

    pdf.add_page()
    pdf.image('image'+str(i)+'.jpg', 10, 10, 100, 100) # pdf.image(image,x,y,w,h)

    # removing images
    os.remove('image'+str(i)+'.jpg')
    i += 1

# Creating PDF in current folder
pdf.output("yourfile.pdf", "F")
</code>```

This words fine.

Then I tried deploying same code in local server:

```<code>import webapp2
from fpdf import FPDF
import urllib2
import os

pdf = FPDF()

class MainPage(webapp2.RequestHandler):
    def get(self):
        imagelist = ["https://storage.googleapis.com/seventh-terrain-179700.appspot.com/excuses.jpg", "https://storage.googleapis.com/seventh-terrain-179700.appspot.com/excuses2.jpg"]

        pdf = FPDF()
        i = 0
        for image in imagelist:
            image = urllib2.urlopen(image)

            with open('image'+str(i)+'.jpg','wb') as output:
                output.write(image.read())

            pdf.add_page()
            pdf.image('image'+str(i)+'.jpg', 10, 10, 100, 100) # pdf.image(image,x,y,w,h)

            os.remove('image'+str(i)+'.jpg')
            i += 1

        pdf.output("yourfile.pdf", "F")

application = webapp2.WSGIApplication([('/', MainPage)],
                                      debug=True)
</code>```

But, I am getting error:

```<code>WARNING  2017-12-08 19:21:56,184 sandbox.py:1082] The module _winreg is whitelisted for local dev only. If your application relies on _winreg, it is likely that it will not function properly in production.
WARNING  2017-12-08 14:21:56,190 urlfetch_stub.py:551] Stripped prohibited headers from URLFetch request: ['Host']
ERROR    2017-12-08 19:21:57,332 webapp2.py:1528] [Errno 30] Read-only file system: 'image0.jpg'
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1511, in __call__
    rv = self.handle_exception(request, response, e)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1505, in __call__
    rv = self.router.dispatch(request, response)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1253, in default_dispatcher
    return route.handler_adapter(request, response)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1077, in __call__
    return handler.dispatch()
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 547, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 545, in dispatch
    return method(*args, **kwargs)
  File "C:\MyMiniGCPProjects\FPDF\main.py", line 23, in get
    with open('image'+str(i)+'.jpg','wb') as output:
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\python\runtime\stubs.py", line 278, in __init__
    raise IOError(errno.EROFS, 'Read-only file system', filename)
IOError: [Errno 30] Read-only file system: 'image0.jpg'
ERROR    2017-12-08 19:21:57,339 wsgi.py:279]
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 267, in Handle
    result = handler(dict(self._environ), self._StartResponse)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1519, in __call__
    response = self._internal_error(e)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1511, in __call__
    rv = self.handle_exception(request, response, e)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1505, in __call__
    rv = self.router.dispatch(request, response)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1253, in default_dispatcher
    return route.handler_adapter(request, response)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1077, in __call__
    return handler.dispatch()
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 547, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 545, in dispatch
    return method(*args, **kwargs)
  File "C:\MyMiniGCPProjects\FPDF\main.py", line 23, in get
    with open('image'+str(i)+'.jpg','wb') as output:
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\python\runtime\stubs.py", line 278, in __init__
    raise IOError(errno.EROFS, 'Read-only file system', filename)
IOError: [Errno 30] Read-only file system: 'image0.jpg'
</code>```

I am not able to find any solution that works.
Is there a way to use files directly from Cloud Storage and also save PDF in Cloud Storage?

答:
You're hitting one of the sandbox restrictions. From The sandbox:

An App Engine application cannot:

write to the filesystem. Applications must use Cloud Datastore for storing persistent data. Reading from the filesystem is allowed,
  and all application files uploaded with the application are available.

Well, the note about the datastore is actually misleading, there are several storage options, best for your case is IMHO the Cloud Storage (GCS).

But you can't write a file to GCS using the regular open(), you nede to use the GCS client library for it. You can find an example here: Write a CSV to store in Google Cloud Storage

Body:
I am sorry if this is a stupid question. I am very new to GCP.

For a web app, I need to create a PDF from images stored in Cloud Storage.

First, I tried to use a python package fpdf with files which are stored in Cloud Storage and see if this is possible.
Because images are stored online, I am using urllib2to fetch images.

Code:

from fpdf import FPDF
import urllib2
import os

imagelist = ["https://storage.googleapis.com/seventh-terrain-179700.appspot.com/excuses.jpg", "https://storage.googleapis.com/seventh-terrain-179700.appspot.com/excuses2.jpg"]

pdf = FPDF()
i = 0
for image in imagelist:
    image = urllib2.urlopen(image)

    # writing image files in current folder
    with open('image'+str(i)+'.jpg','wb') as output:
        output.write(image.read())

    pdf.add_page()
    pdf.image('image'+str(i)+'.jpg', 10, 10, 100, 100) # pdf.image(image,x,y,w,h)

    # removing images
    os.remove('image'+str(i)+'.jpg')
    i += 1

# Creating PDF in current folder
pdf.output("yourfile.pdf", "F")

This words fine.

Then I tried deploying same code in local server:

import webapp2
from fpdf import FPDF
import urllib2
import os

pdf = FPDF()

class MainPage(webapp2.RequestHandler):
    def get(self):
        imagelist = ["https://storage.googleapis.com/seventh-terrain-179700.appspot.com/excuses.jpg", "https://storage.googleapis.com/seventh-terrain-179700.appspot.com/excuses2.jpg"]

        pdf = FPDF()
        i = 0
        for image in imagelist:
            image = urllib2.urlopen(image)

            with open('image'+str(i)+'.jpg','wb') as output:
                output.write(image.read())

            pdf.add_page()
            pdf.image('image'+str(i)+'.jpg', 10, 10, 100, 100) # pdf.image(image,x,y,w,h)

            os.remove('image'+str(i)+'.jpg')
            i += 1

        pdf.output("yourfile.pdf", "F")

application = webapp2.WSGIApplication([('/', MainPage)],
                                      debug=True)

But, I am getting error:

WARNING  2017-12-08 19:21:56,184 sandbox.py:1082] The module _winreg is whitelisted for local dev only. If your application relies on _winreg, it is likely that it will not function properly in production.
WARNING  2017-12-08 14:21:56,190 urlfetch_stub.py:551] Stripped prohibited headers from URLFetch request: ['Host']
ERROR    2017-12-08 19:21:57,332 webapp2.py:1528] [Errno 30] Read-only file system: 'image0.jpg'
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1511, in __call__
    rv = self.handle_exception(request, response, e)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1505, in __call__
    rv = self.router.dispatch(request, response)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1253, in default_dispatcher
    return route.handler_adapter(request, response)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1077, in __call__
    return handler.dispatch()
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 547, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 545, in dispatch
    return method(*args, **kwargs)
  File "C:\MyMiniGCPProjects\FPDF\main.py", line 23, in get
    with open('image'+str(i)+'.jpg','wb') as output:
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\python\runtime\stubs.py", line 278, in __init__
    raise IOError(errno.EROFS, 'Read-only file system', filename)
IOError: [Errno 30] Read-only file system: 'image0.jpg'
ERROR    2017-12-08 19:21:57,339 wsgi.py:279]
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 267, in Handle
    result = handler(dict(self._environ), self._StartResponse)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1519, in __call__
    response = self._internal_error(e)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1511, in __call__
    rv = self.handle_exception(request, response, e)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1505, in __call__
    rv = self.router.dispatch(request, response)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1253, in default_dispatcher
    return route.handler_adapter(request, response)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 1077, in __call__
    return handler.dispatch()
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 547, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.3\webapp2.py", line 545, in dispatch
    return method(*args, **kwargs)
  File "C:\MyMiniGCPProjects\FPDF\main.py", line 23, in get
    with open('image'+str(i)+'.jpg','wb') as output:
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\python\runtime\stubs.py", line 278, in __init__
    raise IOError(errno.EROFS, 'Read-only file system', filename)
IOError: [Errno 30] Read-only file system: 'image0.jpg'

I am not able to find any solution that works.
Is there a way to use files directly from Cloud Storage and also save PDF in Cloud Storage?


问:
type error with LabelEncoder.fit_transform()
I was playing with the Titanic dataset on Kaggle (https://www.kaggle.com/c/titanic/data), and I want to use LabelEncoder from sklearn.preprocessing to transform Sex, originally labeled as 'male' or 'female' into '0' or '1'. I had the following four lines of code,

```<code>import pandas as pd
from sklearn.preprocessing import LabelEncoder
df = pd.read_csv('titanic.csv')
df['Sex'] = LabelEncoder.fit_transform(df['Sex'])
</code>```

But when I ran it I received the following error message:

```<code>TypeError: fit_transform() missing 1 required positional argument: 'y'
</code>```

the error comes from line 4, i.e.,

```<code>df['Sex'] = LabelEncoder.fit_transform(df['Sex'])
</code>```

I wonder what went wrong here. Although I know I could also do the transformation using map, which might be even simpler, but I still want to know what's wrong with my usage of LabelEncoder.

答:
You're just missing the () which initializes a LabelEncoder instance.

This will work: LabelEncoder().fit_transform(df['Sex'])

Having said that, 0p3n5ourcE's example is more conventional, and also a cleaner way to handle objects.

Body:
I was playing with the Titanic dataset on Kaggle (https://www.kaggle.com/c/titanic/data), and I want to use LabelEncoder from sklearn.preprocessing to transform Sex, originally labeled as 'male' or 'female' into '0' or '1'. I had the following four lines of code,

import pandas as pd
from sklearn.preprocessing import LabelEncoder
df = pd.read_csv('titanic.csv')
df['Sex'] = LabelEncoder.fit_transform(df['Sex'])

But when I ran it I received the following error message:

TypeError: fit_transform() missing 1 required positional argument: 'y'

the error comes from line 4, i.e.,

df['Sex'] = LabelEncoder.fit_transform(df['Sex'])

I wonder what went wrong here. Although I know I could also do the transformation using map, which might be even simpler, but I still want to know what's wrong with my usage of LabelEncoder.


问:
Confirm internet data connection before making Firestore Query
I have the following situation:

The application has the option to like the posts of a user. And also has a Dislike option.

It is working properly when it is on a wifi or mobile network (with online connection).

Problem:

When the network is mobile, it is often connected but has no data transmission and does not work. It is a geographical and operator problem in certain locations in the country.

So it's taking a long time for the Like option to have its effect for either Like or DisLike.

Code:

```<code>@Override
    public void onLikeSelected(final DocumentSnapshot like) {

        if (checkConnection()){

            final String idCurrentUser = mCurrentUser.getUid();

            Task<QuerySnapshot> query = mDb.collection("Postagens").document(like.getId()).collection("Likes").whereEqualTo("id_userLike", idCurrentUser)
                    .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                        @Override
                        public void onSuccess(QuerySnapshot documentSnapshots) {

                            if(documentSnapshots.size() == 0) {

                                Map<String, Object> dado_usuario = new HashMap<>();
                                dado_usuario.put("id_userLike", mCurrentUser.getUid());
                                dado_usuario.put("timestamp", FieldValue.serverTimestamp());

                                mDb.collection("Postagens").document(like.getId()).collection("Likes").document(idCurrentUser).set(dado_usuario).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {

                                    }
                                });

                            } else { //utilizando else

                                mDb.collection("Postagens").document(like.getId()).collection("Likes").document(idCurrentUser).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {

                                    }
                                });

                            }

                        }
                    });

        } else {

            Toast.makeText(getActivity(), "Not Connection", Toast.LENGTH_SHORT).show();
        }

}

 public  boolean checkConnection() {
        boolean conectado;
        ConnectivityManager conectivtyManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conectivtyManager.getActiveNetworkInfo() != null
                && conectivtyManager.getActiveNetworkInfo().isAvailable()
                && conectivtyManager.getActiveNetworkInfo().isConnected()) {
            conectado = true;
        } else {
            conectado = false;
        }
        return conectado;
}
</code>```

How can I do this when the mobile connection is bad or weak

I do not know if it would be the case of handling the data connection or changing the treatment of the Like (onLikeSelected()) option in the Firestore Database.

Thanks!!

答:
A simple approch will be use the following method:</p>

```<code>public boolean isInternetAvailable() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process process = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = process.waitFor();
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    return false;
}
</code>```

Body:
I have the following situation:

The application has the option to like the posts of a user. And also has a Dislike option.

It is working properly when it is on a wifi or mobile network (with online connection).

Problem:

When the network is mobile, it is often connected but has no data transmission and does not work. It is a geographical and operator problem in certain locations in the country.

So it's taking a long time for the Like option to have its effect for either Like or DisLike.

Code:

@Override
    public void onLikeSelected(final DocumentSnapshot like) {

        if (checkConnection()){

            final String idCurrentUser = mCurrentUser.getUid();

            Task<QuerySnapshot> query = mDb.collection("Postagens").document(like.getId()).collection("Likes").whereEqualTo("id_userLike", idCurrentUser)
                    .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                        @Override
                        public void onSuccess(QuerySnapshot documentSnapshots) {

                            if(documentSnapshots.size() == 0) {

                                Map<String, Object> dado_usuario = new HashMap<>();
                                dado_usuario.put("id_userLike", mCurrentUser.getUid());
                                dado_usuario.put("timestamp", FieldValue.serverTimestamp());

                                mDb.collection("Postagens").document(like.getId()).collection("Likes").document(idCurrentUser).set(dado_usuario).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {

                                    }
                                });

                            } else { //utilizando else

                                mDb.collection("Postagens").document(like.getId()).collection("Likes").document(idCurrentUser).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {

                                    }
                                });

                            }

                        }
                    });

        } else {

            Toast.makeText(getActivity(), "Not Connection", Toast.LENGTH_SHORT).show();
        }

}

 public  boolean checkConnection() {
        boolean conectado;
        ConnectivityManager conectivtyManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conectivtyManager.getActiveNetworkInfo() != null
                && conectivtyManager.getActiveNetworkInfo().isAvailable()
                && conectivtyManager.getActiveNetworkInfo().isConnected()) {
            conectado = true;
        } else {
            conectado = false;
        }
        return conectado;
}

How can I do this when the mobile connection is bad or weak

I do not know if it would be the case of handling the data connection or changing the treatment of the Like (onLikeSelected()) option in the Firestore Database.

Thanks!!

Body:
A simple approch will be use the following method:

public boolean isInternetAvailable() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process process = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = process.waitFor();
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    return false;
}


问:
Simulate keyboard on another web page from my web page?
I would like to display another web page within a web page... maybe using framnes, then be able to simulate mouse clicks/keyboard input randomally on this new page that is within my page.

Is this possible using asp.net/ javascript or any language. asp.net preferred

Thanks for any input

答:
I dont think it is possible on client. If you are creating a desktop application then may be it could have been done like in automation, but on clint side even javascript cant create events like mouse clicks, it can only handle such events. however you can insert text in text boxes by traversing and accessing DOM in your javascript.

Its Definitely not possible from Server side in ASP.Net


问:
Nodejs - parsing json retrieved from web

I'm trying to parse a json retrieved from the web (https://api.coinmarketcap.com/v1/ticker/?limit=3) and be able to select the name and price_usd. For reference:

```<code>[
{
    "id": "bitcoin",
    "name": "Bitcoin",
    "symbol": "BTC",
    "rank": "1",
    "price_usd": "16148.3",
    "price_btc": "1.0",
    "24h_volume_usd": "18799600000.0",
    "market_cap_usd": "270147332945",
    "available_supply": "16729150.0",
    "total_supply": "16729150.0",
    "max_supply": "21000000.0",
    "percent_change_1h": "-0.28",
    "percent_change_24h": "-4.64",
    "percent_change_7d": "45.79",
    "last_updated": "1512792553"
},
{
    "id": "ethereum",
    "name": "Ethereum",
    "symbol": "ETH",
    "rank": "2",
    "price_usd": "471.833",
    "price_btc": "0.0296001",
    "24h_volume_usd": "2170950000.0",
    "market_cap_usd": "45401368016.0",
    "available_supply": "96223384.0",
    "total_supply": "96223384.0",
    "max_supply": null,
    "percent_change_1h": "0.01",
    "percent_change_24h": "9.29",
    "percent_change_7d": "0.65",
    "last_updated": "1512792556"
},
{
    "id": "bitcoin-cash",
    "name": "Bitcoin Cash",
    "symbol": "BCH",
    "rank": "3",
    "price_usd": "1510.48",
    "price_btc": "0.094759",
    "24h_volume_usd": "2229320000.0",
    "market_cap_usd": "25444318815.0",
    "available_supply": "16845188.0",
    "total_supply": "16845188.0",
    "max_supply": "21000000.0",
    "percent_change_1h": "0.6",
    "percent_change_24h": "1.29",
    "percent_change_7d": "2.64",
    "last_updated": "1512792581"
    }
]
</code>```

Here's the code I currently have:

```<code>var url = 'https://api.coinmarketcap.com/v1/ticker/?limit=3';
var dataResponse = '';
var body = '';

function retrieveData() {
    https.get(url, function(res){
        body = '';

        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            dataResponse = JSON.parse(body);
        });

    }).on('error', function(e) {
          console.log("Error: ", e);
    });

}

retrieveData();

var temp = (dataResponse[0]);

console.log(temp);
</code>```

I want to be able to get something like and be able to select the name and price:

```<code>        "id": "bitcoin",
        "name": "Bitcoin",
        "symbol": "BTC",
        "rank": "1",
        "price_usd": "16148.3",
        "price_btc": "1.0",
        "24h_volume_usd": "18799600000.0",
        "market_cap_usd": "270147332945",
        "available_supply": "16729150.0",
        "total_supply": "16729150.0",
        "max_supply": "21000000.0",
        "percent_change_1h": "-0.28",
        "percent_change_24h": "-4.64",
        "percent_change_7d": "45.79",
        "last_updated": "1512792553"
</code>```

The error I get is that it logs an undefined. I'm not sure what I'm doing wrong. How would I go selecting the name also? Would I split each block into an array and select them by indexing?

答:
So I think you're already there, all ya need to do is log the "dataResponse" to console. Since "dataResponse" is an array of objects, you can simply output the objects to the console with simple javascript. This is how it'd look like: </p>

<p>```</p>

```<code>var https = require ("https")

var url = 'https://api.coinmarketcap.com/v1/ticker/?limit=3';

function retrieveData () {
    https.get (url, function (res){
        body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            dataResponse = JSON.parse (body);
            console.log (dataResponse[0])
        });

    }).on ('error', function (e) {
          console.log ("Error: ", e);
    });

}

retrieveData ()
</code>```

<p>```</p>

Body:
I'm trying to parse a json retrieved from the web (https://api.coinmarketcap.com/v1/ticker/?limit=3) and be able to select the name and price_usd. For reference:

[
{
    "id": "bitcoin",
    "name": "Bitcoin",
    "symbol": "BTC",
    "rank": "1",
    "price_usd": "16148.3",
    "price_btc": "1.0",
    "24h_volume_usd": "18799600000.0",
    "market_cap_usd": "270147332945",
    "available_supply": "16729150.0",
    "total_supply": "16729150.0",
    "max_supply": "21000000.0",
    "percent_change_1h": "-0.28",
    "percent_change_24h": "-4.64",
    "percent_change_7d": "45.79",
    "last_updated": "1512792553"
},
{
    "id": "ethereum",
    "name": "Ethereum",
    "symbol": "ETH",
    "rank": "2",
    "price_usd": "471.833",
    "price_btc": "0.0296001",
    "24h_volume_usd": "2170950000.0",
    "market_cap_usd": "45401368016.0",
    "available_supply": "96223384.0",
    "total_supply": "96223384.0",
    "max_supply": null,
    "percent_change_1h": "0.01",
    "percent_change_24h": "9.29",
    "percent_change_7d": "0.65",
    "last_updated": "1512792556"
},
{
    "id": "bitcoin-cash",
    "name": "Bitcoin Cash",
    "symbol": "BCH",
    "rank": "3",
    "price_usd": "1510.48",
    "price_btc": "0.094759",
    "24h_volume_usd": "2229320000.0",
    "market_cap_usd": "25444318815.0",
    "available_supply": "16845188.0",
    "total_supply": "16845188.0",
    "max_supply": "21000000.0",
    "percent_change_1h": "0.6",
    "percent_change_24h": "1.29",
    "percent_change_7d": "2.64",
    "last_updated": "1512792581"
    }
]

Here's the code I currently have:

var url = 'https://api.coinmarketcap.com/v1/ticker/?limit=3';
var dataResponse = '';
var body = '';

function retrieveData() {
    https.get(url, function(res){
        body = '';

        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            dataResponse = JSON.parse(body);
        });

    }).on('error', function(e) {
          console.log("Error: ", e);
    });

}

retrieveData();

var temp = (dataResponse[0]);

console.log(temp);

I want to be able to get something like and be able to select the name and price:

        "id": "bitcoin",
        "name": "Bitcoin",
        "symbol": "BTC",
        "rank": "1",
        "price_usd": "16148.3",
        "price_btc": "1.0",
        "24h_volume_usd": "18799600000.0",
        "market_cap_usd": "270147332945",
        "available_supply": "16729150.0",
        "total_supply": "16729150.0",
        "max_supply": "21000000.0",
        "percent_change_1h": "-0.28",
        "percent_change_24h": "-4.64",
        "percent_change_7d": "45.79",
        "last_updated": "1512792553"

The error I get is that it logs an undefined. I'm not sure what I'm doing wrong. How would I go selecting the name also? Would I split each block into an array and select them by indexing?

Body:
So I think you're already there, all ya need to do is log the "dataResponse" to console. Since "dataResponse" is an array of objects, you can simply output the objects to the console with simple javascript. This is how it'd look like:

```</p>

<pre><code>var https = require ("https")

var url = 'https://api.coinmarketcap.com/v1/ticker/?limit=3';

function retrieveData () {
    https.get (url, function (res){
        body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            dataResponse = JSON.parse (body);
            console.log (dataResponse[0])
        });

    }).on ('error', function (e) {
          console.log ("Error: ", e);
    });

}

retrieveData ()
</code></pre>

<p>```


问:
Suddenly I can't load some newly upgraded modules in Python
I suddenly can't load newly upgraded modules modules, e.g scikit-learn, zope, but I can find other packages. Even though the path links from the import points to the correct anaconda folder, which contains all the code. Any ideas what might be wrong and how to fix it?

```<code>Python 2.7.13 |Anaconda custom (64-bit)| (default, Dec 20 2016, 23:09:15)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
>>> import sklearn
>>> from os import listdir
>>> print(dir(sklearn))
['_ASSUME_FINITE', '__SKLEARN_SETUP__', '__all__', '__builtins__', '__check_build', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_contextmanager', 'base', 'clone', 'config_context', 'exceptions', 'externals', 'get_config', 'logger', 'logging', 'os', 're', 'set_config', 'setup_module', 'sys', 'utils', 'warnings']
>>> print(listdir(sklearn.__path__[0]))
['exceptions.py', 'cross_validation.pyc', 'lda.py', 'naive_bayes.pyc', 'isotonic.py', '_build_utils', 'neighbors', 'cluster', 'naive_bayes.py', '__init__.pyc', 'multiclass.py', 'dummy.pyc', 'grid_search.pyc', 'tests', '__init__.py', 'calibration.py', '_isotonic.so', 'neural_network', 'datasets', 'preprocessing', '__check_build', 'random_projection.py', 'multiclass.pyc', 'model_selection', 'calibration.pyc', 'pipeline.pyc', 'qda.py', 'learning_curve.py', 'ensemble', 'tree', 'isotonic.pyc', 'kernel_ridge.py', 'gaussian_process', 'decomposition', 'base.pyc', 'dummy.py', 'utils', 'pipeline.py', 'cross_decomposition', 'covariance', 'qda.pyc', 'multioutput.pyc', 'lda.pyc', 'feature_selection', 'linear_model', 'metrics', 'kernel_ridge.pyc', 'setup.py', 'semi_supervised', 'exceptions.pyc', 'multioutput.py', 'cross_validation.py', 'discriminant_analysis.py', 'kernel_approximation.pyc', 'base.py', 'random_projection.pyc', 'setup.pyc', 'kernel_approximation.py', 'grid_search.py', 'discriminant_analysis.pyc', 'mixture', 'manifold', 'externals', 'svm', 'feature_extraction', 'learning_curve.pyc']
>>> import zope
>>> print(dir(zope))
['__doc__', '__name__', '__path__']
>>> print(listdir(zope.__path__[0]))
['interface']
>>> zope.interface
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'interface'
>>> sklearn.lda
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'lda'
</code>```

答:
It's not that you can't load them. As you can see, you did import them successfully with no error messages appearing.

However, it seems that the modules zope and sklearn do not have the attributes that you are trying to use with them.

try:

from zope.interface import Interface

 and the same for sklearn:

from sklearn import lda

I hope this helps. If not, try reinstalling the packages.

Note that: you cannot simply just use pip install package because you are required to install other dependencies as well. Here are the pages with the installation instructions for:

zope:
https://zope.readthedocs.io/en/latest/INSTALL-buildout.html

sklearn:
http://scikit-learn.org/stable/install.html

Body:
I suddenly can't load newly upgraded modules modules, e.g scikit-learn, zope, but I can find other packages. Even though the path links from the import points to the correct anaconda folder, which contains all the code. Any ideas what might be wrong and how to fix it?

Python 2.7.13 |Anaconda custom (64-bit)| (default, Dec 20 2016, 23:09:15)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
>>> import sklearn
>>> from os import listdir
>>> print(dir(sklearn))
['_ASSUME_FINITE', '__SKLEARN_SETUP__', '__all__', '__builtins__', '__check_build', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_contextmanager', 'base', 'clone', 'config_context', 'exceptions', 'externals', 'get_config', 'logger', 'logging', 'os', 're', 'set_config', 'setup_module', 'sys', 'utils', 'warnings']
>>> print(listdir(sklearn.__path__[0]))
['exceptions.py', 'cross_validation.pyc', 'lda.py', 'naive_bayes.pyc', 'isotonic.py', '_build_utils', 'neighbors', 'cluster', 'naive_bayes.py', '__init__.pyc', 'multiclass.py', 'dummy.pyc', 'grid_search.pyc', 'tests', '__init__.py', 'calibration.py', '_isotonic.so', 'neural_network', 'datasets', 'preprocessing', '__check_build', 'random_projection.py', 'multiclass.pyc', 'model_selection', 'calibration.pyc', 'pipeline.pyc', 'qda.py', 'learning_curve.py', 'ensemble', 'tree', 'isotonic.pyc', 'kernel_ridge.py', 'gaussian_process', 'decomposition', 'base.pyc', 'dummy.py', 'utils', 'pipeline.py', 'cross_decomposition', 'covariance', 'qda.pyc', 'multioutput.pyc', 'lda.pyc', 'feature_selection', 'linear_model', 'metrics', 'kernel_ridge.pyc', 'setup.py', 'semi_supervised', 'exceptions.pyc', 'multioutput.py', 'cross_validation.py', 'discriminant_analysis.py', 'kernel_approximation.pyc', 'base.py', 'random_projection.pyc', 'setup.pyc', 'kernel_approximation.py', 'grid_search.py', 'discriminant_analysis.pyc', 'mixture', 'manifold', 'externals', 'svm', 'feature_extraction', 'learning_curve.pyc']
>>> import zope
>>> print(dir(zope))
['__doc__', '__name__', '__path__']
>>> print(listdir(zope.__path__[0]))
['interface']
>>> zope.interface
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'interface'
>>> sklearn.lda
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'lda'


问:
The range of int in Java
I understand that the int range in Java should be -2^31 to 2^31-1.

But when I run this code snippet with 20:

```<code>public class Factorial {
    public int factorial(int n) {
        int fac=1;
        for (int i=1; i<=n; i++) {
            fac *= i;
            System.out.println("Factorial of " + i + " is: " + fac);
        }
        return fac;
    }
}
</code>```

The output:

```<code>Factorial of 1 is: 1
Factorial of 2 is: 2
Factorial of 3 is: 6
Factorial of 4 is: 24
Factorial of 5 is: 120
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
Factorial of 9 is: 362880
Factorial of 10 is: 3628800
Factorial of 11 is: 39916800
Factorial of 12 is: 479001600
Factorial of 13 is: 1932053504
Factorial of 14 is: 1278945280
Factorial of 15 is: 2004310016
Factorial of 16 is: 2004189184
Factorial of 17 is: -288522240
Factorial of 18 is: -898433024
Factorial of 19 is: 109641728
Factorial of 20 is: -2102132736
</code>```

It's not making sense from 13 (13! = 6,227,020,800). It looks like it's out of range and wrapped around. What's wrong? Is it due to Eclipse that I'm using?

Though I think it's not relevant, here is the test code:

```<code>public class TestFac {

    public static void main(String[] args) {
        int n;
        Scanner sc = new Scanner(System.in);

        System.out.println("Input num you want to factorial: ");
        n = sc.nextInt();
        Factorial fac = new Factorial();
        fac.factorial(n);
    }
}
</code>```

答:
Please run this code:

```<code>System.out.println("Minimum value of Integer is: " + Integer.MIN_VALUE);
System.out.println("Maximum value of Integer is: " + Integer.MAX_VALUE);
</code>```

So you can see why it fails.

Title: The range of int in Java

Body:
I understand that the int range in Java should be -2^31 to 2^31-1.

But when I run this code snippet with 20:

public class Factorial {
    public int factorial(int n) {
        int fac=1;
        for (int i=1; i<=n; i++) {
            fac *= i;
            System.out.println("Factorial of " + i + " is: " + fac);
        }
        return fac;
    }
}

The output:

Factorial of 1 is: 1
Factorial of 2 is: 2
Factorial of 3 is: 6
Factorial of 4 is: 24
Factorial of 5 is: 120
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
Factorial of 9 is: 362880
Factorial of 10 is: 3628800
Factorial of 11 is: 39916800
Factorial of 12 is: 479001600
Factorial of 13 is: 1932053504
Factorial of 14 is: 1278945280
Factorial of 15 is: 2004310016
Factorial of 16 is: 2004189184
Factorial of 17 is: -288522240
Factorial of 18 is: -898433024
Factorial of 19 is: 109641728
Factorial of 20 is: -2102132736

It's not making sense from 13 (13! = 6,227,020,800). It looks like it's out of range and wrapped around. What's wrong? Is it due to Eclipse that I'm using?

Though I think it's not relevant, here is the test code:

public class TestFac {

    public static void main(String[] args) {
        int n;
        Scanner sc = new Scanner(System.in);

        System.out.println("Input num you want to factorial: ");
        n = sc.nextInt();
        Factorial fac = new Factorial();
        fac.factorial(n);
    }
}

Body:
Please run this code:

System.out.println("Minimum value of Integer is: " + Integer.MIN_VALUE);
System.out.println("Maximum value of Integer is: " + Integer.MAX_VALUE);

So you can see why it fails.


问:
Getting the index of the leftmost active bit in an integer instantly
How would I scan an integer (in binary) from left to right instead of right to left? I know that I can start from the left and try every bit, and then record the leftmost bit, but is there a faster way? Is there a built-in function that can instantly find the leftmost active bit (that is a 1) in an integer?

I know that for right to left, I can do something like

```<code>int myInt = 1234;
for(int i = 0; i < 32; i++) {
  int curr_bit = myInt & (1 << i);
  // do something with curr_bit
}
</code>```

But, I want to start off at the leftmost available bit, and I want its number "x" so that 1 << x will point to that exact digit
(Just as a side note, I am trying to implement repeated squaring, and I need this in my code).

Any help would be greatly appreciated!

答:
Java has a method in the Integer class called highestOneBit(int value) which returns an int value with at most a single one-bit, in the position of the most significant (left most) bit that is set in the specified int value. It is implemented like this:</p>

```<code>int highestOneBit(int value)
{
    value |= (value >>  1);
    value |= (value >>  2);
    value |= (value >>  4);
    value |= (value >>  8);
    value |= (value >> 16);
    return value - (value >> 1);
}
</code>```

Body:
How would I scan an integer (in binary) from left to right instead of right to left? I know that I can start from the left and try every bit, and then record the leftmost bit, but is there a faster way? Is there a built-in function that can instantly find the leftmost active bit (that is a 1) in an integer?

I know that for right to left, I can do something like

int myInt = 1234;
for(int i = 0; i < 32; i++) {
  int curr_bit = myInt & (1 << i);
  // do something with curr_bit
}

But, I want to start off at the leftmost available bit, and I want its number "x" so that 1 << x will point to that exact digit
(Just as a side note, I am trying to implement repeated squaring, and I need this in my code).

Any help would be greatly appreciated!

Body:
Java has a method in the Integer class called highestOneBit(int value) which returns an int value with at most a single one-bit, in the position of the most significant (left most) bit that is set in the specified int value. It is implemented like this:

int highestOneBit(int value)
{
    value |= (value >>  1);
    value |= (value >>  2);
    value |= (value >>  4);
    value |= (value >>  8);
    value |= (value >> 16);
    return value - (value >> 1);
}