问:
How to separate path parameters with a dash in Swagger
I am trying to create a Swagger document with Yaml on an existing API.
In this API there is a path like this:

```<code>/api/foo--bar/baz
</code>```

So I created the path definition in the Swagger Editor like this:

```<code>paths:
  /api/{foo}--{bar}/{baz}:
    get:
      parameters:
        - $ref: '#/parameters/foo'
        - $ref: '#/parameters/bar'
        - $ref: '#/parameters/baz'
[...]
</code>```

Now I am stuck with the editor telling me:

Semantic error at paths./api/{foo}--{bar}/{baz}
  Partial path templating is not allowed.

Is there a possibility to express url paths like the above in swagger?

答:
Your syntax is correct. The error you see is was a bug in the Swagger Editor 3.0–3.1.5. You can ignore the error, or use the old Swagger Editor 2.x at http://editor2.swagger.io which does not have this bug.

Update: This bug was fixed in Swagger Editor 3.1.6 and in the online editor http://editor.swagger.io.

Body:
I am trying to create a Swagger document with Yaml on an existing API.
In this API there is a path like this:

/api/foo--bar/baz

So I created the path definition in the Swagger Editor like this:

paths:
  /api/{foo}--{bar}/{baz}:
    get:
      parameters:
        - $ref: '#/parameters/foo'
        - $ref: '#/parameters/bar'
        - $ref: '#/parameters/baz'
[...]

Now I am stuck with the editor telling me:

Semantic error at paths./api/{foo}--{bar}/{baz}
  Partial path templating is not allowed.

Is there a possibility to express url paths like the above in swagger?


来源: stackexchange

问:
iPad : Problem changing the background color of Grouped TableView in iOS SDK 4.2
I am using iOS SDK 4.2.

In my iPad app, I am not able to change the background color of Group Table View even it does not set to clear color

If I try to change the table view style from Grouped Table View to Plain Table View and then try changing the background color then it changes.

But something seems to be wrong when I am using Grouped Table View

What could be wrong?

What should I do?

Plese Help and Suggest

Thanks.

答:
I have this problem as well. Only on iPad. Only with a grouped Table.

You can fix this by creating a new view, coloring it and then setting that new view to the backgroundView of the tableView.

This works for static colors, but not Pattern Images(what I'm trying to do)

ContentLicense: CC BY-SA 2.5


问:
Improving Python user defined max function
I am new to programming and am trying to understand how to "think" more programmatically in Python. I wrote a function that returns the largest element in an array without using max:

```<code>def max_userdefined(array):
    """
    Finds largest value of nonempty array of numbers in O(n)
    :param: list/tuple of values
    :return: max value
    """
    try:
        assert isinstance(array, list or tuple)
        result = array[0]
        for element in array:
            if element > result:
                result = element
        return result
    except IndexError:
        return 'Please pass in a nonempty array'
    except AssertionError:
        return 'Please pass in a list or tuple'
    except TypeError:
        return 'Please make sure elements of array are all floats or ints'
</code>```

How can I improve the above code? Open to any criticism or if anyone can recommend a good Pythonic style guide.

答:
```<code>def max_userdefined(array):
    myMax = l[0]
    for num in l:
        if myMax < num:
            myMax = num
    return myMax

print max_userdefined ([1,2,3,4,5])
</code>```

Output

```<code>5
</code>```

Or You can do something like following by using sorted.

```<code>def max_userdefined(array):
    return sorted(array)[-1]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to programming and am trying to understand how to "think" more programmatically in Python. I wrote a function that returns the largest element in an array without using max:

def max_userdefined(array):
    """
    Finds largest value of nonempty array of numbers in O(n)
    :param: list/tuple of values
    :return: max value
    """
    try:
        assert isinstance(array, list or tuple)
        result = array[0]
        for element in array:
            if element > result:
                result = element
        return result
    except IndexError:
        return 'Please pass in a nonempty array'
    except AssertionError:
        return 'Please pass in a list or tuple'
    except TypeError:
        return 'Please make sure elements of array are all floats or ints'

How can I improve the above code? Open to any criticism or if anyone can recommend a good Pythonic style guide.

Body:
def max_userdefined(array):
    myMax = l[0]
    for num in l:
        if myMax < num:
            myMax = num
    return myMax

print max_userdefined ([1,2,3,4,5])

Output

5

Or You can do something like following by using sorted.

def max_userdefined(array):
    return sorted(array)[-1]


问:
disable route being added to camel context based on some condition
I need to restrict particular routes being added to the camel context based on some condition. Tried RoutePolicy.onStart -> but this method is being invoked after starting the route. </p>

<p>I need a way to to completely avoid the route being generated/added to camel context. </p>

```<code> private List<String> eligibleRoutes;

 @Override
  public void onStart(Route route) {
    LOGGER.info("onInit for {}", route.getId());
    if (isCollectionNotEmpty(eligibleRoutes))
    {
      LOGGER.info("route-start eligibility for route {}", route.getId());
      if (eligibleRoutes.contains(route.getId()))
      {
        LOGGER.info("Route-start is set to ELIGiBLE for {}", route.getId());
      }else{
        LOGGER.info("Route-start is set to NOT ELIGiBLE for {}", route.getId());

        route.getRouteContext().getCamelContext().stopRoute(route.getId());
        boolean status = route.getRouteContext().getCamelContext().removeRoute(route.getId());
        return;
      }
}
</code>```

答:
You need to set the route to autoStartup=false, and then in the onInit method you can determine if it should be started anyway, and call its startRoute method.

Or another way is to configure CamelContext to have autoStartup=false, and then you can have an Camel event lister bean that listen for CamelContextStartedEvent, and then you trigger there to find out which routes you want to start, and call the camelContext.startRoute("nameOfRoute").

Body:
I need to restrict particular routes being added to the camel context based on some condition. Tried RoutePolicy.onStart -> but this method is being invoked after starting the route.

I need a way to to completely avoid the route being generated/added to camel context.

 private List<String> eligibleRoutes;

 @Override
  public void onStart(Route route) {
    LOGGER.info("onInit for {}", route.getId());
    if (isCollectionNotEmpty(eligibleRoutes))
    {
      LOGGER.info("route-start eligibility for route {}", route.getId());
      if (eligibleRoutes.contains(route.getId()))
      {
        LOGGER.info("Route-start is set to ELIGiBLE for {}", route.getId());
      }else{
        LOGGER.info("Route-start is set to NOT ELIGiBLE for {}", route.getId());

        route.getRouteContext().getCamelContext().stopRoute(route.getId());
        boolean status = route.getRouteContext().getCamelContext().removeRoute(route.getId());
        return;
      }
}


问:
Ruby extend for object class
Why for this code I have folowing error?

```<code>module ForExtend
  def print
    print "ForExtend print method!"
  end
end

class A
end

a = A.new

class << a
  extend ForExtend
end

a.print
</code>```

Result:

```<code>private method `print' called for #<A:0x005607b26811f8>
(repl):16:in `<main>'
</code>```

In what class/eigenclass lays method print in this case? And how can I access it?

答:
It is because you have A class, not their instance a, extended.

```<code>module ForExtend
  def print
    puts "ForExtend print method!"
  end
end

class A; end

a = A.new
a.extend ForExtend # ⇐ THIS WILL EXTEND a

a.print
#⇒ "ForExtend print method!"
</code>```

Title: Ruby extend for object class

Body:
Why for this code I have folowing error?

module ForExtend
  def print
    print "ForExtend print method!"
  end
end

class A
end

a = A.new

class << a
  extend ForExtend
end

a.print

Result:

private method `print' called for #
(repl):16:in `'

In what class/eigenclass lays method print in this case? And how can I access it?

Body:
It is because you have A class, not their instance a, extended.

module ForExtend
  def print
    puts "ForExtend print method!"
  end
end

class A; end

a = A.new
a.extend ForExtend # ⇐ THIS WILL EXTEND a

a.print
#⇒ "ForExtend print method!"


问:
Unable to execute postgres sql script from ansible
I want to execute a postgresql sql which is fetched from my git resource.
I want to first fetch all the scripts from git repository and then wants to execute scripts from a particular directory which i taking as an input in ansible script.This is my complete ansible script

```<code>- hosts: "{{ HOST }}"
  become: true
  become_user: "admin"
  become_method: su
  gather_facts: true
  vars:
    app_path: "{{ app_path }}"
    app_dir: "{{ app_dir }}"

  tasks:
    - stat:
        path: "{{ app_path }}/{{ app_dir }}"
      register: exist

    - name: create "{{ app_path }}/{{ app_dir }}" directory
      file: dest="{{ app_path }}/{{ app_dir }}" state=directory
      when: exist.stat.exists != True

    - git:
        repo: http://git-url/postgres-demo.git
        dest: "{{ app_path }}/{{ app_dir }}"
        version: "{{ GIT_TAG }}"
        refspec: '+refs/heads/{{ GIT_TAG }}:refs/remotes/origin/{{ GIT_TAG }}'
        update: yes
        force: true
      register: cloned

    - name: Execute postgres dump files
      shell: "/usr/bin/psql -qAtw -f  {{ item }}"
      with_fileglob:
          - "{{ app_path }}/{{ app_dir }}/{{ scripts_dir }}/*"
      register: postgres_sql
      become: true
      become_user: "postgres"
      become_method: su
</code>```

Above script is executed successfully but postgres step throwing me following waning:

```<code>[WARNING]: Unable to find '/home/admin/postgres-dev/test' in expected paths.
</code>```

When i checked my postgresql db,I don't find the table that i want to create using this scripts.

答:
All lookups in Ansible are executed on local ansible host.

So:

```<code>with_fileglob:
  - "{{ app_path }}/{{ app_dir }}/{{ scripts_dir }}/*"
</code>```

uses fileglob lookup, which searches files on localhost!

You should refactor this code to use find module first to find all required scripts, register its output and then loop with with_items over registered variable to execute scripts.

Body:
I want to execute a postgresql sql which is fetched from my git resource.
I want to first fetch all the scripts from git repository and then wants to execute scripts from a particular directory which i taking as an input in ansible script.This is my complete ansible script

- hosts: "{{ HOST }}"
  become: true
  become_user: "admin"
  become_method: su
  gather_facts: true
  vars:
    app_path: "{{ app_path }}"
    app_dir: "{{ app_dir }}"

  tasks:
    - stat:
        path: "{{ app_path }}/{{ app_dir }}"
      register: exist

    - name: create "{{ app_path }}/{{ app_dir }}" directory
      file: dest="{{ app_path }}/{{ app_dir }}" state=directory
      when: exist.stat.exists != True

    - git:
        repo: http://git-url/postgres-demo.git
        dest: "{{ app_path }}/{{ app_dir }}"
        version: "{{ GIT_TAG }}"
        refspec: '+refs/heads/{{ GIT_TAG }}:refs/remotes/origin/{{ GIT_TAG }}'
        update: yes
        force: true
      register: cloned

    - name: Execute postgres dump files
      shell: "/usr/bin/psql -qAtw -f  {{ item }}"
      with_fileglob:
          - "{{ app_path }}/{{ app_dir }}/{{ scripts_dir }}/*"
      register: postgres_sql
      become: true
      become_user: "postgres"
      become_method: su

Above script is executed successfully but postgres step throwing me following waning:

[WARNING]: Unable to find '/home/admin/postgres-dev/test' in expected paths.

When i checked my postgresql db,I don't find the table that i want to create using this scripts.

Body:
All lookups in Ansible are executed on local ansible host.

So:

with_fileglob:
  - "{{ app_path }}/{{ app_dir }}/{{ scripts_dir }}/*"

uses fileglob lookup, which searches files on localhost!

You should refactor this code to use find module first to find all required scripts, register its output and then loop with with_items over registered variable to execute scripts.


问:
Loop over Json using Jquery
Below is my Json Data received from Ajax response.

```<code>{
    "error": {
        "errorCode": "0001",
        "errorText": "SUCCESS"
    },
    "responselist": [
        {
            "count": 2,
            "event": [
                {
                    "startDate": null,
                    "eventId": 1234,
                    "eventName": "Interview",
                    "modifiedUser": "User",
                    "eventTypeCode": "1",
                    "eventVenue": null,
                    "eventSpecialInst": "isnsdf",
                    "eventStatusCode": "OP",
                    "eventLangCode": "Eng",
                    "eventDesc": "sdfsadfsd",
                    "fromEmailId": "Abcd@apple.com",
                    "rsvpDeadline": 5,
                    "canceledInd": "yes",
                    "canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
                    "daysToWaitlistLastCall": 5,
                    "daysToReminderAdmin": 6,
                    "daysToReminderEvent": 3,
                    "daysToReminderInvitation": 2,
                    "endDate": null,
                    "venueAddrLine1": null,
                    "venueAddrLine2": null,
                    "venueAddrLine3": null,
                    "cityCode": null,
                    "stateCode": null,
                    "appId": null,
                    "modifiedDate": "2010-12-16",
                    "countryCode": null,
                    "zipCode": null,
                    "user_id": null,
                    "updateFlag": "R"
                },
                {
                    "startDate": null,
                    "eventId": 4321,
                    "eventName": "Seasonal Hiring",
                    "modifiedUser": "User",
                    "eventTypeCode": "1",
                    "eventVenue": null,
                    "eventSpecialInst": "isnsdf",
                    "eventStatusCode": "OP",
                    "eventLangCode": "Eng",
                    "eventDesc": "sdfsadfsd",
                    "fromEmailId": "Abcd@apple.com",
                    "rsvpDeadline": 5,
                    "canceledInd": "yes",
                    "canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
                    "daysToWaitlistLastCall": 5,
                    "daysToReminderAdmin": 6,
                    "daysToReminderEvent": 3,
                    "daysToReminderInvitation": 2,
                    "endDate": null,
                    "venueAddrLine1": "KFC",
                    "venueAddrLine2": "The Forum",
                    "venueAddrLine3": "Koramangala",
                    "cityCode": "Bangalore",
                    "stateCode": "Karnataka",
                    "appId": null,
                    "modifiedDate": "2010-12-16",
                    "countryCode": "India",
                    "zipCode": "560040",
                    "user_id": null,
                    "updateFlag": "R"
                }
            ]
        }
    ]
}
</code>```

Using below code to extract information inside event object. But I am not able to do it. Need guidance.

```<code>$.ajax({ url:"<%=request.getContextPath()%>/service/showInvitedEvents/21",

         dataType:"json",
         success: function(jsonData)
         {
           alert("Inside response success");

           $.each(jsonData.responselist.event,function(i,item)
          $.each(Employees,function(i,item)
           {
             alert('Iteration is' + i);
            var teventName = item.eventName;

            var teventVenue = item.eventVenue;
            var tstartDate = item.startDate;
            var tendDate = item.endDate;
            var tstarend = tstartDate +" - "+ tendDate ;

            $("#eventTable tbody").append("<tr><td><a id="+teventName+i+" href=<%=request.getContextPath()%>/service/session/1234>"+teventName+"</a></td><td>"+teventVenue+"</td><td>"+tstarend+"</td></tr>");

           });
</code>```

答:
First of all you can't loop over jsonData.responselist.event. jsonData.responselist is an array so either need to make a double loop or if you always know there is one and only one item in responslist you could loop over jsonData.responselist[0].event

For the rest of it I'm not sure why you have this row:

```<code>$.each(Employees,function(i,item)
</code>```

Looks like a misstake to as it isn't valid there(the syntax is wrong and it hides both i and item from the real each).

Title: Loop over Json using Jquery

Body:
Below is my Json Data received from Ajax response.

{
    "error": {
        "errorCode": "0001",
        "errorText": "SUCCESS"
    },
    "responselist": [
        {
            "count": 2,
            "event": [
                {
                    "startDate": null,
                    "eventId": 1234,
                    "eventName": "Interview",
                    "modifiedUser": "User",
                    "eventTypeCode": "1",
                    "eventVenue": null,
                    "eventSpecialInst": "isnsdf",
                    "eventStatusCode": "OP",
                    "eventLangCode": "Eng",
                    "eventDesc": "sdfsadfsd",
                    "fromEmailId": "Abcd@apple.com",
                    "rsvpDeadline": 5,
                    "canceledInd": "yes",
                    "canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
                    "daysToWaitlistLastCall": 5,
                    "daysToReminderAdmin": 6,
                    "daysToReminderEvent": 3,
                    "daysToReminderInvitation": 2,
                    "endDate": null,
                    "venueAddrLine1": null,
                    "venueAddrLine2": null,
                    "venueAddrLine3": null,
                    "cityCode": null,
                    "stateCode": null,
                    "appId": null,
                    "modifiedDate": "2010-12-16",
                    "countryCode": null,
                    "zipCode": null,
                    "user_id": null,
                    "updateFlag": "R"
                },
                {
                    "startDate": null,
                    "eventId": 4321,
                    "eventName": "Seasonal Hiring",
                    "modifiedUser": "User",
                    "eventTypeCode": "1",
                    "eventVenue": null,
                    "eventSpecialInst": "isnsdf",
                    "eventStatusCode": "OP",
                    "eventLangCode": "Eng",
                    "eventDesc": "sdfsadfsd",
                    "fromEmailId": "Abcd@apple.com",
                    "rsvpDeadline": 5,
                    "canceledInd": "yes",
                    "canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
                    "daysToWaitlistLastCall": 5,
                    "daysToReminderAdmin": 6,
                    "daysToReminderEvent": 3,
                    "daysToReminderInvitation": 2,
                    "endDate": null,
                    "venueAddrLine1": "KFC",
                    "venueAddrLine2": "The Forum",
                    "venueAddrLine3": "Koramangala",
                    "cityCode": "Bangalore",
                    "stateCode": "Karnataka",
                    "appId": null,
                    "modifiedDate": "2010-12-16",
                    "countryCode": "India",
                    "zipCode": "560040",
                    "user_id": null,
                    "updateFlag": "R"
                }
            ]
        }
    ]
}

Using below code to extract information inside event object. But I am not able to do it. Need guidance.

$.ajax({ url:"<%=request.getContextPath()%>/service/showInvitedEvents/21",

         dataType:"json",
         success: function(jsonData)
         {
           alert("Inside response success");

           $.each(jsonData.responselist.event,function(i,item)
          $.each(Employees,function(i,item)
           {
             alert('Iteration is' + i);
            var teventName = item.eventName;

            var teventVenue = item.eventVenue;
            var tstartDate = item.startDate;
            var tendDate = item.endDate;
            var tstarend = tstartDate +" - "+ tendDate ;

            $("#eventTable tbody").append("
<a id="+teventName+i+" href=<%=request.getContextPath()%>/service/session/1234>"+teventName+"	"+teventVenue+"	"+tstarend+"
");

           });

Body:
First of all you can't loop over jsonData.responselist.event. jsonData.responselist is an array so either need to make a double loop or if you always know there is one and only one item in responslist you could loop over jsonData.responselist[0].event

For the rest of it I'm not sure why you have this row:

$.each(Employees,function(i,item)

Looks like a misstake to as it isn't valid there(the syntax is wrong and it hides both i and item from the real each).


问:
Loading OECD data into pandas with pandaSDMX
I am trying to load industrial production data (with revisions history) from the OECD. The data can be found at http://stats.oecd.org/Index.aspx?DataSetCode=MEI_ARCHIVE#.

I would like to load the data into a pandas environment in Python using pandaSDMX (https://pandasdmx.readthedocs.io/en/master/).

```<code>from pandasdmx import Request
oecd = Request('OECD')
cat_response = oecd.categoryscheme()
</code>```

I am getting the following error, suggesting that the code is not able to find the url required.

```<code>raise HTTPError(http_error_msg, response=self)requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://stats.oecd.org/SDMX-JSON/categoryscheme?references=parentsandsiblings
</code>```

Is there a way to work around this? Have others experienced similar problems with OECD data and pandaSDMX?

答: The OECD's API used by pandaSDMX Supports requests for datasets only, hence no categoryscheme, no datastructure, no dataflow. You have to figure out the dataflow ID and desired Dimension values yourself through the web Interface and issue the data request.</p>

Body:
I am trying to load industrial production data (with revisions history) from the OECD. The data can be found at http://stats.oecd.org/Index.aspx?DataSetCode=MEI_ARCHIVE#.

I would like to load the data into a pandas environment in Python using pandaSDMX (https://pandasdmx.readthedocs.io/en/master/).

from pandasdmx import Request
oecd = Request('OECD')
cat_response = oecd.categoryscheme()

I am getting the following error, suggesting that the code is not able to find the url required.

raise HTTPError(http_error_msg, response=self)requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://stats.oecd.org/SDMX-JSON/categoryscheme?references=parentsandsiblings

Is there a way to work around this? Have others experienced similar problems with OECD data and pandaSDMX?


问:
observable to return many json objects from server will contain all at once or iterate through?
I'm using angular 4 and typescript

I have created an api endpoint that will return a array of json objects. My question refers to capturing the json inside a variable designed to hold an array of javascript objects. Will the observable return a list of json objects to where I can just set the variable in my typescript code to that array? And if so how.

Or do I have to iterate through the list of json objects and append them to the array variable?

Notice no code, as I am confused as to when I use interaces, when I use constructors and the alike. I would like to see how this is done. I am still learning

答:
```<code>getData(): Observable<Array<any>> {
return this.http.get("http://apiurl")
  .map((response: Response) => response.json());
}
</code>```

Set Observable type to Array<any>,
you can replace any with your datatype.

Iterate over an array using

```<code>let list = [{"name": "john"}, {"name": "doe"}];

for (let i in list) {
   console.log(i); // indexes will be printed
}

for (let i of list) {
   console.log(i); // Actual values will be printed
}
</code>```

Body:
getData(): Observable<Array<any>> {
return this.http.get("http://apiurl")
  .map((response: Response) => response.json());
}

Set Observable type to Array<any>,
you can replace any with your datatype.

Iterate over an array using

let list = [{"name": "john"}, {"name": "doe"}];

for (let i in list) {
   console.log(i); // indexes will be printed
}

for (let i of list) {
   console.log(i); // Actual values will be printed
}


问:
In my picker view array data is not loading?
In this I try to load picker view with data but not able to load data and it is showing as shown in below image that only empty picker view is displaying i was trying from a long time can any one help me what's wrong in implementing ?

```<code>    var firstName : String = ""
    var lastName : String = ""
    var mobileNumber : Int = 0
    var email : String = ""
    var defaultValue = 1
    let url = "http://www.json-generator.com/api/json/get/bPmyumGWeW?indent=2"
    var dateofbirth : String = ""
    var Gender : String = ""
    var genderArray = [String]()

        override func viewDidLoad() {
        super.viewDidLoad()
        let picker = UIPickerView()
        picker.isHidden = true
        picker.delegate = self
        DateofBirthTextfield.delegate = self
        selectGenderTextField.inputView = picker
        MyaccountJsonWithURL()
        genderArray = ["Male","Female"]

    }

    func MyaccountJsonWithURL() {
        let url = NSURL(string: self.url)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                //  print(jsonObj!.value(forKey: "Detail"))
                if let profileArray = jsonObj!.value(forKey: "profile") as? NSArray {
                    for array in profileArray {
                        if let profileDict = array as? NSDictionary {
                            if let firstName = profileDict.value(forKey: "first name"){
                                self.firstName.append(firstName as! String)
                            }
                            if let lastName = profileDict.value(forKey: "last name"){
                                self.lastName.append(lastName as! String)
                            }
                            self.mobileNumber = profileDict.value(forKey: "mobile") as! Int
                            print(self.mobileNumber)
                            if let emailId = profileDict.value(forKey: "email"){
                                self.email.append(emailId as! String)
                            }
                            self.dateofbirth = profileDict.value(forKey: "dob") as! String
                            if let gender = profileDict.value(forKey: "gender"){
                                self.Gender.append(gender as! String)
                            }
                        }
                    }
                }
                OperationQueue.main.addOperation({
                    self.FirstNameTextfield.text = self.firstName
                    self.LastNameTextfield.text = self.lastName
                    self.MobileNumberTextfield.text = String(describing: self.mobileNumber)
                    self.EmailIdTextfield.text = self.email
                    self.DateofBirthTextfield.text = String(describing: self.dateofbirth)
                    self.selectGenderTextField.text = self.Gender
                })
            }
        }).resume()
    }

func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return genderArray.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return genderArray[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectGenderTextField.text = genderArray[row]
        self.view.endEditing(false)
    }
</code>```

答:
type & replace on picker.hidden = true

```<code>picker.hidden = false
</code>```

Body:
In this I try to load picker view with data but not able to load data and it is showing as shown in below image that only empty picker view is displaying i was trying from a long time can any one help me what's wrong in implementing ?

    var firstName : String = ""
    var lastName : String = ""
    var mobileNumber : Int = 0
    var email : String = ""
    var defaultValue = 1
    let url = "http://www.json-generator.com/api/json/get/bPmyumGWeW?indent=2"
    var dateofbirth : String = ""
    var Gender : String = ""
    var genderArray = [String]()

        override func viewDidLoad() {
        super.viewDidLoad()
        let picker = UIPickerView()
        picker.isHidden = true
        picker.delegate = self
        DateofBirthTextfield.delegate = self
        selectGenderTextField.inputView = picker
        MyaccountJsonWithURL()
        genderArray = ["Male","Female"]

    }

    func MyaccountJsonWithURL() {
        let url = NSURL(string: self.url)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                //  print(jsonObj!.value(forKey: "Detail"))
                if let profileArray = jsonObj!.value(forKey: "profile") as? NSArray {
                    for array in profileArray {
                        if let profileDict = array as? NSDictionary {
                            if let firstName = profileDict.value(forKey: "first name"){
                                self.firstName.append(firstName as! String)
                            }
                            if let lastName = profileDict.value(forKey: "last name"){
                                self.lastName.append(lastName as! String)
                            }
                            self.mobileNumber = profileDict.value(forKey: "mobile") as! Int
                            print(self.mobileNumber)
                            if let emailId = profileDict.value(forKey: "email"){
                                self.email.append(emailId as! String)
                            }
                            self.dateofbirth = profileDict.value(forKey: "dob") as! String
                            if let gender = profileDict.value(forKey: "gender"){
                                self.Gender.append(gender as! String)
                            }
                        }
                    }
                }
                OperationQueue.main.addOperation({
                    self.FirstNameTextfield.text = self.firstName
                    self.LastNameTextfield.text = self.lastName
                    self.MobileNumberTextfield.text = String(describing: self.mobileNumber)
                    self.EmailIdTextfield.text = self.email
                    self.DateofBirthTextfield.text = String(describing: self.dateofbirth)
                    self.selectGenderTextField.text = self.Gender
                })
            }
        }).resume()
    }

func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return genderArray.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return genderArray[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectGenderTextField.text = genderArray[row]
        self.view.endEditing(false)
    }

Body:
type & replace on picker.hidden = true

picker.hidden = false


问:
why es6 expport and import is messy
I am using babel es6 class:

```<code>export class Util{
  async stringy(str){
    return await str
  }
}
</code>```

then I import it

```<code>import Util from '../lib/util'
</code>```

but it is undefined.

答:
as 4castle said, you have mixed up export/import types. it should be either:

// util.js
export class Util{
  async stringy(str){
    return await str
  }
}

// other.js
import { Util } from '../lib/util'```
</div>
</div>
</p>

<p>or</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// util.js
export default class Util{
  async stringy(str){
    return await str
  }
}

// other.js
import Util from '../lib/util'</code>```

Title: why es6 expport and import is messy

Body:
I am using babel es6 class:

export class Util{
  async stringy(str){
    return await str
  }
}

then I import it

import Util from '../lib/util'

but it is undefined.

Body:
as 4castle said, you have mixed up export/import types. it should be either:

// util.js
export class Util{
  async stringy(str){
    return await str
  }
}

// other.js
import { Util } from '../lib/util'

or

// util.js
export default class Util{
  async stringy(str){
    return await str
  }
}

// other.js
import Util from '../lib/util'


问:
for loop prints the same thing in each iteration, should only print it once
I am having trouble in which my for loop prints the same vector 17 times from 17 elements instead of printing 1 time and drawing from 17 elements. What is going wrong?

Also, I am trying to add the mean value at the end of the inverted vector but it is saying that the dimensions are off. (Second function works but I included it for reference as it is inside ProcessSpike).

```<code>function [] = ProcessSpike(dataset,element,cluster)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
result = []
for a = 1:element
    for b = 1:cluster
        result = [result AvSpike(dataset, a, b)];
        mean = nanmean(result)
        r = [result]'
        r(end+1) = num2str(mean)
    end
end

function [result] = AvSpike(dataset,element,cluster)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
Trans1 = dataset.Trans1;
Before_Trans1 = Trans1-600;
Firing_Time1 = dataset(cluster).time(dataset(cluster).time>Before_Trans1(element)&dataset(cluster).time<Trans1(element));
ISI1 = diff(Firing_Time1);
result = numel(ISI1)/600
result(result == 0) = NaN
end
</code>```

答:
I have added comments to a revised version of your code which hopefully make things clearer.</p>

```<code>result = []
for a = 1:element
    for b = 1:cluster
        % Concatenate vertically (use ;) so no need to transpose later
        result = [result; AvSpike(dataset, a, b)];
        % Use a semi-colon at the end of line to supress outputs from command window
        % Changed variable name, don't call a variable the same as an in-built function
        mymean = nanmean(result);
        % r = result'  % This line removed as no need since we concatenated vertically
        % Again, using the semi-colon to supress output, not sure why num2str was used
        r(end+1) = mymean;
    end
end
disp(r) % Deliberately output the result!
</code>```

Body:
I am having trouble in which my for loop prints the same vector 17 times from 17 elements instead of printing 1 time and drawing from 17 elements. What is going wrong?

Also, I am trying to add the mean value at the end of the inverted vector but it is saying that the dimensions are off. (Second function works but I included it for reference as it is inside ProcessSpike).

function [] = ProcessSpike(dataset,element,cluster)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
result = []
for a = 1:element
    for b = 1:cluster
        result = [result AvSpike(dataset, a, b)];
        mean = nanmean(result)
        r = [result]'
        r(end+1) = num2str(mean)
    end
end

function [result] = AvSpike(dataset,element,cluster)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
Trans1 = dataset.Trans1;
Before_Trans1 = Trans1-600;
Firing_Time1 = dataset(cluster).time(dataset(cluster).time>Before_Trans1(element)&dataset(cluster).time<Trans1(element));
ISI1 = diff(Firing_Time1);
result = numel(ISI1)/600
result(result == 0) = NaN
end

Body:
I have added comments to a revised version of your code which hopefully make things clearer.

result = []
for a = 1:element
    for b = 1:cluster
        % Concatenate vertically (use ;) so no need to transpose later
        result = [result; AvSpike(dataset, a, b)];
        % Use a semi-colon at the end of line to supress outputs from command window
        % Changed variable name, don't call a variable the same as an in-built function
        mymean = nanmean(result);
        % r = result'  % This line removed as no need since we concatenated vertically
        % Again, using the semi-colon to supress output, not sure why num2str was used
        r(end+1) = mymean;
    end
end
disp(r) % Deliberately output the result!


问:
I have to pass values from on page to another page using jquery, see the below code, & suggest me changes
I have to pass values from one page to another page with jquery function (& in url). Problem is that some values are dates (with slashs), that's why its not working properly. And i also want encrypt those values.

```<code>    function gotoreq()
    {
         var baseurl = '<?php echo BASE_URL; ?>';
         var d1 = $('#date1').val(); /*date with slashs*/
         var d2 = $('#date2').val(); /*date with slashs*/
         var pid = $('#prop_ids').val();
         window.location.href = baseurl+'controller/method/'+d1+'/'+d2+'/'+pid;
    }
</code>```

Now I changed it to:

```<code>jQuery(document).on('click','#reqBook',function (event) {
             var d1 = $('#date1').val();
             d1 = d1.replace(/\//g, "-");
             var d2 = $('#date2').val();
             d2 = d2.replace(/\//g, "-");
             var pid = $('#prop_ids').val();
             window.location.href = BASE_URL+'controller/method/'+d1+'/'+d2+'/'+pid;
        });
</code>```

And In controller:

```<code>public function method($mov_in,$mov_out,$prp_id)
{
   echo $mov_in.', '.$mov_out.', '.$prp_id; exit;
}
</code>```

Its giving error of missing arguments

why this is happening?

答:
use below code

```<code>var date = $('#date1').val();
var d1 = date.replace(/\//g, "-");
</code>```

same for second date and then pass it to url

Body:
I have to pass values from one page to another page with jquery function (& in url). Problem is that some values are dates (with slashs), that's why its not working properly. And i also want encrypt those values.

    function gotoreq()
    {
         var baseurl = '<?php echo BASE_URL; ?>';
         var d1 = $('#date1').val(); /*date with slashs*/
         var d2 = $('#date2').val(); /*date with slashs*/
         var pid = $('#prop_ids').val();
         window.location.href = baseurl+'controller/method/'+d1+'/'+d2+'/'+pid;
    }

Now I changed it to:

jQuery(document).on('click','#reqBook',function (event) {
             var d1 = $('#date1').val();
             d1 = d1.replace(/\//g, "-");
             var d2 = $('#date2').val();
             d2 = d2.replace(/\//g, "-");
             var pid = $('#prop_ids').val();
             window.location.href = BASE_URL+'controller/method/'+d1+'/'+d2+'/'+pid;
        });

And In controller:

public function method($mov_in,$mov_out,$prp_id)
{
   echo $mov_in.', '.$mov_out.', '.$prp_id; exit;
}

Its giving error of missing arguments

why this is happening?

Body:
use below code

var date = $('#date1').val();
var d1 = date.replace(/\//g, "-");

same for second date and then pass it to url


问:
How to access data obtained by WebClient.DownloadDataAsync?
(This is a follow-up question to this one.)

I want to read an endless audio stream asynchronously, so that I can do my JIT analysis on the obtained data. Using a WebClient object's DownloadDataAsync method, I can initiate the download easily, see following Win form project:

```<code>Imports System.Net      'For WebClient

Public Class Form1
    Private WithEvents c As New WebClient()

    Protected Overrides Sub Finalize()
        c.Dispose()
        MyBase.Finalize()
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim u As New Uri("http://flower.serverhostingcenter.com:8433/;")
        c.DownloadDataAsync(u)
    End Sub

    Private Sub c_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles c.DownloadProgressChanged
        Debug.Print(e.BytesReceived.ToString & " B received.")
    End Sub
End Class
</code>```

and the stream seems to flow, as per the DownloadProgressChanged event's output to the immediate window:

```<code>2920 B received.
48180 B received.
56940 B received.
61320 B received.
87600 B received.
94900 B received.
160436 B received.
162060 B received.
227596 B received.
...
</code>```

However, I lack to find a method to also read the obtained data. As this is an endless stream, DownloadDataCompleted will never fire (nor does any other event except the one used).

How do I access the obtained data?

答:
Use OpenReadAsync in conjunction with the OpenReadCompleted event.

```<code>Private Sub c_OpenReadCompleted(sender As Object, e As OpenReadCompletedEventArgs) Handles c.OpenReadCompleted
   Dim stream = e.Result
End Sub
</code>```

Body:
(This is a follow-up question to this one.)

I want to read an endless audio stream asynchronously, so that I can do my JIT analysis on the obtained data. Using a WebClient object's DownloadDataAsync method, I can initiate the download easily, see following Win form project:

Imports System.Net      'For WebClient

Public Class Form1
    Private WithEvents c As New WebClient()

    Protected Overrides Sub Finalize()
        c.Dispose()
        MyBase.Finalize()
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim u As New Uri("http://flower.serverhostingcenter.com:8433/;")
        c.DownloadDataAsync(u)
    End Sub

    Private Sub c_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles c.DownloadProgressChanged
        Debug.Print(e.BytesReceived.ToString & " B received.")
    End Sub
End Class

and the stream seems to flow, as per the DownloadProgressChanged event's output to the immediate window:

2920 B received.
48180 B received.
56940 B received.
61320 B received.
87600 B received.
94900 B received.
160436 B received.
162060 B received.
227596 B received.
...

However, I lack to find a method to also read the obtained data. As this is an endless stream, DownloadDataCompleted will never fire (nor does any other event except the one used).

How do I access the obtained data?

Body:
Use OpenReadAsync in conjunction with the OpenReadCompleted event.

Private Sub c_OpenReadCompleted(sender As Object, e As OpenReadCompletedEventArgs) Handles c.OpenReadCompleted
   Dim stream = e.Result
End Sub


问:
How do I access APIs without using NetworkCredential in C#/UWP?
I got some of the APP's APIs.
When I use the browser to access these APIs, the browser popup window tell me to fill in the username/password, Then I tried to fill out my username/password and found that I passed the verification!
Then I tried to write the code

```<code>var myClientHandler = new HttpClientHandler();
myClientHandler.Credentials = new NetworkCredential("abc", "!@#");

this._client = new HttpClient(myClientHandler);
this._client.BaseAddress = new Uri("http://api.xxx.com");
var result = await this._client.GetStringAsync("some_api_foo.json");
</code>```

Run well!

(We know that if there are no NetworkCredential, there will be 401 unauthorized exception)

But I found out that the official APP could access some of the APIs without the user logging in. How does it work? Does it use a public account? Or is there another way to access the APIs?

答: It uses Windows integrated authentication (Kerberos) to authenticate your users without asking them for credentials</p>

Body:
I got some of the APP's APIs.
When I use the browser to access these APIs, the browser popup window tell me to fill in the username/password, Then I tried to fill out my username/password and found that I passed the verification!
Then I tried to write the code

var myClientHandler = new HttpClientHandler();
myClientHandler.Credentials = new NetworkCredential("abc", "!@#");

this._client = new HttpClient(myClientHandler);
this._client.BaseAddress = new Uri("http://api.xxx.com");
var result = await this._client.GetStringAsync("some_api_foo.json");

Run well!

(We know that if there are no NetworkCredential, there will be 401 unauthorized exception)

But I found out that the official APP could access some of the APIs without the user logging in. How does it work? Does it use a public account? Or is there another way to access the APIs?


问:
What should I use to make this kind of cell, so I can get each of them to segue to different ViewController?
Here is what I want to do (UI is showing down below), I want to perform different segue when I taped different cell in it. But I don't know what component I should use to get this done

I think to use the Collection View Controller, but it seems doest support static cells,  I want to use Customized UIVIew to do this, but it couldn't be dragged to another VC in StoryBoard, should I adopt some sort of Protocols of something to do this?

Please answer in Swift

After been helped

Turns out I just need to show the ViewController and haven't need segue yet, so here is the code.

```<code>let categories: [(name: String, pic: String, identifier: String)] = [
    ("人物",  "Wilson_head",      "CharactersVC"),
    ("动物",  "Pig",              "MobsVC"),
    ("植物",  "Bamboo_Patch",     "PlantsVC"),
    ("食谱",  "Crock_Pot_Build",  "RecipesVC")
]

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let currentCategory = categories[indexPath.row]
    let destVC: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: currentCategory.identifier)
    navigationController!.pushViewController(destVC, animated: true)
}
</code>```

答:
```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        if(indexPath.row == 0)
        {
            let objstory = self.storyboard?.instantiateViewController(withIdentifier: “your Story bord identifier”) as! Your View_ViewController

            self.navigationController?.pushViewController(objstory, animated: true)
        }

    }
</code>```

Body:
Here is what I want to do (UI is showing down below), I want to perform different segue when I taped different cell in it. But I don't know what component I should use to get this done

I think to use the Collection View Controller, but it seems doest support static cells,  I want to use Customized UIVIew to do this, but it couldn't be dragged to another VC in StoryBoard, should I adopt some sort of Protocols of something to do this?

Please answer in Swift

After been helped

Turns out I just need to show the ViewController and haven't need segue yet, so here is the code.

let categories: [(name: String, pic: String, identifier: String)] = [
    ("人物",  "Wilson_head",      "CharactersVC"),
    ("动物",  "Pig",              "MobsVC"),
    ("植物",  "Bamboo_Patch",     "PlantsVC"),
    ("食谱",  "Crock_Pot_Build",  "RecipesVC")
]

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let currentCategory = categories[indexPath.row]
    let destVC: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: currentCategory.identifier)
    navigationController!.pushViewController(destVC, animated: true)
}


问:
Django memcached won't cache a large template output
I am using Django with memcached.

In one of my templates, I added

```<code>{% cache 28800 template_browse_gene_list %}
...
{% endcache %}
</code>```

The stuff in the block is rather large, just over 1 MB; it is the result of iterating through an expensive SQL that returns lots of data. Since QuerySet is lazily evaluated, using the cache here avoids the SQL, if cache works.

When I use locmem as the cache backend, this works. I avoid the SQL and get cached result.

When I hookup memcached, with -I 4m setting, I get the following in the verbose output:

```<code><30 new auto-negotiating client connection
30: Client using the ascii protocol
....
<30 get template.cache.template_browse_gene_list.d41d8cd98f00b204e9800998ecf8427e
>30 END
<30 connection closed.
</code>```

The connection closed line is displayed as soon as the page is returned, but after quite a wait. I think basically when the SQL is done, the connection closed message appears. So basically, nothing gets into memcached for this entry. Again, this worked with locmem.

Any thoughts?

Thanks.

答:
Found this... explains it...

memcache won't store key/value because the value is too big

Body:
I am using Django with memcached.

In one of my templates, I added

{% cache 28800 template_browse_gene_list %}
...
{% endcache %}

The stuff in the block is rather large, just over 1 MB; it is the result of iterating through an expensive SQL that returns lots of data. Since QuerySet is lazily evaluated, using the cache here avoids the SQL, if cache works.

When I use locmem as the cache backend, this works. I avoid the SQL and get cached result.

When I hookup memcached, with -I 4m setting, I get the following in the verbose output:

<30 new auto-negotiating client connection
30: Client using the ascii protocol
....
<30 get template.cache.template_browse_gene_list.d41d8cd98f00b204e9800998ecf8427e
>30 END
<30 connection closed.

The connection closed line is displayed as soon as the page is returned, but after quite a wait. I think basically when the SQL is done, the connection closed message appears. So basically, nothing gets into memcached for this entry. Again, this worked with locmem.

Any thoughts?

Thanks.


答:
Collection View Controller doesn't support static cell.
But you can add static cell programmatically.

set your cell data and target(segue id) for each cell.
ex:

cellData[0].segue = "segueToHuman"

cellData[1].segue = "segueToAnimal"

add segues depend on your view controller(not on cell) like below:

create segue

segue setting

perform particular segue in didSelectItemAt indexPath

let segueID = cellData[indexPath.row].segue
performSegue(withIdentifier: segueID, sender: nil)

Title: What should I use to make this kind of cell, so I can get each of them to segue to different ViewController?


问:
Partition a spark dataframe based on column value?
i have a dataframe from a sql source which looks like:

```<code>User(id: Long, fname: String, lname: String, country: String)

[1, Fname1, Lname1, Belarus]
[2, Fname2, Lname2, Belgium]
[3, Fname3, Lname3, Austria]
[4, Fname4, Lname4, Australia]
</code>```

I want to partition and write this data into csv files where each partition is based on initial letter of the country, so Belarus and Belgium should be one in output file, Austria and Australia in other.

答:
Here is what you can do

```<code>import org.apache.spark.sql.functions._
//create a dataframe with demo data
val df = spark.sparkContext.parallelize(Seq(
  (1, "Fname1", "Lname1", "Belarus"),
  (2, "Fname2", "Lname2", "Belgium"),
  (3, "Fname3", "Lname3", "Austria"),
  (4, "Fname4", "Lname4", "Australia")
)).toDF("id", "fname","lname", "country")

//create a new column with the first letter of column
val result = df.withColumn("countryFirst", split($"country", "")(0))

//save the data with partitionby first letter of country

result.write.partitionBy("countryFirst").format("com.databricks.spark.csv").save("outputpath")
</code>```

Edited:
You can also use the substring which can increase the performance as suggested by Raphel as

substring(Column str, int pos, int len) Substring starts at pos and is
  of length len when str is String type or returns the slice of byte
  array that starts at pos in byte and is of length len when str is
  Binary type

```<code>val result = df.withColumn("firstCountry", substring($"country",1,1))
</code>```

and then use partitionby with write

Hope this solves your problem!

Body:
i have a dataframe from a sql source which looks like:

User(id: Long, fname: String, lname: String, country: String)

[1, Fname1, Lname1, Belarus]
[2, Fname2, Lname2, Belgium]
[3, Fname3, Lname3, Austria]
[4, Fname4, Lname4, Australia]

I want to partition and write this data into csv files where each partition is based on initial letter of the country, so Belarus and Belgium should be one in output file, Austria and Australia in other.

Body:
Here is what you can do

import org.apache.spark.sql.functions._
//create a dataframe with demo data
val df = spark.sparkContext.parallelize(Seq(
  (1, "Fname1", "Lname1", "Belarus"),
  (2, "Fname2", "Lname2", "Belgium"),
  (3, "Fname3", "Lname3", "Austria"),
  (4, "Fname4", "Lname4", "Australia")
)).toDF("id", "fname","lname", "country")

//create a new column with the first letter of column
val result = df.withColumn("countryFirst", split($"country", "")(0))

//save the data with partitionby first letter of country

result.write.partitionBy("countryFirst").format("com.databricks.spark.csv").save("outputpath")

Edited:
You can also use the substring which can increase the performance as suggested by Raphel as

substring(Column str, int pos, int len) Substring starts at pos and is
  of length len when str is String type or returns the slice of byte
  array that starts at pos in byte and is of length len when str is
  Binary type

val result = df.withColumn("firstCountry", substring($"country",1,1))

and then use partitionby with write

Hope this solves your problem!


问:
Dynamically add and position form items based on list in C#
So I'm trying to show a list of activities on my form.

The activity class looks like:

```<code> class Activity
    {
        public int ID { get; set; }
        public int IncidentID { get; set; }
        public string Description { get; set; }
        public int TimeSpent { get; set; }
        public Activity(int iD, int incidentID, string description, int timeSpent)
        {
            this.ID = iD;
            this.IncidentID = incidentID;
            this.Description = description;
            this.TimeSpent = timeSpent;
        }

    }
</code>```

My end goal is to have something like this mock up:

A number of activities, however, is chosen at runtime and can change (since it's based on an Incident, how many activities will be shown.

I have come up with the following code to dynamically fill the GUI:

```<code>   List<Activity> activities = new List<Activity>();
            activities.Add(new Activity(1, 2, "Mail client", 5));
            activities.Add(new Activity(2, 2, "Fix problem", 5));
            activities.Add(new Activity(3, 2, "Mail client for success", 10));
            activities.Add(new Activity(4, 2, "Mail client", 5));

            int n = activities.Count();
            Label[] labels = new Label[n];
            TextBox[] textboxes = new TextBox[n];
            CheckBox[] checkboxes = new CheckBox[n];

            for (int i = 0; i < n; i++)
            {
                labels[i] = new Label();
                labels[i].Text = activities.ElementAt(i).Description.ToString();

                textboxes[i] = new TextBox();
                textboxes[i].Text = activities.ElementAt(i).TimeSpent.ToString();

                checkboxes[i] = new CheckBox();
            }
</code>```

My first question was, how do we add these components to a GUI? Would I have another separate for-loop with a layout (or in my case, a group box) to store the items?

Secondly, how is it possible for me to link the checkbox with the activity. This because at a later stage, I would have to sum up the times of activities that have their checkbox checked. But would they be currently linked to an activity?

Thanks

答:
You can do the following:

1. In your Activities class have static StartX and StartY to keep controls coordinates and write DrawToForm method like below:

```<code>using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public class Activity
    {
        public int ID { get; set; }
        public int IncidentID { get; set; }
        public string Description { get; set; }
        public int TimeSpent { get; set; }

        public static int StartX { get; set; } = 10;
        public static int StartY { get; set; } = 10;
        public Activity(int iD, int incidentID, string description, int timeSpent)
        {
            this.ID = iD;
            this.IncidentID = incidentID;
            this.Description = description;
            this.TimeSpent = timeSpent;
        }
        public void DrawToForm(Form f)
        {

            var label = new Label();
            var textBox = new TextBox();
            var checkBox = new CheckBox();
            label.Text = Description.ToString();
            textBox.Text = TimeSpent.ToString();
            label.Left = StartX;
            label.Top = StartY;
            StartX += 100;// Move position to right
            textBox.Left = StartX;
            textBox.Top = StartY;
            StartX += 150;// Move position to right
            checkBox.Left = StartX;
            checkBox.Top = StartY;
            StartX = 10;// Reset to start
            StartY += 50;// Move position to down
            f.Controls.Add(label);
            f.Controls.Add(textBox);
            f.Controls.Add(checkBox);
        }
    }
}
</code>```

Now in Form's constructor or anyway you need you can do this:

```<code>public Form1()
{
    InitializeComponent();
    List<Activity> activities = new List<Activity>();
    activities.Add(new Activity(1, 2, "Mail client", 5));
    activities.Add(new Activity(2, 2, "Fix problem", 5));
    activities.Add(new Activity(3, 2, "Mail client for success", 10));
    activities.Add(new Activity(4, 2, "Mail client", 5));
    foreach(Activity a in activities)
    {
        a.DrawToForm(this);
    }
}
</code>```

I have not write part of the Labels for Header part as it's not dynamical.

Body:
So I'm trying to show a list of activities on my form.

The activity class looks like:

 class Activity
    {
        public int ID { get; set; }
        public int IncidentID { get; set; }
        public string Description { get; set; }
        public int TimeSpent { get; set; }
        public Activity(int iD, int incidentID, string description, int timeSpent)
        {
            this.ID = iD;
            this.IncidentID = incidentID;
            this.Description = description;
            this.TimeSpent = timeSpent;
        }

    }

My end goal is to have something like this mock up:

A number of activities, however, is chosen at runtime and can change (since it's based on an Incident, how many activities will be shown.

I have come up with the following code to dynamically fill the GUI:

   List<Activity> activities = new List<Activity>();
            activities.Add(new Activity(1, 2, "Mail client", 5));
            activities.Add(new Activity(2, 2, "Fix problem", 5));
            activities.Add(new Activity(3, 2, "Mail client for success", 10));
            activities.Add(new Activity(4, 2, "Mail client", 5));

            int n = activities.Count();
            Label[] labels = new Label[n];
            TextBox[] textboxes = new TextBox[n];
            CheckBox[] checkboxes = new CheckBox[n];

            for (int i = 0; i < n; i++)
            {
                labels[i] = new Label();
                labels[i].Text = activities.ElementAt(i).Description.ToString();

                textboxes[i] = new TextBox();
                textboxes[i].Text = activities.ElementAt(i).TimeSpent.ToString();

                checkboxes[i] = new CheckBox();
            }

My first question was, how do we add these components to a GUI? Would I have another separate for-loop with a layout (or in my case, a group box) to store the items?

Secondly, how is it possible for me to link the checkbox with the activity. This because at a later stage, I would have to sum up the times of activities that have their checkbox checked. But would they be currently linked to an activity?

Thanks

Body:
You can do the following:

1. In your Activities class have static StartX and StartY to keep controls coordinates and write DrawToForm method like below:

using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public class Activity
    {
        public int ID { get; set; }
        public int IncidentID { get; set; }
        public string Description { get; set; }
        public int TimeSpent { get; set; }

        public static int StartX { get; set; } = 10;
        public static int StartY { get; set; } = 10;
        public Activity(int iD, int incidentID, string description, int timeSpent)
        {
            this.ID = iD;
            this.IncidentID = incidentID;
            this.Description = description;
            this.TimeSpent = timeSpent;
        }
        public void DrawToForm(Form f)
        {

            var label = new Label();
            var textBox = new TextBox();
            var checkBox = new CheckBox();
            label.Text = Description.ToString();
            textBox.Text = TimeSpent.ToString();
            label.Left = StartX;
            label.Top = StartY;
            StartX += 100;// Move position to right
            textBox.Left = StartX;
            textBox.Top = StartY;
            StartX += 150;// Move position to right
            checkBox.Left = StartX;
            checkBox.Top = StartY;
            StartX = 10;// Reset to start
            StartY += 50;// Move position to down
            f.Controls.Add(label);
            f.Controls.Add(textBox);
            f.Controls.Add(checkBox);
        }
    }
}

Now in Form's constructor or anyway you need you can do this:

public Form1()
{
    InitializeComponent();
    List<Activity> activities = new List<Activity>();
    activities.Add(new Activity(1, 2, "Mail client", 5));
    activities.Add(new Activity(2, 2, "Fix problem", 5));
    activities.Add(new Activity(3, 2, "Mail client for success", 10));
    activities.Add(new Activity(4, 2, "Mail client", 5));
    foreach(Activity a in activities)
    {
        a.DrawToForm(this);
    }
}

I have not write part of the Labels for Header part as it's not dynamical.


问:
How to time different parts of a loop in Javascript
Not a duplicate of How to measure time taken by a function to execute. Please actually read my question before marking it as a duplicate of something else. Regardless, it's been answered.

I have code like

```<code>for (var i = 0 ; i < 10000 ; i++) {

    doSomething();

    doSomethingElse();

}
</code>```

And I want to know how much time each function inside the loop is taking overall. How do I measure that?

答:
```<code>var t1;
var t2;
var f1Time =0;
var f2Time =0;
for (var i = 0 ; i < 10000 ; i++) {
    t1 = performance.now();
    doSomething();
    t2  = performance.now();
    f1Time+= (t2 - t1);

    t1 = performance.now();
    doSomethingElse();
    t2  = performance.now();
    f1Time+=(t2 - t1);

}
</code>```

Body:
Not a duplicate of How to measure time taken by a function to execute. Please actually read my question before marking it as a duplicate of something else. Regardless, it's been answered.

I have code like

for (var i = 0 ; i < 10000 ; i++) {

    doSomething();

    doSomethingElse();

}

And I want to know how much time each function inside the loop is taking overall. How do I measure that?


问:
Calculate concordance and correlation in a text file
I have a file with 4 columns and 300 rows. Every Id occurs twice. Based on if column 4 is a match for both the 2 occurrences of ids (like id 2 and 3) calculate the percentage of matches. In this case 2 ids match perfectly (both the occurrences match) so it will be 2/4 =0.5. also calculate the percentage of single matches. And calculate correlation between column 2 & column 3. I know how to do it in excel but it is too time consuming as i have many files. How can we do it in linux? May be awk or sed.

My file contents as below

```<code>1 12 12 match
1 13 12 mismatch
2 5 5 match
2 4 4 match
3 17 17 match
3 12 12 match
4 12 13 mismatch
4 12 14 mismatch
</code>```

Desired output

```<code>Perfect match =0.5, Single match =1/8 =0.1, Correlation = 0.98
</code>```

答:
In awk (correlation calculation from https://www.mathsisfun.com/data/correlation.html). Two runs. First run calculates the means of $2 and $3, the second run all the other values:

```<code>$ awk '
NR==FNR {                 # first run
    v2s+=$2               # var $2 sum
    v3s+=$3               # var $3 sum
    next
}
FNR==1 {                  # for the first record of second run
    v2m=v2s/(NR-1)        # var 2 mean
    v3m=v3s/(NR-1)        # var 3 mean
}
{
    m[$1]+=($4=="match")  # count matches for each pair
    a=$2-v2m              # a as in the link above $2-mean
    b=$3-v3m              # b too as above
    ab+=a*b               # ab
    a2+=a*a               # a squared all summed up
    b2+=b*b               # b squared as well
}
END {
    for(i in m) {
        print i, m[i]
        if(m[i]==2)
            pm+=2         # perfect matches
        if(m[i]==1)
            sm+=2         # single matches
    }
    print "Perfect match= " pm/FNR " Single match= " sm/FNR " Correlation= " ab/sqrt(a2*b2)
}' file file
Perfect match= 0.5 Single match= 0.25 Correlation= 0.979748
</code>```

Body:
I have a file with 4 columns and 300 rows. Every Id occurs twice. Based on if column 4 is a match for both the 2 occurrences of ids (like id 2 and 3) calculate the percentage of matches. In this case 2 ids match perfectly (both the occurrences match) so it will be 2/4 =0.5. also calculate the percentage of single matches. And calculate correlation between column 2 & column 3. I know how to do it in excel but it is too time consuming as i have many files. How can we do it in linux? May be awk or sed.

My file contents as below

1 12 12 match
1 13 12 mismatch
2 5 5 match
2 4 4 match
3 17 17 match
3 12 12 match
4 12 13 mismatch
4 12 14 mismatch

Desired output

Perfect match =0.5, Single match =1/8 =0.1, Correlation = 0.98

Body:
In awk (correlation calculation from https://www.mathsisfun.com/data/correlation.html). Two runs. First run calculates the means of $2 and $3, the second run all the other values:

$ awk '
NR==FNR {                 # first run
    v2s+=$2               # var $2 sum
    v3s+=$3               # var $3 sum
    next
}
FNR==1 {                  # for the first record of second run
    v2m=v2s/(NR-1)        # var 2 mean
    v3m=v3s/(NR-1)        # var 3 mean
}
{
    m[$1]+=($4=="match")  # count matches for each pair
    a=$2-v2m              # a as in the link above $2-mean
    b=$3-v3m              # b too as above
    ab+=a*b               # ab
    a2+=a*a               # a squared all summed up
    b2+=b*b               # b squared as well
}
END {
    for(i in m) {
        print i, m[i]
        if(m[i]==2)
            pm+=2         # perfect matches
        if(m[i]==1)
            sm+=2         # single matches
    }
    print "Perfect match= " pm/FNR " Single match= " sm/FNR " Correlation= " ab/sqrt(a2*b2)
}' file file
Perfect match= 0.5 Single match= 0.25 Correlation= 0.979748


问:
Log4j2: How to write the log to a folder inside of WEB-INF?
I am using Tomcat. I want some Log4j2 log to be written inside the WEB-INF folder of the web application. For example:

```<code><RollingRandomAccessFile name="MyLog" fileName="${????}/logs/MyLog.log">
</code>```

How can I do that?

答:
This is a bad idea and not guaranteed to work for the following (incomplete) reasons:

Your application server might not even unpack a WAR file, so that you don't have a file system to write to: An application can easily run from a WAR file.

If you had an actual file system backed application: The next deployment of your application would wipe your log files

For security reasons it's a good argument to not have web applications being able to overwrite themselves - granted, you could only make a single log directory writeable, but IMHO this is not a good strategy (and the permissions would easily be changed with the next deployment)

Rather allocate a specific log directory to your application server and use it for output. There you can configure log rotation etc. in a well known place, rather than all over the various web applications that might follow this style of configuration.

Body:
I am using Tomcat. I want some Log4j2 log to be written inside the WEB-INF folder of the web application. For example:

<RollingRandomAccessFile name="MyLog" fileName="${????}/logs/MyLog.log">

How can I do that?


问:
Best way to approach loading a class from a comma delimited file
I am a fairly new to objective-c and to object oriented programming in general and have a theoretical, stylistic type question.  What I want to do is load a table of classes with entries from a comma delimited file.  The data in the file consists many entries made up of a short key followed by several string values, all delimited by commmas.

There are a million ways to do this but I'm asking what would be the way which would be best from a strictly theoretical point of view.  I'd like to stay away from any sort of XML coding for the moment but will probably eventually convert to that format once I get an entry program together.

I could use a function to get the 'next record' and pass a structure in and out of the function, create a new instance of the class, load it up from the structure, then add it into an array.  I'd use the stringWithContentsOfFile method to load the file into a string initially then use string functions and some pointers to march through the file to return the structure elements which I would then load into the class.

Does this seem like a reasonable way to do this in objective-c or is there a better method which is perhaps more theoretically sound which would work at least as well?

答:
You have a CSV file, and you want to read it?  There's some code for that.

The simplest approach would be something like:

```<code>#import "CHCSV.h"

NSString * csvFile = ...; //path to the CSV file
NSError * error = nil;
NSArray * contents = [NSArray arrayWithContentsOfCSVFile:csvFile
                                                encoding:NSUTF8StringEncoding
                                                   error:&error];
if (contents == nil) {
    NSLog (@"Error %@", error);
} else {
    for (NSArray * row in contents) {
        NSLog(@"CSV fields in this line: %@", row);
        // "row" contains all the fields (as NSStrings) that were present
        // on this line of CSV
    }
}
</code>```

Body:
You have a CSV file, and you want to read it?  There's some code for that.

The simplest approach would be something like:

#import "CHCSV.h"

NSString * csvFile = ...; //path to the CSV file
NSError * error = nil;
NSArray * contents = [NSArray arrayWithContentsOfCSVFile:csvFile
                                                encoding:NSUTF8StringEncoding
                                                   error:&error];
if (contents == nil) {
    NSLog (@"Error %@", error);
} else {
    for (NSArray * row in contents) {
        NSLog(@"CSV fields in this line: %@", row);
        // "row" contains all the fields (as NSStrings) that were present
        // on this line of CSV
    }
}


问:
How to Sum array value by key for chart?
Sorry, I see multiple similar solutions but i'm unable to implement them in my situations. I tried isset to check if value exist before sum but its giving me true value and not able to add its actual value. with bellow code it's repeating the same value as long as for loop running and giving me wrong sum value. Please correct me.

I want to add array value to single array by matching key..

I have this array...

```<code>Array(
[0] => Array
    (
        [Customer] => Array
            (
                [created_by] => 3
                [amount] => 475
            )

    )

[1] => Array
    (
        [Customer] => Array
            (
                [created_by] => 5
                [amount] => 199
            )

    )

[2] => Array
    (
        [Customer] => Array
            (
                [created_by] => 1
                [amount] => 199
                [refund_amount] => 200
                [upgrade_amount] => 199
            )

    )

[3] => Array
    (
        [Customer] => Array
            (
                [created_by] => 1
                [amount] => 199
            )

    )

[4] => Array
    (
        [Customer] => Array
            (
                [created_by] => 4
                [upgrade_amount] => 199
            )

    )
</code>```

)
I'm looking for result like this.....

```<code>Array(
[3] => Array
    (
        [sale] => 475
        [refund] => 0
        [upgrade] => 0
    )

[5] => Array
    (
        [sale] => 199
        [refund] => 0
        [upgrade] => 0
    )

[1] => Array
    (
        [sale] => 398
        [refund] => 200
        [upgrade] => 199
    )

[4] => Array
    (
        [sale] => 0
        [refund] => 0
        [upgrade] => 199
    )
</code>```

)

I'm using this code to get my result....

```<code>   foreach($records as $y_key => $y_value){
            //print_r($y_value);
            if(!isset($top_performer[$y_value['Customer']['created_by']])){
                $top_performer[$y_value['Customer']['created_by']]['sale'] = 0;
                $top_performer[$y_value['Customer']['created_by']]['refund'] = 0;
                $top_performer[$y_value['Customer']['created_by']]['upgrade'] = 0;
            }
             $top_performer[$y_value['Customer']['created_by']]['sale']+= $y_value['Customer']['amount'];
             $top_performer[$y_value['Customer']['created_by']]['refund']+= $y_value['Customer']['refund_amount'];
             $top_performer[$y_value['Customer']['created_by']]['upgrade']+=$y_value['Customer']['upgrade_amount'];

        }
</code>```

答:
Your code is looking good, you only need to check if array element exists</p>

```<code>   foreach($records as $y_key => $y_value){
            if(!isset($top_performer[$y_value['Customer']['created_by']])){
                $top_performer[$y_value['Customer']['created_by']]['sale'] = 0;
                $top_performer[$y_value['Customer']['created_by']]['refund'] = 0;
                $top_performer[$y_value['Customer']['created_by']]['upgrade'] = 0;
            }
             $top_performer[$y_value['Customer']['created_by']]['sale'] += isset($y_value['Customer']['amount']) ? $y_value['Customer']['amount'] : 0;
             $top_performer[$y_value['Customer']['created_by']]['refund'] += isset($y_value['Customer']['refund_amount']) ? $y_value['Customer']['refund_amount'] : 0;
             $top_performer[$y_value['Customer']['created_by']]['upgrade'] += isset($y_value['Customer']['upgrade_amount']) ? $y_value['Customer']['upgrade_amount'] : 0;
    }
</code>```

Body:
Sorry, I see multiple similar solutions but i'm unable to implement them in my situations. I tried isset to check if value exist before sum but its giving me true value and not able to add its actual value. with bellow code it's repeating the same value as long as for loop running and giving me wrong sum value. Please correct me.

I want to add array value to single array by matching key..

I have this array...

Array(
[0] => Array
    (
        [Customer] => Array
            (
                [created_by] => 3
                [amount] => 475
            )

    )

[1] => Array
    (
        [Customer] => Array
            (
                [created_by] => 5
                [amount] => 199
            )

    )

[2] => Array
    (
        [Customer] => Array
            (
                [created_by] => 1
                [amount] => 199
                [refund_amount] => 200
                [upgrade_amount] => 199
            )

    )

[3] => Array
    (
        [Customer] => Array
            (
                [created_by] => 1
                [amount] => 199
            )

    )

[4] => Array
    (
        [Customer] => Array
            (
                [created_by] => 4
                [upgrade_amount] => 199
            )

    )

)
I'm looking for result like this.....

Array(
[3] => Array
    (
        [sale] => 475
        [refund] => 0
        [upgrade] => 0
    )

[5] => Array
    (
        [sale] => 199
        [refund] => 0
        [upgrade] => 0
    )

[1] => Array
    (
        [sale] => 398
        [refund] => 200
        [upgrade] => 199
    )

[4] => Array
    (
        [sale] => 0
        [refund] => 0
        [upgrade] => 199
    )

)

I'm using this code to get my result....

   foreach($records as $y_key => $y_value){
            //print_r($y_value);
            if(!isset($top_performer[$y_value['Customer']['created_by']])){
                $top_performer[$y_value['Customer']['created_by']]['sale'] = 0;
                $top_performer[$y_value['Customer']['created_by']]['refund'] = 0;
                $top_performer[$y_value['Customer']['created_by']]['upgrade'] = 0;
            }
             $top_performer[$y_value['Customer']['created_by']]['sale']+= $y_value['Customer']['amount'];
             $top_performer[$y_value['Customer']['created_by']]['refund']+= $y_value['Customer']['refund_amount'];
             $top_performer[$y_value['Customer']['created_by']]['upgrade']+=$y_value['Customer']['upgrade_amount'];

        }

Body:
Your code is looking good, you only need to check if array element exists

   foreach($records as $y_key => $y_value){
            if(!isset($top_performer[$y_value['Customer']['created_by']])){
                $top_performer[$y_value['Customer']['created_by']]['sale'] = 0;
                $top_performer[$y_value['Customer']['created_by']]['refund'] = 0;
                $top_performer[$y_value['Customer']['created_by']]['upgrade'] = 0;
            }
             $top_performer[$y_value['Customer']['created_by']]['sale'] += isset($y_value['Customer']['amount']) ? $y_value['Customer']['amount'] : 0;
             $top_performer[$y_value['Customer']['created_by']]['refund'] += isset($y_value['Customer']['refund_amount']) ? $y_value['Customer']['refund_amount'] : 0;
             $top_performer[$y_value['Customer']['created_by']]['upgrade'] += isset($y_value['Customer']['upgrade_amount']) ? $y_value['Customer']['upgrade_amount'] : 0;
    }


问:
How to do not repeat a razor code in an ASP.NET MVC "edit" view for each model property?
If you use ASP.NET MVC, then the following code must be familiar to you:

```<code><div class="row">
    <div class="form-sm-4">
        @Html.LabelFor(m => m.att)
    </div>
    <div class="form-sm-8">
        @Html.EditorFor(m => m.att, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(m => m.att)
    </div>
</div>
</code>```

This is a basic input group set with label, input and validation message.

Today I'm facing a POCO class with dozens of attributes. I mean It has N number of properties in model class. In order to build a HTML he has to repeat above code snippet N times. If there is change in DOM he has to manually change all CSS class or even certain HTML.

I am looking for a solution wherein he don't have to repeat above code snippet for dozens of model propeties.

答:
Create classes:

```<code>public static class PropertyExtensions
{
    public static ModelWrapper<T> Wrap<T>(this T property, string propertyName)
    {
        var genericType = typeof(ModelWrapper<>);
        var specificType = genericType.MakeGenericType(typeof(T));

        var wrappedPropertyModel = (ModelWrapper<T>)Activator.CreateInstance(specificType);

        wrappedPropertyModel.ModelProperty = property;
        wrappedPropertyModel.PropertyName = propertyName;

        return wrappedPropertyModel;
    }
}

public class ModelWrapper<T>
{
    public string PropertyName { get; set; }
    public T ModelProperty { get; set; }
}
</code>```

Create a partial view:

```<code>@model ModelWrapper<object>

<div class="row">
    <div class="form-sm-4">
        @Html.Label(Model.PropertyName)
    </div>
    <div class="form-sm-8">
        @Html.EditorFor(m => m.ModelProperty, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(m => m.ModelProperty)
    </div>
</div>
</code>```

In the main View:

```<code>@Html.Partial("_PartialViewName", ((object)Model.YourVariableProperty).Wrap("YourVariableProperty"))
</code>```

Body:
If you use ASP.NET MVC, then the following code must be familiar to you:

        @Html.LabelFor(m => m.att)

        @Html.EditorFor(m => m.att, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(m => m.att)

This is a basic input group set with label, input and validation message.

Today I'm facing a POCO class with dozens of attributes. I mean It has N number of properties in model class. In order to build a HTML he has to repeat above code snippet N times. If there is change in DOM he has to manually change all CSS class or even certain HTML.

I am looking for a solution wherein he don't have to repeat above code snippet for dozens of model propeties.

Body:
Create classes:

public static class PropertyExtensions
{
    public static ModelWrapper<T> Wrap<T>(this T property, string propertyName)
    {
        var genericType = typeof(ModelWrapper<>);
        var specificType = genericType.MakeGenericType(typeof(T));

        var wrappedPropertyModel = (ModelWrapper<T>)Activator.CreateInstance(specificType);

        wrappedPropertyModel.ModelProperty = property;
        wrappedPropertyModel.PropertyName = propertyName;

        return wrappedPropertyModel;
    }
}

public class ModelWrapper<T>
{
    public string PropertyName { get; set; }
    public T ModelProperty { get; set; }
}

Create a partial view:

@model ModelWrapper<object>

<div class="row">
    <div class="form-sm-4">
        @Html.Label(Model.PropertyName)
    </div>
    <div class="form-sm-8">
        @Html.EditorFor(m => m.ModelProperty, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(m => m.ModelProperty)
    </div>
</div>

In the main View:

@Html.Partial("_PartialViewName", ((object)Model.YourVariableProperty).Wrap("YourVariableProperty"))


问:
exc bad instruction code exc i386 invop swift With NSArray
I faced "exc bad instruction code exc i386 invop" issue. I struggling to solve this issue. If any one know this ping me...

Issue

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("didselect")

    if(tableView == self.tabledata){
        print("Entered into tableview of listing")
        let savearr : NSArray = UserDefaults.standard.object(forKey: "savedarray") as! NSArray

        let addarr: NSArray = savearr.value(forKeyPath:"country") as! NSArray
        let sumarr: NSArray = savearr.value(forKeyPath:"description") as! NSArray
        let titarr: NSArray = savearr.value(forKeyPath:"title") as! NSArray
</code>```

Then I Tried This code:

```<code>    if let savearr : NSArray = UserDefaults.standard.object(forKey: "savedarray") as? NSArray
        {
        let addarr: NSArray = savearr.value(forKeyPath:"country") as! NSArray
        let sumarr: NSArray = savearr.value(forKeyPath:"description") as! NSArray
        let titarr: NSArray = savearr.value(forKeyPath:"title") as! NSArray
    let MenuViewController = self.storyboard?.instantiateViewController(withIdentifier: "five") as! FiveStepsViewController

    MenuViewController.writeTitleString = String(describing: titarr[indexPath.row])

    MenuViewController.writeSummaryString = String(describing: sumarr[indexPath.row])

    MenuViewController.writeAddressString = String(describing: addarr[indexPath.row])

    //MenuViewController.writePriceString = String(describing: self.appDelegate.fivepricearray[indexPath.row])

        self.present(MenuViewController, animated: true, completion: nil)
        }
        else {
            print("Error Occured while listing")
        }
</code>```

Its always goes to else part..

答:
```<code> let MenuViewController = self.storyboard?.instantiateViewController(withIdentifier: "five") as! FiveStepsViewController

  if let savearr : NSArray = UserDefaults.standard.object(forKey: "savedarray") as? NSArray
    {
    let addarr: NSArray = savearr.value(forKeyPath:"country") as? NSArray
    let sumarr: NSArray = savearr.value(forKeyPath:"description") as? NSArray
    let titarr: NSArray = savearr.value(forKeyPath:"title") as? NSArray

   MenuViewController.writeTitleString = String(describing: titarr[indexPath.row])

   MenuViewController.writeSummaryString = String(describing: sumarr[indexPath.row])

   MenuViewController.writeAddressString = String(describing: addarr[indexPath.row])

    }
    else {
        print("Error Occured while listing")
    }

 self.present(MenuViewController, animated: true, completion: nil)
</code>```

Body:
I faced "exc bad instruction code exc i386 invop" issue. I struggling to solve this issue. If any one know this ping me...

Issue

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("didselect")

    if(tableView == self.tabledata){
        print("Entered into tableview of listing")
        let savearr : NSArray = UserDefaults.standard.object(forKey: "savedarray") as! NSArray

        let addarr: NSArray = savearr.value(forKeyPath:"country") as! NSArray
        let sumarr: NSArray = savearr.value(forKeyPath:"description") as! NSArray
        let titarr: NSArray = savearr.value(forKeyPath:"title") as! NSArray

Then I Tried This code:

    if let savearr : NSArray = UserDefaults.standard.object(forKey: "savedarray") as? NSArray
        {
        let addarr: NSArray = savearr.value(forKeyPath:"country") as! NSArray
        let sumarr: NSArray = savearr.value(forKeyPath:"description") as! NSArray
        let titarr: NSArray = savearr.value(forKeyPath:"title") as! NSArray
    let MenuViewController = self.storyboard?.instantiateViewController(withIdentifier: "five") as! FiveStepsViewController

    MenuViewController.writeTitleString = String(describing: titarr[indexPath.row])

    MenuViewController.writeSummaryString = String(describing: sumarr[indexPath.row])

    MenuViewController.writeAddressString = String(describing: addarr[indexPath.row])

    //MenuViewController.writePriceString = String(describing: self.appDelegate.fivepricearray[indexPath.row])

        self.present(MenuViewController, animated: true, completion: nil)
        }
        else {
            print("Error Occured while listing")
        }

Its always goes to else part..


问:
C# AppSettingsReader: "reread" values into the AppSettingsReader (runtime)?
In my application, I need to change some value ("Environment") in appSetting of app.config at runtime.

I use AppSettingsReader

```<code>    private static AppSettingsReader _settingReader;

    public static AppSettingsReader SettingReader
    {
        get
        {
            if (_settingReader == null)
            {
                _settingReader = new AppSettingsReader();
            }
            return _settingReader;
        }
    }
</code>```

Then at some stage I do this

```<code>        config.AppSettings.Settings[AppSettingString.Environment.ToString()].Value = newEnvironment.ToString();
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");
</code>```

However, next time I try to read "Environment" like this

```<code>       string environment = (string)SettingReader.GetValue(AppSettingString.Environment.ToString(), typeof(System.String));
</code>```

I end up with the old value of Environment.

I noticed that I can fix this by doing

```<code>_settingReader = new AppSettingsReader();
</code>```

before I read "Environment".

But I think creating a new instance is not the proper approach.

Maybe there is a way to let my SettingReader know, that the values have changed to use the same instance of it, but with refreshed values?

(Not a project-breaking question obviously, more of an educational one)

答:
AppSettingsReader doesn't seem to have any method to reload from disk. It just derives from Object. Creating a new instance seems to be the only thing that would work... I may be wrong, but AppSettings are supposed to be read-only values for your app. More like configuration parameters for your application that can be tweaked before startup.

For read-write application settings, I think the Settings mechanism with IDE support (System.Configuration.ApplicationSettingsBase) would be the preferred approach. This has Save and Reload methods. The designer-gen class makes the code far more readable too..

Double click on the Properties Node under your Project in Solution Explorer. Find the Settings tab.

Instead of

```<code>sEnvironment = (string)SettingReader.GetValue(AppSettingString.Environment.ToString(), typeof(System.String));
</code>```

you could have typed properties like

```<code>sEnvironment = Properties.Settings.Default.Environment;
</code>```

The designer generated class exposes a synchronized singleton instance via the Default property.. which should mean you don't need to reload.. you'd always get the latest value within the application.

OwnerDisplayName: Evgeny

Body:
In my application, I need to change some value ("Environment") in appSetting of app.config at runtime.

I use AppSettingsReader

    private static AppSettingsReader _settingReader;

    public static AppSettingsReader SettingReader
    {
        get
        {
            if (_settingReader == null)
            {
                _settingReader = new AppSettingsReader();
            }
            return _settingReader;
        }
    }

Then at some stage I do this

        config.AppSettings.Settings[AppSettingString.Environment.ToString()].Value = newEnvironment.ToString();
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");

However, next time I try to read "Environment" like this

       string environment = (string)SettingReader.GetValue(AppSettingString.Environment.ToString(), typeof(System.String));

I end up with the old value of Environment.

I noticed that I can fix this by doing

_settingReader = new AppSettingsReader();

before I read "Environment".

But I think creating a new instance is not the proper approach.

Maybe there is a way to let my SettingReader know, that the values have changed to use the same instance of it, but with refreshed values?

(Not a project-breaking question obviously, more of an educational one)

Body:
AppSettingsReader doesn't seem to have any method to reload from disk. It just derives from Object. Creating a new instance seems to be the only thing that would work... I may be wrong, but AppSettings are supposed to be read-only values for your app. More like configuration parameters for your application that can be tweaked before startup.

For read-write application settings, I think the Settings mechanism with IDE support (System.Configuration.ApplicationSettingsBase) would be the preferred approach. This has Save and Reload methods. The designer-gen class makes the code far more readable too..

Double click on the Properties Node under your Project in Solution Explorer. Find the Settings tab.

Instead of

sEnvironment = (string)SettingReader.GetValue(AppSettingString.Environment.ToString(), typeof(System.String));

you could have typed properties like

sEnvironment = Properties.Settings.Default.Environment;

The designer generated class exposes a synchronized singleton instance via the Default property.. which should mean you don't need to reload.. you'd always get the latest value within the application.

OwnerDisplayName: Gishu


问:
Why does this code return a list index error?
Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:

```<code>if result[i][0] < 0 or result[i][0] >= board.dimensions:
    result.pop(i)
</code>```

when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statement it throws the errors. Why is this happening?

```<code>def neighborGen(row,col,board):
    """
    returns lists of coords of neighbors, in order of up, down, left, right
    """

    result = []
    result.append([row-1 , col])
    result.append([row+1 , col])
    result.append([row , col-1])
    result.append([row , col+1])

     #prune off invalid neighbors (such as (0,-1), etc etc)
     for i in range(len(result)):
        if result[i][0] < 0 or result[i][0] >= board.dimensions:
            result.pop(i)
        if result[i][1] < 0 or result[i][1] >= board.dimensions:
            result.pop(i)

    return result
</code>```

答:
As others said, the indexes of the remaining elements change when you remove elements from the middle of the list. To avoid problems, you could process the elements from last index to first:

```<code>for i in range(len(result)-1, -1, -1):
   ...
</code>```

Now, when the current element is removed, only indexes for already processed elements change. Since those elements are already processed and don't need to be accessed again, it doesn't matter if their indexes are no longer valid.

Body:
Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:

if result[i][0] < 0 or result[i][0] >= board.dimensions:
    result.pop(i)

when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statement it throws the errors. Why is this happening?

def neighborGen(row,col,board):
    """
    returns lists of coords of neighbors, in order of up, down, left, right
    """

    result = []
    result.append([row-1 , col])
    result.append([row+1 , col])
    result.append([row , col-1])
    result.append([row , col+1])

     #prune off invalid neighbors (such as (0,-1), etc etc)
     for i in range(len(result)):
        if result[i][0] < 0 or result[i][0] >= board.dimensions:
            result.pop(i)
        if result[i][1] < 0 or result[i][1] >= board.dimensions:
            result.pop(i)

    return result

Body:
As others said, the indexes of the remaining elements change when you remove elements from the middle of the list. To avoid problems, you could process the elements from last index to first:

for i in range(len(result)-1, -1, -1):
   ...

Now, when the current element is removed, only indexes for already processed elements change. Since those elements are already processed and don't need to be accessed again, it doesn't matter if their indexes are no longer valid.


问:
Openlayers 4: WFS Format always flips coordinates on EPSG:4326
When using the ol.format.WFS (both GML2 and GML3) to read features they will always be assumed to be in YX if the projection is EPSG:4326. So OL flips them. I am using this with Geoserver 2.11 and, as of this version, the server can send the coordinates as XY, depending on how you pass the projection. You can read about it here.

Going through the OL code I can see it reads the projection from the xml and it decides to flip it based on the axis orientation, which for 4326 is neu, resulting in a flip.

The problem is my configuration depends on the client and the server might be already sending XY. I was wondering if this is a bug with OpenLayers or if it was a decision made.

Is there a way to prevent it from doing it?

答:
You can override it with a custom projection object

```<code>/ override the axis orientation for WMS GetFeatureInfo
var proj = new ol.proj.Projection({
  code: 'http://www.opengis.net/gml/srs/epsg.xml#4326',
  axis: 'enu'
});
ol.proj.addEquivalentProjections([ol.proj.get('EPSG:4326'), proj]);
</code>```

Just make sure that the string for code matches what is in your WFS/GML document.

Body:
You can override it with a custom projection object

/ override the axis orientation for WMS GetFeatureInfo
var proj = new ol.proj.Projection({
  code: 'http://www.opengis.net/gml/srs/epsg.xml#4326',
  axis: 'enu'
});
ol.proj.addEquivalentProjections([ol.proj.get('EPSG:4326'), proj]);

Just make sure that the string for code matches what is in your WFS/GML document.