问:
Need to use shared_ptr?
I have two classes: Lattice and ModelGUI. I want to pass function from Lattice to GUI as a callback. I implemented Lattice as unique_ptr. Some code:

ModelGUI.h:

```<code>using CheckTypeClbk = std::function<Enums::AgentType(int)>;
ModelGUI(const Matrix* matrix_, CheckTypeClbk callback, float windowHeight_, float windowWidth_, float latticeWidth_);
</code>```

main.cpp:

```<code>std::unique_ptr<ILattice> lattice(new Lattice(5, qMap));
ModelGUI gui(lattice->getLattice(), std::bind(&ILattice::checkAgentType, lattice, std::placeholders::_1),
800, 1200, 800);
</code>```

With this implementation I got strange compilation errors about templates:

```<code>1>main.cpp
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\xutility(390): error C2664: 'std::tuple<std::unique_ptr<ILattice,std::default_delete<_Ty>>,std::_Ph<1>>::tuple(std::tuple<std::unique_ptr<_Ty,std::default_delete<_Ty>>,std::_Ph<1>> &&)': cannot convert argument 1 from 'std::unique_ptr<ILattice,std::default_delete<_Ty>>' to 'std::allocator_arg_t'
1>        with
1>        [
1>            _Ty=ILattice
1>        ]
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\xutility(389): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\functional(1902): note: see reference to function template instantiation 'std::_Compressed_pair<Enums::AgentType (__cdecl ILattice::* )(int),std::tuple<std::unique_ptr<ILattice,std::default_delete<_Ty>>,std::_Ph<1>>,false>::_Compressed_pair<Enums::AgentType(__cdecl ILattice::* )(int),_Cv_TiD&,const std::_Ph<1>&>(std::_One_then_variadic_args_t,_Other1 &&,_Cv_TiD &,const std::_Ph<1> &)' being compiled
1>        with
1>        [
1>            _Ty=ILattice,
1>            _Cv_TiD=std::unique_ptr<ILattice,std::default_delete<ILattice>>,
1>            _Other1=Enums::AgentType (__cdecl ILattice::* )(int)
1>        ]
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\functional(1903): note: see reference to function template instantiation 'std::_Compressed_pair<Enums::AgentType (__cdecl ILattice::* )(int),std::tuple<std::unique_ptr<ILattice,std::default_delete<_Ty>>,std::_Ph<1>>,false>::_Compressed_pair<Enums::AgentType(__cdecl ILattice::* )(int),_Cv_TiD&,const std::_Ph<1>&>(std::_One_then_variadic_args_t,_Other1 &&,_Cv_TiD &,const std::_Ph<1> &)' being compiled
1>        with
1>        [
1>            _Ty=ILattice,
1>            _Cv_TiD=std::unique_ptr<ILattice,std::default_delete<ILattice>>,
1>            _Other1=Enums::AgentType (__cdecl ILattice::* )(int)
1>        ]
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\functional(1902): note: while compiling class template member function 'std::_Binder<std::_Unforced,Enums::AgentType (__cdecl ILattice::* )(int),std::unique_ptr<ILattice,std::default_delete<_Ty>> &,const std::_Ph<1> &>::_Binder(_Fx &&,std::unique_ptr<_Ty,std::default_delete<_Ty>> &,const std::_Ph<1> &)'
1>        with
1>        [
1>            _Ty=ILattice,
1>            _Fx=Enums::AgentType (__cdecl ILattice::* )(int)
1>        ]
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\functional(1929): note: see reference to function template instantiation 'std::_Binder<std::_Unforced,Enums::AgentType (__cdecl ILattice::* )(int),std::unique_ptr<ILattice,std::default_delete<_Ty>> &,const std::_Ph<1> &>::_Binder(_Fx &&,std::unique_ptr<_Ty,std::default_delete<_Ty>> &,const std::_Ph<1> &)' being compiled
1>        with
1>        [
1>            _Ty=ILattice,
1>            _Fx=Enums::AgentType (__cdecl ILattice::* )(int)
1>        ]
1>d:\predator-prey\predator-prey\main.cpp(16): note: see reference to class template instantiation 'std::_Binder<std::_Unforced,Enums::AgentType (__cdecl ILattice::* )(int),std::unique_ptr<ILattice,std::default_delete<_Ty>> &,const std::_Ph<1> &>' being compiled
1>        with
1>        [
1>            _Ty=ILattice
1>        ]
</code>```

But when I am using shared_ptr instead of unique_ptr, everything works fine. Is a good practice? I've heard to avoid shared_ptr as much as I can, unless they are totally necessary.

答:
You are passing std::unique_ptr by value and it's always a bad idea, because it doesn't have a copy constructor.

Why doesn't your code even compile? It seems that passing std::unique_ptr to a bound function is a long-living bug of visual studio.

Title: Need to use shared_ptr?

Body:
I have two classes: Lattice and ModelGUI. I want to pass function from Lattice to GUI as a callback. I implemented Lattice as unique_ptr. Some code:

ModelGUI.h:

using CheckTypeClbk = std::function<Enums::AgentType(int)>;
ModelGUI(const Matrix* matrix_, CheckTypeClbk callback, float windowHeight_, float windowWidth_, float latticeWidth_);

main.cpp:

std::unique_ptr<ILattice> lattice(new Lattice(5, qMap));
ModelGUI gui(lattice->getLattice(), std::bind(&ILattice::checkAgentType, lattice, std::placeholders::_1),
800, 1200, 800);

With this implementation I got strange compilation errors about templates:

1>main.cpp
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\xutility(390): error C2664: 'std::tuple<std::unique_ptr<ILattice,std::default_delete<_Ty>>,std::_Ph<1>>::tuple(std::tuple<std::unique_ptr<_Ty,std::default_delete<_Ty>>,std::_Ph<1>> &&)': cannot convert argument 1 from 'std::unique_ptr<ILattice,std::default_delete<_Ty>>' to 'std::allocator_arg_t'
1>        with
1>        [
1>            _Ty=ILattice
1>        ]
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\xutility(389): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\functional(1902): note: see reference to function template instantiation 'std::_Compressed_pair<Enums::AgentType (__cdecl ILattice::* )(int),std::tuple<std::unique_ptr<ILattice,std::default_delete<_Ty>>,std::_Ph<1>>,false>::_Compressed_pair<Enums::AgentType(__cdecl ILattice::* )(int),_Cv_TiD&,const std::_Ph<1>&>(std::_One_then_variadic_args_t,_Other1 &&,_Cv_TiD &,const std::_Ph<1> &)' being compiled
1>        with
1>        [
1>            _Ty=ILattice,
1>            _Cv_TiD=std::unique_ptr<ILattice,std::default_delete<ILattice>>,
1>            _Other1=Enums::AgentType (__cdecl ILattice::* )(int)
1>        ]
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\functional(1903): note: see reference to function template instantiation 'std::_Compressed_pair<Enums::AgentType (__cdecl ILattice::* )(int),std::tuple<std::unique_ptr<ILattice,std::default_delete<_Ty>>,std::_Ph<1>>,false>::_Compressed_pair<Enums::AgentType(__cdecl ILattice::* )(int),_Cv_TiD&,const std::_Ph<1>&>(std::_One_then_variadic_args_t,_Other1 &&,_Cv_TiD &,const std::_Ph<1> &)' being compiled
1>        with
1>        [
1>            _Ty=ILattice,
1>            _Cv_TiD=std::unique_ptr<ILattice,std::default_delete<ILattice>>,
1>            _Other1=Enums::AgentType (__cdecl ILattice::* )(int)
1>        ]
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\functional(1902): note: while compiling class template member function 'std::_Binder<std::_Unforced,Enums::AgentType (__cdecl ILattice::* )(int),std::unique_ptr<ILattice,std::default_delete<_Ty>> &,const std::_Ph<1> &>::_Binder(_Fx &&,std::unique_ptr<_Ty,std::default_delete<_Ty>> &,const std::_Ph<1> &)'
1>        with
1>        [
1>            _Ty=ILattice,
1>            _Fx=Enums::AgentType (__cdecl ILattice::* )(int)
1>        ]
1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\functional(1929): note: see reference to function template instantiation 'std::_Binder<std::_Unforced,Enums::AgentType (__cdecl ILattice::* )(int),std::unique_ptr<ILattice,std::default_delete<_Ty>> &,const std::_Ph<1> &>::_Binder(_Fx &&,std::unique_ptr<_Ty,std::default_delete<_Ty>> &,const std::_Ph<1> &)' being compiled
1>        with
1>        [
1>            _Ty=ILattice,
1>            _Fx=Enums::AgentType (__cdecl ILattice::* )(int)
1>        ]
1>d:\predator-prey\predator-prey\main.cpp(16): note: see reference to class template instantiation 'std::_Binder<std::_Unforced,Enums::AgentType (__cdecl ILattice::* )(int),std::unique_ptr<ILattice,std::default_delete<_Ty>> &,const std::_Ph<1> &>' being compiled
1>        with
1>        [
1>            _Ty=ILattice
1>        ]

But when I am using shared_ptr instead of unique_ptr, everything works fine. Is a good practice? I've heard to avoid shared_ptr as much as I can, unless they are totally necessary.


来源: stackexchange

问:
How to loop through similar vars files in an Ansible playbook
I need to create a single ansible playbook that will loop through multiple vars files in a single directory and use each configuration individually in a rest API POST.

Ideally, with the following vars files...

```<code>/my/vars/dir
  - my_pen.yml
      pen:
        color: "blue"

  - her_pen.yml
      pen:
        color: "red"

  - his_pen.yml
      pen:
        color: "green"
</code>```

...my playbook would execute a POST for each pen. Unfortunately, all files contain a configuration for the same object type so an include_vars task would only retain the configuration for "his_pen".

I've been able to get a list of all files in the directory using find:

```<code>- name: "find config files"
  find:
    paths: /path/to/config/files
    patterns: '*.yml'
  register: config_files
</code>```

I have a task that can do the POST:

```<code>- name: Do post
  uri:
    url: "{{ rest_api_endpoint }}"
    method: POST
    user: "{{ username }}"
    password: "{{ password }}"
    body: "{{ pen }}"
    body_format: json
    return_content: yes
    status_code: 200
  register: post_result
</code>```

Now I just need to fuse the two. Is this possible? I can't change the file structure, so I have to use what's in place.

Thoughts?

答:
Let's create the list of pens first and then loop the list. The play below

```<code>- set_fact:
    pens: "{{ pens|default([]) + [ lookup('file', item)|from_yaml ] }}"
  loop: "{{ lookup('fileglob', 'vars/*.yml', wantlist=True) }}"
- debug:
    msg: "{{ item }}"
  loop: "{{ pens }}"
</code>```

gives (abridged):

```<code>ok: [localhost] => (item={'pen': {'color': u'blue'}}) => {
    "msg": {
        "pen": {
            "color": "blue"
        }
    }
}
ok: [localhost] => (item={'pen': {'color': u'green'}}) => {
    "msg": {
        "pen": {
            "color": "green"
        }
    }
}
ok: [localhost] => (item={'pen': {'color': u'red'}}) => {
    "msg": {
        "pen": {
            "color": "red"
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to create a single ansible playbook that will loop through multiple vars files in a single directory and use each configuration individually in a rest API POST.

Ideally, with the following vars files...

/my/vars/dir
  - my_pen.yml
      pen:
        color: "blue"

  - her_pen.yml
      pen:
        color: "red"

  - his_pen.yml
      pen:
        color: "green"

...my playbook would execute a POST for each pen. Unfortunately, all files contain a configuration for the same object type so an include_vars task would only retain the configuration for "his_pen".

I've been able to get a list of all files in the directory using find:

- name: "find config files"
  find:
    paths: /path/to/config/files
    patterns: '*.yml'
  register: config_files

I have a task that can do the POST:

- name: Do post
  uri:
    url: "{{ rest_api_endpoint }}"
    method: POST
    user: "{{ username }}"
    password: "{{ password }}"
    body: "{{ pen }}"
    body_format: json
    return_content: yes
    status_code: 200
  register: post_result

Now I just need to fuse the two. Is this possible? I can't change the file structure, so I have to use what's in place.

Thoughts?

Body:
Let's create the list of pens first and then loop the list. The play below

- set_fact:
    pens: "{{ pens|default([]) + [ lookup('file', item)|from_yaml ] }}"
  loop: "{{ lookup('fileglob', 'vars/*.yml', wantlist=True) }}"
- debug:
    msg: "{{ item }}"
  loop: "{{ pens }}"

gives (abridged):

ok: [localhost] => (item={'pen': {'color': u'blue'}}) => {
    "msg": {
        "pen": {
            "color": "blue"
        }
    }
}
ok: [localhost] => (item={'pen': {'color': u'green'}}) => {
    "msg": {
        "pen": {
            "color": "green"
        }
    }
}
ok: [localhost] => (item={'pen': {'color': u'red'}}) => {
    "msg": {
        "pen": {
            "color": "red"
        }
    }
}


问:
What is the Apple Maps navigation notification type?
I am building an app that interacts with dangerous equipment. Because of this, I need to be able to alert them of various events when they are operating the app in the background. I am looking at the type of notification that Apple Maps uses to alert users that their turn is coming up. This is exactly what I want, but I can't find what type of notification it is or how to implement it.

I have tried push notifications, alerts, etc... None of them are what I am looking for.

答:
The notification type Apple Maps uses for turn-by-turn navigation is not accessible to public APIs. Other third-party navigation apps (such as Google Maps) use standard push notifications for that reason.

To mimic the look of the Apple Maps notification, use a local notification with an attached UNNotificationContentExtension.


问:
Add textbox when button is pressed
I know this can be accomplished in Javascript (I hope!) I have a couple of forms on my page, but I cannot guess how many the user will need, so is there some magic which can be done in javascript which when a button is pressed this:

```<code> <input name="userfile[]" type="file" /><br />
    <input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
</code>```

Is added to a designated area? Keeping in mind adding a number onto the name if the  button is pressed eg name="imagedescription3" next name="imagedescription4" and so forth
This may be posted around the internet, I know it would be, I just don't know how to thorougly phrase my question

答:
another jQuery solution:

Live Demo

```<code>$("#f_add").click(function(e) {
    var field = document.createElement('input');
    $(field).attr('type', 'text');
    $(field).attr('name', 'field[]');
    $("#thenewhotness").append(field);
    e.preventDefault();
});

<form id="thenewhotness">
    <button id="f_add">Add Extra Field</button>
    <input type="text" name="field[]">
</form>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Add textbox when button is pressed

Body:
I know this can be accomplished in Javascript (I hope!) I have a couple of forms on my page, but I cannot guess how many the user will need, so is there some magic which can be done in javascript which when a button is pressed this:

 <input name="userfile[]" type="file" />

    <input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" />

Is added to a designated area? Keeping in mind adding a number onto the name if the  button is pressed eg name="imagedescription3" next name="imagedescription4" and so forth
This may be posted around the internet, I know it would be, I just don't know how to thorougly phrase my question

Body:
another jQuery solution:

Live Demo

$("#f_add").click(function(e) {
    var field = document.createElement('input');
    $(field).attr('type', 'text');
    $(field).attr('name', 'field[]');
    $("#thenewhotness").append(field);
    e.preventDefault();
});

<form id="thenewhotness">
    <button id="f_add">Add Extra Field</button>
    <input type="text" name="field[]">
</form>


问:
Private enum access fails to compile from a nested class's friend function
I am currently porting a project that has so far only been built using Clang, to also work with GCC. The project contains code similar to below and compiles fine with Clang, however GCC gives an error message.

```<code>class Outer
{
  enum
  {
      ONE, TWO, THREE, COUNT
  };
public:
  class Inner
  {
    friend class Outer;
    friend void somefunc()
    {
      int x = Outer::COUNT;
    }
  };
};
</code>```

The error is:

```<code><source>: In function 'void somefunc()':

<source>:15:32: error: 'Outer::<unnamed enum> Outer::COUNT' is private within this context

   15 |                 int x = Outer::COUNT;

      |                                ^~~~~

<source>:6:26: note: declared private here

    6 |         ONE, TWO, THREE, COUNT

      |                          ^~~~~
</code>```

Note the friend keyword in the somefunc signature. Removing this makes the code compile fine with GCC, I'm wondering which compiler is correct? I am under the impression that friend functions have the same access as member functions which would make this a GCC bug.

Godbolt link: https://godbolt.org/z/OAR0gc

答:
```<code>friend class Outer;
</code>```

1. Is not needed, nested class has access to private members of embracing class.

```<code>friend void somefunc()
</code>```

2. According to https://en.cppreference.com/w/cpp/language/friend point 2, function that member of "Inner" and friend can't get privilege from point 1. Remove friend keyword.

Body:
I am currently porting a project that has so far only been built using Clang, to also work with GCC. The project contains code similar to below and compiles fine with Clang, however GCC gives an error message.

class Outer
{
  enum
  {
      ONE, TWO, THREE, COUNT
  };
public:
  class Inner
  {
    friend class Outer;
    friend void somefunc()
    {
      int x = Outer::COUNT;
    }
  };
};

The error is:

<source>: In function 'void somefunc()':

<source>:15:32: error: 'Outer::<unnamed enum> Outer::COUNT' is private within this context

   15 |                 int x = Outer::COUNT;

      |                                ^~~~~

<source>:6:26: note: declared private here

    6 |         ONE, TWO, THREE, COUNT

      |                          ^~~~~

Note the friend keyword in the somefunc signature. Removing this makes the code compile fine with GCC, I'm wondering which compiler is correct? I am under the impression that friend functions have the same access as member functions which would make this a GCC bug.

Godbolt link: https://godbolt.org/z/OAR0gc

Body:
friend class Outer;

1. Is not needed, nested class has access to private members of embracing class.

friend void somefunc()

2. According to https://en.cppreference.com/w/cpp/language/friend point 2, function that member of "Inner" and friend can't get privilege from point 1. Remove friend keyword.


问:
Is there a reason I continue to reach my daily query limit with this small test case?
I am attempting learn some geocoding so that I can ultimately convert a csv file of addresses into their respective latitudes and longitudes. I am following the documented example on google's geocoding API instructional and continue to get an error stating that I have maxed out my daily request quota. The example I am following can be found here (https://github.com/googlemaps/google-maps-services-python). I get this error when trying to convert ONE single address as a test case... I will say that I am completely new to this and this is the first time I have used an API. Thanks for any help!

I have tried creating a new API key and using that. I have followed multiple tutorials on youtube and continue to get the error stating I have exceeded my daily limit

```<code>import googlemaps
from datetime import datetime
</code>```

Define our api key

```<code>API_KEY = 'Insert an API key here - for security purposes I left mine out'
</code>```

Define our client

```<code>gmaps = googlemaps.Client(key = API_KEY)
</code>```

Geocoding an address

```<code>geocode_result = gmaps.geocode('1 Wilson Road, Annapolis, MD 21412')
</code>```

I want to be able to print out the latitude and longitude given the address I input.

答:
According to Google docs, geocoding is not free and billing has to be correctly set-up. See:

https://developers.google.com/maps/documentation/geocoding/intro

```
OVER_DAILY_LIMIT indicates any of the following:
    The API key is missing or invalid.
    Billing has not been enabled on your account.
    A self-imposed usage cap has been exceeded.
    The provided method of payment is no longer valid (for example, a credit card has expired).
```

And also

https://developers.google.com/maps/faq#over-limit-key-error

https://developers.google.com/maps/documentation/geocoding/usage-and-billing

Reminder: To use the Geocoding API, you must include an API key with all API requests and you must enable billing on each of your projects.

Priced from "0.005 USD per each"

I read that all google maps terms changed quite recently, messing many people...

Body:
I am attempting learn some geocoding so that I can ultimately convert a csv file of addresses into their respective latitudes and longitudes. I am following the documented example on google's geocoding API instructional and continue to get an error stating that I have maxed out my daily request quota. The example I am following can be found here (https://github.com/googlemaps/google-maps-services-python). I get this error when trying to convert ONE single address as a test case... I will say that I am completely new to this and this is the first time I have used an API. Thanks for any help!

I have tried creating a new API key and using that. I have followed multiple tutorials on youtube and continue to get the error stating I have exceeded my daily limit

import googlemaps
from datetime import datetime

Define our api key

API_KEY = 'Insert an API key here - for security purposes I left mine out'

Define our client

gmaps = googlemaps.Client(key = API_KEY)

Geocoding an address

geocode_result = gmaps.geocode('1 Wilson Road, Annapolis, MD 21412')

I want to be able to print out the latitude and longitude given the address I input.

Body:
According to Google docs, geocoding is not free and billing has to be correctly set-up. See:

https://developers.google.com/maps/documentation/geocoding/intro

OVER_DAILY_LIMIT indicates any of the following:
    The API key is missing or invalid.
    Billing has not been enabled on your account.
    A self-imposed usage cap has been exceeded.
    The provided method of payment is no longer valid (for example, a credit card has expired).

And also

https://developers.google.com/maps/faq#over-limit-key-error

https://developers.google.com/maps/documentation/geocoding/usage-and-billing

Reminder: To use the Geocoding API, you must include an API key with all API requests and you must enable billing on each of your projects.

Priced from "0.005 USD per each"

I read that all google maps terms changed quite recently, messing many people...


问:
Using reduce to delete even numbers in an object
I'm given an array of numbers. I have created an object named counts, whose keys are the numbers and values the amount of times those numbers appear in the array. Can't work out how to use reduce to delete the even counts of the numbers.

```<code>A =  [ 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5 ]

n =  5

function findOdd(A) {

  let counts = {};

  for (let i = 0; i < A.length; i++) {
    let num = A[i];
    counts[num] = counts[num] ? counts[num] + 1 : 1;
  }

//counts -> { '1': 2, '2': 2, '3': 2, '4': 2, '5': 3, '20': 2, '-1': 2, '-2': 2 }

  const answer = Object.keys(counts).reduce((object, key) => {
    if (key % 2 !== 0) {
      object[key] = counts[key];
    }
    return object;
  }, {})

  return answer;
</code>```

Must return the key of the odd count.

SOLUTION:

```<code>function findOdd(A) {
  const counts = {};
  for (let i = 0; i < A.length; i++) {
    let num = A[i];
    counts[num] = counts[num] ? counts[num] + 1 : 1;
  }
  Object.keys(counts).forEach(key => {
    if(counts[key] % 2 === 0) {
    delete counts[key];
    }
  });
  return Number(Object.keys(counts));
}
</code>```

答:
You can make use of Object.entries to obtain entires, then filter entries whose values are odd, and then reconstruct new Object from those entries using Object.fromEntries:

const countObject = { '1': 2, '2': 2, '3': 2, '4': 2, '5': 3, '20': 2, '-1': 2, '-2': 2 };
const oddEntries = Object.entries(countObject).filter(([key, value]) => value % 2 !== 0);
const oddCountObject = Object.fromEntries(oddEntries)

console.log(oddCountObject)```

Body:
I'm given an array of numbers. I have created an object named counts, whose keys are the numbers and values the amount of times those numbers appear in the array. Can't work out how to use reduce to delete the even counts of the numbers.

A =  [ 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5 ]

n =  5

function findOdd(A) {

  let counts = {};

  for (let i = 0; i  { '1': 2, '2': 2, '3': 2, '4': 2, '5': 3, '20': 2, '-1': 2, '-2': 2 }

  const answer = Object.keys(counts).reduce((object, key) => {
    if (key % 2 !== 0) {
      object[key] = counts[key];
    }
    return object;
  }, {})

  return answer;

Must return the key of the odd count.

SOLUTION:

function findOdd(A) {
  const counts = {};
  for (let i = 0; i  {
    if(counts[key] % 2 === 0) {
    delete counts[key];
    }
  });
  return Number(Object.keys(counts));
}


问:
HTTP Error 413 - Request Entity Too Large - on TranslateArray request
When I called Microsoft Translator Text API's TranslateArray, Error 413 (Request Entity is too Large)  occurred.

I recognize API limitations:

The total of all texts to be translated must not exceed 10000 characters.

The maximum number of array elements is 2000.

When the request's Content-Length header is greater than 30721, the request fails with a 413 error even though the above api limitations are observed.

is there any other limitation?

答:
If anyone is still running into this issue, upgrading to the latest google-cloud-translate client should fix the issue. For more information, the PR here fixed the problem for me, which was that the client was using GET requests instead of POST requests.

Note: This should also fix a related error of getting 411 (Length Required) when cutting off a piece of text to only translate the first N characters.


问:
Unable to run nodejs script for a json rpc test case automation
I am trying to run a nodejs script written for a json rpc test case automation. However, I keep getting the error:

```<code>npm run test\resources\nv-jsonrpc-tests\pingServer.spec.js
error missing script: test\resources\nv-jsonrpc-tests\pingServer.spec.js
verbose exit [ 1, true ]/>

var rpc = require('node-json-rpc');

var options = {
// int port of rpc server
port: 8080,
// string domain name or ip of rpc server, default '127.0.0.1'
host: '127.0.0.1',
// string with default path, default '/'
path: 'https://',
// boolean false to turn rpc checks off, default true
strict: true
};

// Create a server object with options
var client = new rpc.Client(options);

client.call(
{"jsonrpc": "2.0", "method": "Ping", "params": {classname: 'NServer'},
"id": 1},
function (err, res) {
// Check whether it worked and capture the response and error
if (err) { console.log(err); }
else { console.log(res); }
}
);
</code>```

Expectation:

Client send request with 'Ping' and receives 'Pong' from the server response.

答:
You seems to confuse npm run and node

npm run is meant to execute scripts declared in your package.json

node can directly execute the script in the file you give

Running this should work

```<code>node test\resources\nv-jsonrpc-tests\pingServer.spec.js
</code>```

Body:
I am trying to run a nodejs script written for a json rpc test case automation. However, I keep getting the error:

npm run test\resources\nv-jsonrpc-tests\pingServer.spec.js
error missing script: test\resources\nv-jsonrpc-tests\pingServer.spec.js
verbose exit [ 1, true ]/>

var rpc = require('node-json-rpc');

var options = {
// int port of rpc server
port: 8080,
// string domain name or ip of rpc server, default '127.0.0.1'
host: '127.0.0.1',
// string with default path, default '/'
path: 'https://',
// boolean false to turn rpc checks off, default true
strict: true
};

// Create a server object with options
var client = new rpc.Client(options);

client.call(
{"jsonrpc": "2.0", "method": "Ping", "params": {classname: 'NServer'},
"id": 1},
function (err, res) {
// Check whether it worked and capture the response and error
if (err) { console.log(err); }
else { console.log(res); }
}
);

Expectation:

Client send request with 'Ping' and receives 'Pong' from the server response.

Body:
You seems to confuse npm run and node

npm run is meant to execute scripts declared in your package.json

node can directly execute the script in the file you give

Running this should work

node test\resources\nv-jsonrpc-tests\pingServer.spec.js


问:
No Xcode support for iOS 12.3
My phone has updated to iOS 12.3 beta, the latest Xcode 10.2 beta only supports up to iOS 12.2.

Is there a beta version of xcode anywhere that is compatible with iOS 12.3?

I guess the options are to wait for apple to release a new version of xcode or to roll back. unless anyone knows otherwise?

答:
Any update on The IOS 12.3 Beta Developer Disk Image?
The official Debugging File for iOS 12.3 is not available.
You can try the following method to let Xcode support debugging iOS 12.3 devices.

1. Go to the folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

2. Create a folder named "12.3".

3. Copy the "12.2" file to the "12.3" folder.

Title: No Xcode support for iOS 12.3


问:
z-index between two absolutely positioned columns?
I have a two-column layout with two 'absolute' positioned divs.

```<code>    #left {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
    }

    #right {
        position: absolute;
        top: 0;
        left: 0
        z-index: 0;
    }
</code>```

In each column I have images and would like them to be able to overlap one another in differing configurations with z-index. Using wordpress, #left is populated with posts from one category then subsequently, #right is populated.

Is it possible for an image from #left to be positioned above an image in #right but not all? In essence - can the z-indexes between two separate divs be relative to one another?

I have assigned z-index for images in #left higher than that of #right, but images in #right are always on top. I assume it is something to do with the fact that #left appears first in the code?

答:
No.

Once you put position:absolute on those containers, each establishes its own "stacking context" and elements within will only be z-positioned relative to each other. There's a good explanation of stacking contexts at TimKadlec.com -- Detailed Look at Stacking in CSS

Body:
I have a two-column layout with two 'absolute' positioned divs.

    #left {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
    }

    #right {
        position: absolute;
        top: 0;
        left: 0
        z-index: 0;
    }

In each column I have images and would like them to be able to overlap one another in differing configurations with z-index. Using wordpress, #left is populated with posts from one category then subsequently, #right is populated.

Is it possible for an image from #left to be positioned above an image in #right but not all? In essence - can the z-indexes between two separate divs be relative to one another?

I have assigned z-index for images in #left higher than that of #right, but images in #right are always on top. I assume it is something to do with the fact that #left appears first in the code?


问:
How do I fix this script that I've written?
I'm getting error codes every time I change just a piece of my code. I'm trying to run a statement that will count the number of CADS.
Error message ~ "Incorrect syntax near the keyword 'from'"
Also, trying to add a Group by dbo.uneTablePTX.PropertyName
When I remove the count function my query will run flawlessly

```<code>select dbo.ptx_CADS.cad_name, dbo.uneTablePTX.PropertyName, (SELECT count(*)
from dbo.ptx_CADS.cad_id  AS "TotalAccounts"
from dbo.ptx_CADS
Inner Join dbo.uneTablePTX on dbo.ptx_CADS.cad_id=dbo.uneTablePTX.cad_id
Group bydbo.uneTablePTX.PropertyName
</code>```

I expect the columns name to change and for it to add them up. I don't understand the error message.

答: Gordon's answer is probably best, but I noticed you're missing a closing parenthesis in there as well, that could be part of the error message issue.</p>

Body:
I'm getting error codes every time I change just a piece of my code. I'm trying to run a statement that will count the number of CADS.
Error message ~ "Incorrect syntax near the keyword 'from'"
Also, trying to add a Group by dbo.uneTablePTX.PropertyName
When I remove the count function my query will run flawlessly

select dbo.ptx_CADS.cad_name, dbo.uneTablePTX.PropertyName, (SELECT count(*)
from dbo.ptx_CADS.cad_id  AS "TotalAccounts"
from dbo.ptx_CADS
Inner Join dbo.uneTablePTX on dbo.ptx_CADS.cad_id=dbo.uneTablePTX.cad_id
Group bydbo.uneTablePTX.PropertyName

I expect the columns name to change and for it to add them up. I don't understand the error message.


问:
How to manually configurate SSL Handshake in Spring boot
I am setting up a server that should communicate with other trusted servers, and I am using SSL Handshake in spring boot with apache tomcat.

I managed to succeed in making 2 way SSL however if I add Root CA that did generate the certificates in the trust store it automatically trusts every child from that CA. I want it to check if that specific certificate is in the trust store not just from the same parent.

Application properties are the same for the second server just with different KeyStore and Truststore.

Application.properties

```<code>server.ssl.key-store=classpath:booker.p12
server.ssl.key-store-password=pass
server.ssl.key-password=pass
server.ssl.key-alies=booker
server.ssl.trust-store=classpath:bookerTrust.p12
server.ssl.trust-store-password=pass
server.ssl.trust-store-type = PKCS12
server.ssl.client-auth=need
server.port=8111
</code>```

RestTemplate setup in main.java

```<code>    @Bean
    public RestTemplate restTemplate() throws Exception {
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
        restTemplate.setErrorHandler(
                new DefaultResponseErrorHandler() {
                    @Override
                    protected boolean hasError(HttpStatus statusCode) {
                        return false;
                    }
                });

        return restTemplate;
    }

    private ClientHttpRequestFactory clientHttpRequestFactory() throws Exception {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    private HttpClient httpClient() throws Exception {
        // Load our keystore and truststore containing certificates that we trust.
        SSLContext sslcontext =
                SSLContexts.custom().loadTrustMaterial(trustResource.getFile(), trustStorePassword.toCharArray())
                        .loadKeyMaterial(keyStore.getFile(), keyStorePassword.toCharArray(),
                                keyPassword.toCharArray()).build();
        SSLConnectionSocketFactory sslConnectionSocketFactory =
                new SSLConnectionSocketFactory(sslcontext, new HostCustomVerifer(trustResource,trustStorePassword,trustStoreType));
        return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
    }
}
</code>```

The communication in the controller:

```<code>@RestController
@RequestMapping(value = "/server1")
public class ClientController {

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping(value = "/data", method = RequestMethod.GET)
    ResponseEntity<?> getMessage(ServletRequest request) {
    return ResponseEntity.ok("Server1 successfully called!");
    }

    @RequestMapping(value = "/sdata", method = RequestMethod.GET)
    public ResponseEntity<String> getMsData() {
        try {
            String msEndpoint = https://localhost:8111/api/server2/data";
            return new ResponseEntity<String>( restTemplate.getForObject(new URI(msEndpoint), String.class), HttpStatus.OK) ;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ResponseEntity<String>("Exception occurred.. so, returning default data", HttpStatus.BAD_GATEWAY);
    }

}
</code>```

I expect for this scenario to fail however it succeeds:

Server1: Trusts RootCA,Server1,Server2

Server2: Trusts RootCA,Server2

Server1 starts communication with Server2 and succeeds somehow

I expect it to fail because Server2 does not trust Server1

答:
Not the best solution, however, it worked for my needs to fail communication if not trusted both ways.
I implemented javax.net.ssl.HostnameVerifier and made my CustomNameVerifier and did put that in SSLConnectionSocketFactory when making RestTemplate. Code that follows

Bean code should go in main (With @SpringBootApplication)

```<code>@Bean
public RestTemplate template() throws Exception{

    RestTemplate restTemplate = new RestTemplate();

    KeyStore keyStore;
    KeyStore trustStore;
    HttpComponentsClientHttpRequestFactory requestFactory = null;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        ClassPathResource classPathResource = new ClassPathResource(keyStoreLocation.getFilename());
        InputStream inputStream = classPathResource.getInputStream();
        keyStore.load(inputStream, keyStorePassword.toCharArray());

        trustStore = KeyStore.getInstance(trustStoreType);
        ClassPathResource classPathResourceTrust = new ClassPathResource(trustStoreLocation.getFilename());
        InputStream trustInput = classPathResourceTrust.getInputStream();
        trustStore.load(trustInput, trustStorePassword.toCharArray());

        javax.net.ssl.SSLContext sslContext = SSLContextBuilder.create()
                .loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
                .loadTrustMaterial(trustStore, null).setProtocol("TLS")
                .build();
        SSLConnectionSocketFactory sslConnectionSocketFactory =
                new SSLConnectionSocketFactory(sslContext,
                new HostCustomVerifer(trustStoreLocation,trustStorePassword,trustStoreType));

        HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory)
                .setMaxConnTotal(Integer.valueOf(200))
                .setMaxConnPerRoute(Integer.valueOf(200))
                .build();

        requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        requestFactory.setReadTimeout(Integer.valueOf(10000));
        requestFactory.setConnectTimeout(Integer.valueOf(10000));

        restTemplate.setRequestFactory(requestFactory);
    } catch (Exception exception) {
        System.out.println("Exception Occured while creating restTemplate "+exception);
        exception.printStackTrace();
    }
    return restTemplate;
}
</code>```

The CustomNameVerifier is as follows: (Even though you get a different error message ( it should be untrusted certificate you get for name validation failure.

```<code>public class HostCustomVerifer implements HostnameVerifier {

private String trustStorePassword;
private String trustResource;
private String trustType;

@Autowired
public HostCustomVerifer(@Value("${server.ssl.trust-store}") Resource trustResource,@Value("${server.ssl.trust-store-password}") String trustStorePassword,@Value("${server.ssl.trust-store-type}") String trustType) {
    this.trustStorePassword = trustStorePassword;
    this.trustResource = trustResource.getFilename();
    this.trustType = trustType;
}

@Override
public boolean verify(String hostName, SSLSession sslSession) {
    try {
        X509Certificate list[] =  (X509Certificate[]) sslSession.getPeerCertificates();
        int size = list.length;
        KeyStore trustStore = KeyStore.getInstance(trustType);
        ClassPathResource classPathResourceTrust = new ClassPathResource(trustResource);
        InputStream trustInput = classPathResourceTrust.getInputStream();
        trustStore.load(trustInput, trustStorePassword.toCharArray());
        for (X509Certificate x509Certificate : list) {
            ArrayList<String> content = Collections.list(trustStore.aliases());
            for (String alias : content) {
                X509Certificate cert = (X509Certificate) trustStore.getCertificate(alias);
                boolean isSelfSigned = cert.getIssuerDN().equals(cert.getSubjectDN());
                if(cert.equals(x509Certificate) && (!isSelfSigned || size==1))
                    return true;
            }
        }
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
        e.printStackTrace();
    }
    return false;
}
</code>```

}

If someone suddenly stumbles upon this thread and finds a better way you can inform me.

Body:
I am setting up a server that should communicate with other trusted servers, and I am using SSL Handshake in spring boot with apache tomcat.

I managed to succeed in making 2 way SSL however if I add Root CA that did generate the certificates in the trust store it automatically trusts every child from that CA. I want it to check if that specific certificate is in the trust store not just from the same parent.

Application properties are the same for the second server just with different KeyStore and Truststore.

Application.properties

server.ssl.key-store=classpath:booker.p12
server.ssl.key-store-password=pass
server.ssl.key-password=pass
server.ssl.key-alies=booker
server.ssl.trust-store=classpath:bookerTrust.p12
server.ssl.trust-store-password=pass
server.ssl.trust-store-type = PKCS12
server.ssl.client-auth=need
server.port=8111

RestTemplate setup in main.java

    @Bean
    public RestTemplate restTemplate() throws Exception {
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
        restTemplate.setErrorHandler(
                new DefaultResponseErrorHandler() {
                    @Override
                    protected boolean hasError(HttpStatus statusCode) {
                        return false;
                    }
                });

        return restTemplate;
    }

    private ClientHttpRequestFactory clientHttpRequestFactory() throws Exception {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    private HttpClient httpClient() throws Exception {
        // Load our keystore and truststore containing certificates that we trust.
        SSLContext sslcontext =
                SSLContexts.custom().loadTrustMaterial(trustResource.getFile(), trustStorePassword.toCharArray())
                        .loadKeyMaterial(keyStore.getFile(), keyStorePassword.toCharArray(),
                                keyPassword.toCharArray()).build();
        SSLConnectionSocketFactory sslConnectionSocketFactory =
                new SSLConnectionSocketFactory(sslcontext, new HostCustomVerifer(trustResource,trustStorePassword,trustStoreType));
        return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
    }
}

The communication in the controller:

@RestController
@RequestMapping(value = "/server1")
public class ClientController {

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping(value = "/data", method = RequestMethod.GET)
    ResponseEntity<?> getMessage(ServletRequest request) {
    return ResponseEntity.ok("Server1 successfully called!");
    }

    @RequestMapping(value = "/sdata", method = RequestMethod.GET)
    public ResponseEntity<String> getMsData() {
        try {
            String msEndpoint = https://localhost:8111/api/server2/data";
            return new ResponseEntity<String>( restTemplate.getForObject(new URI(msEndpoint), String.class), HttpStatus.OK) ;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ResponseEntity<String>("Exception occurred.. so, returning default data", HttpStatus.BAD_GATEWAY);
    }

}

I expect for this scenario to fail however it succeeds:

Server1: Trusts RootCA,Server1,Server2

Server2: Trusts RootCA,Server2

Server1 starts communication with Server2 and succeeds somehow

I expect it to fail because Server2 does not trust Server1

Body:
Not the best solution, however, it worked for my needs to fail communication if not trusted both ways.
I implemented javax.net.ssl.HostnameVerifier and made my CustomNameVerifier and did put that in SSLConnectionSocketFactory when making RestTemplate. Code that follows

Bean code should go in main (With @SpringBootApplication)

@Bean
public RestTemplate template() throws Exception{

    RestTemplate restTemplate = new RestTemplate();

    KeyStore keyStore;
    KeyStore trustStore;
    HttpComponentsClientHttpRequestFactory requestFactory = null;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        ClassPathResource classPathResource = new ClassPathResource(keyStoreLocation.getFilename());
        InputStream inputStream = classPathResource.getInputStream();
        keyStore.load(inputStream, keyStorePassword.toCharArray());

        trustStore = KeyStore.getInstance(trustStoreType);
        ClassPathResource classPathResourceTrust = new ClassPathResource(trustStoreLocation.getFilename());
        InputStream trustInput = classPathResourceTrust.getInputStream();
        trustStore.load(trustInput, trustStorePassword.toCharArray());

        javax.net.ssl.SSLContext sslContext = SSLContextBuilder.create()
                .loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
                .loadTrustMaterial(trustStore, null).setProtocol("TLS")
                .build();
        SSLConnectionSocketFactory sslConnectionSocketFactory =
                new SSLConnectionSocketFactory(sslContext,
                new HostCustomVerifer(trustStoreLocation,trustStorePassword,trustStoreType));

        HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory)
                .setMaxConnTotal(Integer.valueOf(200))
                .setMaxConnPerRoute(Integer.valueOf(200))
                .build();

        requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        requestFactory.setReadTimeout(Integer.valueOf(10000));
        requestFactory.setConnectTimeout(Integer.valueOf(10000));

        restTemplate.setRequestFactory(requestFactory);
    } catch (Exception exception) {
        System.out.println("Exception Occured while creating restTemplate "+exception);
        exception.printStackTrace();
    }
    return restTemplate;
}

The CustomNameVerifier is as follows: (Even though you get a different error message ( it should be untrusted certificate you get for name validation failure.

public class HostCustomVerifer implements HostnameVerifier {

private String trustStorePassword;
private String trustResource;
private String trustType;

@Autowired
public HostCustomVerifer(@Value("${server.ssl.trust-store}") Resource trustResource,@Value("${server.ssl.trust-store-password}") String trustStorePassword,@Value("${server.ssl.trust-store-type}") String trustType) {
    this.trustStorePassword = trustStorePassword;
    this.trustResource = trustResource.getFilename();
    this.trustType = trustType;
}

@Override
public boolean verify(String hostName, SSLSession sslSession) {
    try {
        X509Certificate list[] =  (X509Certificate[]) sslSession.getPeerCertificates();
        int size = list.length;
        KeyStore trustStore = KeyStore.getInstance(trustType);
        ClassPathResource classPathResourceTrust = new ClassPathResource(trustResource);
        InputStream trustInput = classPathResourceTrust.getInputStream();
        trustStore.load(trustInput, trustStorePassword.toCharArray());
        for (X509Certificate x509Certificate : list) {
            ArrayList<String> content = Collections.list(trustStore.aliases());
            for (String alias : content) {
                X509Certificate cert = (X509Certificate) trustStore.getCertificate(alias);
                boolean isSelfSigned = cert.getIssuerDN().equals(cert.getSubjectDN());
                if(cert.equals(x509Certificate) && (!isSelfSigned || size==1))
                    return true;
            }
        }
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
        e.printStackTrace();
    }
    return false;
}

}

If someone suddenly stumbles upon this thread and finds a better way you can inform me.


问:
How can I center the title in Appbar.Header in react-native-paper?
As you can see in the docs, the default positioning for the title in react-native-paper is left-aligned. I've seen multiple questions and answers about how to implement a centered title both for Android Native as well as React Native's StackNavigator, but I am having no luck pulling off the same effect with react-native-paper.

So far I have tried using the style parameter in Appbar.Header to pass in { textAlign: 'center' } or { flexDirection: 'row', justifyContent: 'space-between' }, but nothing seems to work. I'm not very impressed with react-native-paper's lack of documentation on overrides, but I still hope there's a way to do what I'm looking for.

```<code>const styles = { header: { textAlign: 'center' }}

<Appbar.Header style={styles.header}>
  <Appbar.Action icon="close" onPress={() => this.close()} />
  <Appbar.Content title={title} />
  <Button mode="text" onPress={() => this.submit()}>
    DONE
  </Button>
</Appbar.Header>
</code>```

Considering title accept a node, it can be used to display a react component.

How can I force center the title on all devices?

答:
You have to use titleStyle instead of style to center the text. The below code is working for me.

```<code><Appbar.Header>
  <Appbar.Content titleStyle={{textAlign: 'center'}} title="Centered Title" />
</Appbar.Header>
</code>```

There is also a similar subtitleStyle for styling the subtitle. Check the docs for more info.

Body:
As you can see in the docs, the default positioning for the title in react-native-paper is left-aligned. I've seen multiple questions and answers about how to implement a centered title both for Android Native as well as React Native's StackNavigator, but I am having no luck pulling off the same effect with react-native-paper.

So far I have tried using the style parameter in Appbar.Header to pass in { textAlign: 'center' } or { flexDirection: 'row', justifyContent: 'space-between' }, but nothing seems to work. I'm not very impressed with react-native-paper's lack of documentation on overrides, but I still hope there's a way to do what I'm looking for.

const styles = { header: { textAlign: 'center' }}

<Appbar.Header style={styles.header}>
  <Appbar.Action icon="close" onPress={() => this.close()} />
  <Appbar.Content title={title} />
  <Button mode="text" onPress={() => this.submit()}>
    DONE
  </Button>
</Appbar.Header>

Considering title accept a node, it can be used to display a react component.

How can I force center the title on all devices?

Body:
You have to use titleStyle instead of style to center the text. The below code is working for me.

<Appbar.Header>
  <Appbar.Content titleStyle={{textAlign: 'center'}} title="Centered Title" />
</Appbar.Header>

There is also a similar subtitleStyle for styling the subtitle. Check the docs for more info.


问:
Web page doesn't load when opened through a bot or requested through any other method in python code
I am trying to scrape https://www.hyatt.com and It not for illegal use I just want to make a simple script to find Hotel which matches my search.

But the problem is I am unable to even load the webpage using any bot. It simply does not load.

here are some ways I already tried.
1 - Used selenium
2 - used scrapy frame-work to get the data
3 - used python requests library

```<code>from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.hyatt.com")

driver.close()
</code>```

I just want that the page loads itself. I will take care of the rest.

答:
I took your code added a few tweaks and ran the same test at my end:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
# options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get("https://www.hyatt.com")
WebDriverWait(driver, 20).until(EC.title_contains("Hyatt"))
print(driver.title)
driver.quit()
</code>```

Eventually I ran into the same issue. Using Selenium I was also unable to even load the webpage. But when I inspected the Console Errors  within google-chrome-devtools it clearly showed that:

Failed to load resource: the server responded with a status of 404 () https://www.hyatt.com/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3/fingerprint

Snapshot:

404 Not Found

The HTTP 404 Not Found client error response code indicates that the server can't find the requested resource. Links which lead to a 404 page are often called broken or dead links, and can be subject to link rot.

A 404 status code does not indicate whether the resource is temporarily or permanently missing. But if a resource is permanently removed, ideally a 410 (Gone) should be used instead of a 404 status.

Moving ahead, while inspecting the HTML DOM of https://www.hyatt.com/ it was observed that some of the

Which is a clear indication that the website is protected by Bot Management service provider Akamai Bot Manager and the navigation by WebDriver driven Browser Client gets detected and subsequently gets blocked.

Outro

You can find some more relevant discussions in:

Unable to use Selenium to automate Chase site login

How does recaptcha 3 know I'm using selenium/chromedriver?

Selenium and non-headless browser keeps asking for Captcha

Body:
I am trying to scrape https://www.hyatt.com and It not for illegal use I just want to make a simple script to find Hotel which matches my search.

But the problem is I am unable to even load the webpage using any bot. It simply does not load.

here are some ways I already tried.
1 - Used selenium
2 - used scrapy frame-work to get the data
3 - used python requests library

from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.hyatt.com")

driver.close()

I just want that the page loads itself. I will take care of the rest.

Body:
I took your code added a few tweaks and ran the same test at my end:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
# options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get("https://www.hyatt.com")
WebDriverWait(driver, 20).until(EC.title_contains("Hyatt"))
print(driver.title)
driver.quit()

Eventually I ran into the same issue. Using Selenium I was also unable to even load the webpage. But when I inspected the Console Errors  within google-chrome-devtools it clearly showed that:

Failed to load resource: the server responded with a status of 404 () https://www.hyatt.com/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3/fingerprint

Snapshot:

404 Not Found

The HTTP 404 Not Found client error response code indicates that the server can't find the requested resource. Links which lead to a 404 page are often called broken or dead links, and can be subject to link rot.

A 404 status code does not indicate whether the resource is temporarily or permanently missing. But if a resource is permanently removed, ideally a 410 (Gone) should be used instead of a 404 status.

Moving ahead, while inspecting the HTML DOM of https://www.hyatt.com/ it was observed that some of the <script> and <noscript> tags refers to akam:

<script type="text/javascript" src="https://www.hyatt.com/akam/10/28f56097" defer=""></script>

<noscript><img src="https://www.hyatt.com/akam/10/pixel_28f56097?a=dD02NDllZTZmNzg1NmNmYmIyYjVmOGFiOGYwMWI5YWMwZmM4MzcyZGY5JmpzPW9mZg==" style="visibility: hidden; position: absolute; left: -999px; top: -999px;" /></noscript>

Which is a clear indication that the website is protected by Bot Management service provider Akamai Bot Manager and the navigation by WebDriver driven Browser Client gets detected and subsequently gets blocked.

Outro

You can find some more relevant discussions in:

Unable to use Selenium to automate Chase site login

How does recaptcha 3 know I'm using selenium/chromedriver?

Selenium and non-headless browser keeps asking for Captcha


问:
How to automate helm package --sign non-interactively in bash
I am writing a bash script on a machine without expect.
The script automates the build of a helm (v2.9.1) chart.

I've got to the part in the script where it runs a

helm package --sign --key 'mykey' --keyring 'path/to/keyring' -d chartdir chart

and because helm prompts for the passphrase of the gpg key I created in order to use provenance files (a requirement), I cannot script around the soliciting of the passphrase, which I would like to prompt for separately as the script is part of a CI/CD build chain.

I have tried using

yes $promptedPassPhrase | helm package --sign...

and I got

xrealloc: cannot allocate 18446744071562067968 bytes (237568 bytes allocated)

I also tried plain old

echo $promptedPassPhrase | helm package --sign...

and I got

Error: inappropriate ioctl for device

I also tried script and got the same response.  As I do not have expect on the server, I cannot expect my way round it, so I'm stumped as to how to automate the helm package command and am not going to use a key without a passphrase as it is bad practice.

答:
I don't know how long this has been the case, or exactly which versions this works on, but this doc page says:

If your PGP private key has a passphrase, [...] You can set the HELM_KEY_PASSPHRASE environment variable to that passphrase in case you don't want to be prompted to enter the passphrase.

This works for me on v2.13.1. It looks like it was added in October of 2018, so my guess is that it was first available in v2.12.0-rc.1.

Although this doesn't directly answer the OP's question (since they asked about v2.9.1), it will hopefully help anyone who ends up here because they (like me the first time round) missed that line in the doc.


问:
How do I read from/write to a binary file in 2D Array form?
I am trying to use a binary file to hold my data in it. But I don't understand how do I read/write in 2D Array form. I know how to read arrays/structs etc. from binary files, I just don't know how do I do that with a 2D array.

I have looked at similar questions to this, but I did not understand what most of the people were getting at. I just want to know how does one read/write data in 2D Array format. as in fwrite( x , y , z , w ); .

Here is what my array looks like:

```<code>int array[50][100];
</code>```

I don't know what to do from now on, if it were 1 dimensional I'd do;

```<code>FILE* fp;
fp = fopen("file.bin","wb+");
fwrite(array, sizeof(int), 50, fp);
</code>```

but since that array is multi dimensional I don't actually know what to put in that function.

Thank you in advance.

Please note that I am pretty new at coding and I may not be seeing a pretty easy solution.

答:
The method for saving a 2-dimensional array will be very similar to saving a 1-dimensional array, it is indeed as you wrote in the comment to the question:

```<code>fwrite(array, sizeof(int), 50*100, fp);
</code>```

This is because the 2 dimensional (in this case, int)array is stored identically to how a 1 dimensional array would be; an unbroken chain of ints. However, you could save it any way you want to as long as you stay consistent with saving/loading. fwrite takes a pointer as an argument, so as long as the data you pass to it is an array it will work.

Body:
I am trying to use a binary file to hold my data in it. But I don't understand how do I read/write in 2D Array form. I know how to read arrays/structs etc. from binary files, I just don't know how do I do that with a 2D array.

I have looked at similar questions to this, but I did not understand what most of the people were getting at. I just want to know how does one read/write data in 2D Array format. as in fwrite( x , y , z , w ); .

Here is what my array looks like:

int array[50][100];

I don't know what to do from now on, if it were 1 dimensional I'd do;

FILE* fp;
fp = fopen("file.bin","wb+");
fwrite(array, sizeof(int), 50, fp);

but since that array is multi dimensional I don't actually know what to put in that function.

Thank you in advance.

Please note that I am pretty new at coding and I may not be seeing a pretty easy solution.

Body:
The method for saving a 2-dimensional array will be very similar to saving a 1-dimensional array, it is indeed as you wrote in the comment to the question:

fwrite(array, sizeof(int), 50*100, fp);

This is because the 2 dimensional (in this case, int)array is stored identically to how a 1 dimensional array would be; an unbroken chain of ints. However, you could save it any way you want to as long as you stay consistent with saving/loading. fwrite takes a pointer as an argument, so as long as the data you pass to it is an array it will work.


问:
How do Rpy2, pyrserve and PypeR compare?
I would like to access R from within a Python program.  I am aware of Rpy2, pyrserve and PypeR.

What are the advantages or disadvantages of these three options?

答:
From the paper in the Journal of Statistical Software on PypeR:

RPy presents a simple and efficient way of accessing R from Python. It is robust and very
  convenient for frequent interaction operations between Python and R. This package allows
  Python programs to pass Python objects of basic data types to R functions and return the
  results in Python objects. Such features make it an attractive solution for the cases in which Python and R interact frequently. However, there are still limitations of this package as listed below.

  Performance:

  RPy may not behave very well for large-size data sets or for computation-intensive
  duties. A lot of time and memory are inevitably consumed in producing the Python
  copy of the R data because in every round of a conversation RPy converts the returned
  value of an R expression into a Python object of basic types or NumPy array. RPy2, a
  recently developed branch of RPy, uses Python objects to refer to R objects instead of
  copying them back into Python objects. This strategy avoids frequent data conversions
  and improves speed. However, memory consumption remains a problem. [...]
  When we were implementing WebArray (Xia et al. 2005), an online platform for microarray data analysis, a job consumed roughly one quarter more computational time if running R through RPy instead of through R's command-line user interface. Therefore, we decided to run R in Python through pipes in subsequent developments, e.g., WebArrayDB (Xia et al. 2009), which retained the same performance as achieved when running R independently. We do not know the exact reason for such a difference in performance, but we noticed that RPy directly uses the shared library of R to run R scripts. In contrast, running R through pipes means running the R interpreter directly.

  Memory:

  R has been denounced for its uneconomical use of memory. The memory used by large-
  size R objects is rarely released after these objects are deleted. Sometimes the only
  way to release memory from R is to quit R. RPy module wraps R in a Python object.
  However, the R library will stay in memory even if the Python object is deleted. In other
  words, memory used by R cannot be released until the host Python script is terminated.

  Portability:

  As a module with extensions written in C, the RPy source package has to be compiled
  with a specific R version on POSIX (Portable Operating System Interface for Unix)
  systems, and the R must be compiled with the shared library enabled. Also, the binary
  distributions for Windows are bound to specic combinations of different versions of
  Python/R, so it is quite frequent that a user has difficulty in finding a distribution that
  ts the user's software environment.


问:
Google Apps script move My drive Files to Team drive folder based on file name
I am new to Google Apps Script. I'm trying to get for our workplace a script to move files from a single folder on a Google My Drive, over to a Team Drive if part of the filename has a certain phrase. However the script is still moving any and all files from the My Drive source folder to the Team Drive target folder, even those that don't have the "required" phrase in the file name.
Example file names used:

ALT ADJ 01_03_2018

ALT CHG 01_03_2018

ALT CHG 01_04_2018

ALT PMT 01_03_2018

APX ADJ 01_03_2018

Enabled Drive API v2 in Advanced Google Services under Resources

```<code>function moveFileToFolder() {
  var upldFldr=DriveApp.getFolderById('<<original Folder ID>>');
  var files=upldFldr.getFiles();
  supportsTeamDrives: true;
  while(files.hasNext()) {
    var file=files.next();
    var key=file.getName().slice(0,7);  //intended to take the first 7 characters of the filename.
      if (key = "ALT CHG") {
        supportsTeamDrives: true;
        supportTeamDrives: true;
        var targetFolder = DriveApp.getFolderById('<<new folder ID>>');
        targetFolder.addFile(file);
      };
  }
}
</code>```

In the code, I'm trying to get only files that have the first 7 letters of ALT CHG in the file name to be moved/copied to the Team Drive folder. Instead, all of the files end up in the Team Drive Folder.  Note this is the entire code start to finish.

答:
Change:

```<code>if (key = "ALT CHG") {
</code>```

to

```<code>if (key == "ALT CHG") {
</code>```

This should fix the issue, i.e. use == instead of =

Body:
I am new to Google Apps Script. I'm trying to get for our workplace a script to move files from a single folder on a Google My Drive, over to a Team Drive if part of the filename has a certain phrase. However the script is still moving any and all files from the My Drive source folder to the Team Drive target folder, even those that don't have the "required" phrase in the file name.
Example file names used:

ALT ADJ 01_03_2018

ALT CHG 01_03_2018

ALT CHG 01_04_2018

ALT PMT 01_03_2018

APX ADJ 01_03_2018

Enabled Drive API v2 in Advanced Google Services under Resources

function moveFileToFolder() {
  var upldFldr=DriveApp.getFolderById('<<original Folder ID>>');
  var files=upldFldr.getFiles();
  supportsTeamDrives: true;
  while(files.hasNext()) {
    var file=files.next();
    var key=file.getName().slice(0,7);  //intended to take the first 7 characters of the filename.
      if (key = "ALT CHG") {
        supportsTeamDrives: true;
        supportTeamDrives: true;
        var targetFolder = DriveApp.getFolderById('<<new folder ID>>');
        targetFolder.addFile(file);
      };
  }
}

In the code, I'm trying to get only files that have the first 7 letters of ALT CHG in the file name to be moved/copied to the Team Drive folder. Instead, all of the files end up in the Team Drive Folder.  Note this is the entire code start to finish.

Body:
Change:

if (key = "ALT CHG") {

to

if (key == "ALT CHG") {

This should fix the issue, i.e. use == instead of =


问:
How is the method Total being called in this example
I see in the code below how the list item's class and state is being modified but I don't understand where or how the total() method is being triggered. The total is added to the markup in the {{total() | currency}} but there is no click event or anything reactive that I see in the code that is bound to it.

```<code><template>

    <!-- v-cloak hides any un-compiled data bindings until the Vue instance is ready. -->
    <form id="main" v-cloak>

        <h1>Services</h1>

        <ul>
            <!-- Loop through the services array, assign a click handler, and set or
                remove the "active" css class if needed -->
            <li
                v-for="service in services"
                v-bind:key="service.id"
                v-on:click="toggleActive(service)"
                v-bind:class="{ 'active': service.active}">
                <!-- Display the name and price for every entry in the array .
                    Vue.js has a built in currency filter for formatting the price -->
                {{service.name}} <span>{{service.price | currency}}</span>
            </li>
        </ul>

        <div class="total">
            <!-- Calculate the total price of all chosen services. Format it as currency. -->
            Total: <span>{{total() | currency}}</span>
        </div>

    </form>
</template>

<script>
export default {
    name: 'OrderForm',
    data(){
        return{
        // Define the model properties. The view will loop
        // through the services array and genreate a li
        // element for every one of its items.
        services: [
            {
                name: 'Web Development',
                price: 300,
                active:true
            },{
                name: 'Design',
                price: 400,
                active:false
            },{
                name: 'Integration',
                price: 250,
                active:false
            },{
                name: 'Training',
                price: 220,
                active:false
            }
        ]
        }
    },
    // Functions we will be using.
    methods: {
        toggleActive: function(s){
            s.active = !s.active;
        },
        total: function(){

            var total = 0;

            this.services.forEach(function(s){
                if (s.active){
                    total+= s.price;
                }
            });

           return total;
        }
    },
    filters: {
        currency: function(value) {
            return '$' + value.toFixed(2);
        }
    }
}
</script>
</code>```

EDIT:

Working example
https://tutorialzine.com/2016/03/5-practical-examples-for-learning-vue-js

答:
When you update the data, the template in the components rerendered. That means that the template will trigger all methods bind to the templates. You can see it by adding dynamic date for example.</p>

```<code><div id="app">
  <button @click="increment">Increment by 1</button>
  <p>{{total()}}</p>
  <p>
  // Date will be updated after clicking on increment:
  {{date()}}
  </p>
</div>

new Vue({
  el: "#app",
  data: {
        counter: 0,
  },
  methods: {
        increment: function(){
            this.counter += 1;
    },
    total: function(){
      return this.counter;
    },
    date: function() {
      return new Date();
    }
  }
})
</code>```

Body:
I see in the code below how the list item's class and state is being modified but I don't understand where or how the total() method is being triggered. The total is added to the markup in the {{total() | currency}} but there is no click event or anything reactive that I see in the code that is bound to it.

<template>

    <form id="main" v-cloak>

Services

                {{service.name}} {{service.price | currency}}

            Total: {{total() | currency}}

    </form>
</template>

EDIT:

Working example
https://tutorialzine.com/2016/03/5-practical-examples-for-learning-vue-js

Body:
When you update the data, the template in the components rerendered. That means that the template will trigger all methods bind to the templates. You can see it by adding dynamic date for example.

<div id="app">
  <button @click="increment">Increment by 1</button>
  <p>{{total()}}</p>
  <p>
  // Date will be updated after clicking on increment:
  {{date()}}
  </p>
</div>

new Vue({
  el: "#app",
  data: {
        counter: 0,
  },
  methods: {
        increment: function(){
            this.counter += 1;
    },
    total: function(){
      return this.counter;
    },
    date: function() {
      return new Date();
    }
  }
})


问:
Pass hashed password from $request->validated in Laravel?
Is there a way I can create the user with the hashed password, not plain password?</p>

```<code>public function post(StoreUserRequest $request) {
    User::create($request->validated());
    return redirect()->route('frontend.login')->with('message', 'Your account has been created!');
}
</code>```

答:
See the hashing docs here https://laravel.com/docs/5.8/hashing

You may hash a password by calling the make method on the Hash facade

```<code>public function post(StoreUserRequest $request)
{
    $userData = $request->validated();
    $userData['password'] = Hash::make($request->input['password']);
    User::create($userData);
    return redirect()->route('frontend.login')->with('message', 'Your account has been created!');
}
</code>```

Body:
Is there a way I can create the user with the hashed password, not plain password?

public function post(StoreUserRequest $request) {
    User::create($request->validated());
    return redirect()->route('frontend.login')->with('message', 'Your account has been created!');
}

Body:
See the hashing docs here https://laravel.com/docs/5.8/hashing

You may hash a password by calling the make method on the Hash facade

public function post(StoreUserRequest $request)
{
    $userData = $request->validated();
    $userData['password'] = Hash::make($request->input['password']);
    User::create($userData);
    return redirect()->route('frontend.login')->with('message', 'Your account has been created!');
}


问:
React js. How to make a component with this structure: <Component> description of the component </Component>
I have the following code. And I am having trouble understanding how the ProjectCardDescription component should be implemented in order to be able to pass its description within the ProjectCard component

I've tried this, but got an empty component:

```<code>import React, { Component } from 'react';

class ProjectCardDescription extends Component {
    render () {
        return (
            <span>
                {this.props.description}
            </span>
        );
    }
}

export default ProjectCardDescription;
</code>```

This is how my ProjectCard component looks like:

```<code>import React, { Component } from 'react';
import ProjectCardIcon from './ProjectCardIcon/ProjectCardIcon';
import './ProjectCard.css';
import ProjectCardDescription from './ProjectCardDescription/ProjectCardDescription';

class ProjectCard extends Component {
    render() {
        return(
            <div className="project-card project-card-medium">
                <a href="https://www.linkedin.com/in/florovarelaa/" target="_blank" rel="noopener noreferrer">
                    <ProjectCardIcon icon='react'/>
                    <ProjectCardDescription>
                        Una descripcion de un projecto hecho en react. Que contiene dos oraciones.
                    </ProjectCardDescription>
                </a>
            </div>
        );
    };
}
export default ProjectCard;
</code>```

I would like to get the ProjectCardDescription Component with its propper
inside html. Should I pass it as props?

答:
If you want to use the structure you have:

```<code><ProjectCardDescription>
  Una descripcion de un projecto hecho en react. Que contiene dos oraciones.
</ProjectCardDescription>
</code>```

your ProjectCardDescription component should look like:

```<code>class ProjectCardDescription extends Component {
    render () {
        return (
            <span>
                {this.props.children}
            </span>
        );
    }
}
</code>```

this.props.children is anything in between the opening and closing tags of your rendered component.

Documentation here

Body:
I have the following code. And I am having trouble understanding how the ProjectCardDescription component should be implemented in order to be able to pass its description within the ProjectCard component

I've tried this, but got an empty component:

import React, { Component } from 'react';

class ProjectCardDescription extends Component {
    render () {
        return (

                {this.props.description}

        );
    }
}

export default ProjectCardDescription;

This is how my ProjectCard component looks like:

import React, { Component } from 'react';
import ProjectCardIcon from './ProjectCardIcon/ProjectCardIcon';
import './ProjectCard.css';
import ProjectCardDescription from './ProjectCardDescription/ProjectCardDescription';

class ProjectCard extends Component {
    render() {
        return(

                    <ProjectCardIcon icon='react'/>
                    <ProjectCardDescription>
                        Una descripcion de un projecto hecho en react. Que contiene dos oraciones.
                    </ProjectCardDescription>

        );
    };
}
export default ProjectCard;

I would like to get the ProjectCardDescription Component with its propper
inside html. Should I pass it as props?

Body:
If you want to use the structure you have:

<ProjectCardDescription>
  Una descripcion de un projecto hecho en react. Que contiene dos oraciones.
</ProjectCardDescription>

your ProjectCardDescription component should look like:

class ProjectCardDescription extends Component {
    render () {
        return (
            <span>
                {this.props.children}
            </span>
        );
    }
}

this.props.children is anything in between the opening and closing tags of your rendered component.

Documentation here


问:
Sorting an object with object.entries
I have an object of data which I'd like to sort. I'm running the following object through Object.entries(data).map() to display it on my Front-End, but I'd like to maintain a specific order. Right now it seems that the order is somewhat random. I'm using .map to display a number of React components so sorting after the map doesn't seem to be possible.

```<code>const data = {
  rent: {
   value: '100'
    },
  },
  legal: {
    value: '300'
  },
  misc: {
    value: '300'
    },
 horse: {
   value: '400'
   }
  },
};
</code>```

Ideally rent should be the first item when it's mapped out, and misc should be the last one. I've tried using .sort() but I don't seem to be having any luck.

What is the right way to achieve this? I assume some combination of Object.entries(data).sort().map() but I can't seem to figure it out.

答:
You have to provide a compare function to your sort function, if wishing to use Object.entries:

const data = {
  rent: {
   value: '100'
  },
  legal: {
    value: '300'
  },
  misc: {
    value: '201'
 },
 horse: {
   value: '400'
 }
};

function compare(a, b){
  if( a[1].value  b[1].value ){
    return 1;
  }
  return 0;
}
console.log(Object.entries(data).sort(compare))```
</div>
</div>
</p>

<p>The code above becomes much cleaner if the original data structure is an array of objects:</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>const data = [
  { key: 'rent', value: '100' },
  { key: 'legal', value: '300' },
  { key: 'misc', value: '201' },
  { key: 'horse', value: '400' }
];

let sorted = data.sort(({key:k1, value:v1}, {key:k2, value:v2}) => {
  if( v1 < v2 ){
    return -1;
  } else if( v1 > v2 ){
    return 1;
  }
  return 0;
})
console.log('sorted arr', sorted)</code>```

Title: Sorting an object with object.entries

Body:
I have an object of data which I'd like to sort. I'm running the following object through Object.entries(data).map() to display it on my Front-End, but I'd like to maintain a specific order. Right now it seems that the order is somewhat random. I'm using .map to display a number of React components so sorting after the map doesn't seem to be possible.

const data = {
  rent: {
   value: '100'
    },
  },
  legal: {
    value: '300'
  },
  misc: {
    value: '300'
    },
 horse: {
   value: '400'
   }
  },
};

Ideally rent should be the first item when it's mapped out, and misc should be the last one. I've tried using .sort() but I don't seem to be having any luck.

What is the right way to achieve this? I assume some combination of Object.entries(data).sort().map() but I can't seem to figure it out.

Body:
You have to provide a compare function to your sort function, if wishing to use Object.entries:

const data = {
  rent: {
   value: '100'
  },
  legal: {
    value: '300'
  },
  misc: {
    value: '201'
 },
 horse: {
   value: '400'
 }
};

function compare(a, b){
  if( a[1].value < b[1].value ){
    return -1
  } else if( a[1].value > b[1].value ){
    return 1;
  }
  return 0;
}
console.log(Object.entries(data).sort(compare))

The code above becomes much cleaner if the original data structure is an array of objects:

const data = [
  { key: 'rent', value: '100' },
  { key: 'legal', value: '300' },
  { key: 'misc', value: '201' },
  { key: 'horse', value: '400' }
];

let sorted = data.sort(({key:k1, value:v1}, {key:k2, value:v2}) => {
  if( v1 < v2 ){
    return -1;
  } else if( v1 > v2 ){
    return 1;
  }
  return 0;
})
console.log('sorted arr', sorted)


问:
How does the CPU know how many bytes it should read for the next instruction, considering instructions have different lengths?
So i was reading a paper, and in it, they said that statically disassembling the code of a binary is undecidable, because a series of bytes could be represented as many possible ways as shown in picture ( its x86 )

so my question is :

how does the CPU execute this then? for example in the picture, when we reach after C3, how does it know how many bytes it should  read for the next instruction?

how does the CPU know how much it should increment the PC after executing one instruction? does it somehow store the size of the current instruction and add that when it wants to increment PC?

if the CPU can somehow know how many bytes it should read for the next instruction or basically how to interpret the next instruction, why cant we do it statically?

答:
Static disassembly is undecidable because the disassembler cannot discern whether a group of bytes is code or data. The example you provided is a good one: after the RETN instruction, ther might be another subroutine, or it might be some data, then a routine.  There is no way to decide which is the correct one until you actually execute the code.

When an opcode is read during the instruction fetch phase, the opcode itself encodes one kind of instruction and the sequencer already knows how much bytes to read from it. There is no ambiguity. In your example, after fetching C3 but before executing it, the CPU will adjust its EIP register (Intruction Pointer) to read what it considers it will be the next instruction (the one beginning with 0F), BUT during the execution of instruction C3 (which it's a RETN instruction), the EIP is changed as RETN is "Return from subroutine) so it won't reach instruction 0F 88 52. That instruction will only be reached if some other part of the code jumps to the location of that instruction. If no code performs such jump, then it will be considered as data, but the problem of determining whether a particular instruction will or will not executed is not a decidable problem.

Some clever disassemblers (I think IDA Pro does that) start from a location known to store code, and assume all following bytes to be instructions as well, UNTIL a jump or ret is found. If a jump is found and the destination of the jump is known by reading the binary code, then the scanning continues there. If the jump is conditional, then the scanning branches into two paths: jump not taken and jump taken.

After all brances have been scanned, everything that is left, is considered data (that means that interrupt handlers, exception handlers, and functions that are called from a function pointer calculated at runtime won't be detected)


问:
conda-forge: Why does Conda inconsistently want to downgrade NumPy?
I'm trying to prefer packages from CondaForge (for availability and compatibility). However, Conda seems to want to prefer versions of core libraries (e.g. NumPy) from other channels.

For example, when I try to install a new library, Conda offers to downgrade NumPy, but if I ask for the same library and NumPy, Conda no longer advises downgrade. Why?

```<code>$ conda install -c conda-forge beautifulsoup4
The following NEW packages will be INSTALLED:
    beautifulsoup4: 4.6.3-py36_0 conda-forge
The following packages will be UPDATED:
    numpy-base: 1.14.3-py36h0ea5e3f_1 --> 1.15.0-py36h3dfced4_0
The following packages will be DOWNGRADED:
    blas: 1.1-openblas conda-forge --> 1.0-mkl
    numpy: 1.15.1-py36_blas_openblashd3ea46f_1 conda-forge [blas_openblas] --> 1.15.0-py36h1b885b7_0
    scikit-learn: 0.19.2-py36_blas_openblasha84fab4_201 conda-forge [blas_openblas] --> 0.19.1-py36hedc7406_0
    scipy: 1.1.0-py36_blas_openblash7943236_201 conda-forge [blas_openblas] --> 1.1.0-py36hc49cb51_0
Proceed ([y]/n)? n

$ conda install -c conda-forge beautifulsoup4 numpy
The following NEW packages will be INSTALLED:
    beautifulsoup4: 4.6.3-py36_0 conda-forge
Proceed ([y]/n)? y
</code>```

Is there a preference that will give better behaviour?

答:
You can read the conda-forge documentation
http://conda-forge.org/docs/user/tipsandtricks.html#multiple-channels

To see your channels and priorities
$conda config --describe channel_priority

The solution is to add the conda-forge channel on top of defaults in your .condarc file when using conda-forge packages and activate the strict channel priority with:

$ conda config --set channel_priority strict

Here is how a .condarc file would look like:

$ cat .condarc
channel_priority: strict
channels:
  - conda-forge
  - defaults

In addition to the channel priority we recommend to always install your packages inside a new environment instead the root environment from anaconda/miniconda. Using envs make it easier to debug problems with packages and ensure the stability of your root env.

Body:
I'm trying to prefer packages from CondaForge (for availability and compatibility). However, Conda seems to want to prefer versions of core libraries (e.g. NumPy) from other channels.

For example, when I try to install a new library, Conda offers to downgrade NumPy, but if I ask for the same library and NumPy, Conda no longer advises downgrade. Why?

$ conda install -c conda-forge beautifulsoup4
The following NEW packages will be INSTALLED:
    beautifulsoup4: 4.6.3-py36_0 conda-forge
The following packages will be UPDATED:
    numpy-base: 1.14.3-py36h0ea5e3f_1 --> 1.15.0-py36h3dfced4_0
The following packages will be DOWNGRADED:
    blas: 1.1-openblas conda-forge --> 1.0-mkl
    numpy: 1.15.1-py36_blas_openblashd3ea46f_1 conda-forge [blas_openblas] --> 1.15.0-py36h1b885b7_0
    scikit-learn: 0.19.2-py36_blas_openblasha84fab4_201 conda-forge [blas_openblas] --> 0.19.1-py36hedc7406_0
    scipy: 1.1.0-py36_blas_openblash7943236_201 conda-forge [blas_openblas] --> 1.1.0-py36hc49cb51_0
Proceed ([y]/n)? n

$ conda install -c conda-forge beautifulsoup4 numpy
The following NEW packages will be INSTALLED:
    beautifulsoup4: 4.6.3-py36_0 conda-forge
Proceed ([y]/n)? y

Is there a preference that will give better behaviour?


问:
Python returns NoneType if an Except happens in recursive function
I am scraping from a site using Requests. Given a valid URL, I loop through API services and available tables inside those services. The target site is old and will throw 500 codes at random, so I must control for this.

At present, I feed a For loop a list of Services. The loop sends services to a function that generates a URL to query the site for the names of Tables, and builds a dictionary of table names and ID's.

To catch the 500 codes and immediately retry the query, I use a try/except block inside the function, and direct the function to a separate helper function that prints a helpful error message stating that it got a 500 code. The helper then calls the function again, passing the query back to it, and it tries again.

The function works as expected when no 500 code is received. The function returns a dictionary for me with my IDs and names.

However, if a 500 code is received for that query, the function retries the query as described above, and is successful. However, the function returns None in these cases.

def sit_and_wait(url):
    print("500 received. sleeping.")
    time.sleep(1)
    query_for_tables(url)

def query_for_tables(url):
    data = r.get(url)
    content = json.loads(data)
    please_return_this_dict = {}
    try:
        if content['tables']:
            for x in content['tables']:
                please_return_this_dict[x['id']] = x['name']
            return please_return_this_dict
            print(please_return_this_dict) # always prints the dict
    except KeyError:
        # the API returned a JSON string like "'error':'500'"
        sit_and_wait(url)

my_tables = query_for_tables(url)
print(type(my_tables))
# If a 500 status was received at least once, this returns NoneType
```

If the Except is never hit and sit_and_wait is unused in the function, the dictionary returns as expected. If the website gives me a 500 code any nonzero number of times, I receive a NoneType return.

答:
The problem is that once it does not get a 500, it will return a value to sit_and_wait but sit_and_wait does not return that value back to query_for_tables.  This will result in no return, or None being returned back to the initial query_for_tables in the except which will return None.

```<code>def sit_and_wait(url):
    print("500 received. sleeping.")
    time.sleep(1)
    return query_for_tables(url)

def query_for_tables(url):
    data = r.get(url)
    content = json.loads(data)
    please_return_this_dict = {}
    try:
        if content['tables']:
            for x in content['tables']:
                please_return_this_dict[x['id']] = x['name']
            return please_return_this_dict
            print(please_return_this_dict) # always prints the dict
    except KeyError:
        # the API returned a JSON string like "'error':'500'"
        return sit_and_wait(url)

my_tables = query_for_tables(url)
print(type(my_tables))
</code>```

This would be an example with a loop, which in most cases is better.

```<code>def query_for_tables(url):
    data = r.get(url)
    content = json.loads(data)
    please_return_this_dict = {}
    for i in range(100): # 100 second timeout
        try:
            if content['tables']:
                for x in content['tables']:
                    please_return_this_dict[x['id']] = x['name']
                return please_return_this_dict
                print(please_return_this_dict) # always prints the dict
        except KeyError:
            print("500 received. sleeping.")
            time.sleep(1)

my_tables = query_for_tables(url)
print(type(my_tables))
</code>```

Body:
I am scraping from a site using Requests. Given a valid URL, I loop through API services and available tables inside those services. The target site is old and will throw 500 codes at random, so I must control for this.

At present, I feed a For loop a list of Services. The loop sends services to a function that generates a URL to query the site for the names of Tables, and builds a dictionary of table names and ID's.

To catch the 500 codes and immediately retry the query, I use a try/except block inside the function, and direct the function to a separate helper function that prints a helpful error message stating that it got a 500 code. The helper then calls the function again, passing the query back to it, and it tries again.

The function works as expected when no 500 code is received. The function returns a dictionary for me with my IDs and names.

However, if a 500 code is received for that query, the function retries the query as described above, and is successful. However, the function returns None in these cases.

def sit_and_wait(url):
    print("500 received. sleeping.")
    time.sleep(1)
    query_for_tables(url)

def query_for_tables(url):
    data = r.get(url)
    content = json.loads(data)
    please_return_this_dict = {}
    try:
        if content['tables']:
            for x in content['tables']:
                please_return_this_dict[x['id']] = x['name']
            return please_return_this_dict
            print(please_return_this_dict) # always prints the dict
    except KeyError:
        # the API returned a JSON string like "'error':'500'"
        sit_and_wait(url)

my_tables = query_for_tables(url)
print(type(my_tables))
# If a 500 status was received at least once, this returns NoneType

If the Except is never hit and sit_and_wait is unused in the function, the dictionary returns as expected. If the website gives me a 500 code any nonzero number of times, I receive a NoneType return.

Body:
The problem is that once it does not get a 500, it will return a value to sit_and_wait but sit_and_wait does not return that value back to query_for_tables.  This will result in no return, or None being returned back to the initial query_for_tables in the except which will return None.

def sit_and_wait(url):
    print("500 received. sleeping.")
    time.sleep(1)
    return query_for_tables(url)

def query_for_tables(url):
    data = r.get(url)
    content = json.loads(data)
    please_return_this_dict = {}
    try:
        if content['tables']:
            for x in content['tables']:
                please_return_this_dict[x['id']] = x['name']
            return please_return_this_dict
            print(please_return_this_dict) # always prints the dict
    except KeyError:
        # the API returned a JSON string like "'error':'500'"
        return sit_and_wait(url)

my_tables = query_for_tables(url)
print(type(my_tables))

This would be an example with a loop, which in most cases is better.

def query_for_tables(url):
    data = r.get(url)
    content = json.loads(data)
    please_return_this_dict = {}
    for i in range(100): # 100 second timeout
        try:
            if content['tables']:
                for x in content['tables']:
                    please_return_this_dict[x['id']] = x['name']
                return please_return_this_dict
                print(please_return_this_dict) # always prints the dict
        except KeyError:
            print("500 received. sleeping.")
            time.sleep(1)

my_tables = query_for_tables(url)
print(type(my_tables))


问:
Textarea is not display information extracting from mysql record
I am attempting to display data in a textarea, I'm using the

```<code>$row=mysqli_fetch_array($results, MYSQLI_NUM)
</code>```

to extract the record. Using $row[2] displays the correct information using the p function. Using the same syntax with textarea does not display anything. The field is not blank in the database. The code does update the field properly.

I have tried changing to change the textarea to a paragraph with no success. I have change the variable by assigning to a new variable without success. I have tried escaping the column and row quotes all to no effect.

```<code><?php
echo '<input id="title_edit" type="text" name="ppy" value="'.$row[4].'">'
works

echo '<textarea id=prop_edit cols="65" rows="4" type="text" name="ppy" value="'.$row[7].'"></textarea>'  does not work.
?>
</code>```

Should read the field in the database and display it on the screen. But the screen field is blank. There is data in the database.

答:
I'd try:

```<code>var_dump($row[2]);
</code>```

to make sure it actually has the data I want in it.

Since you don't show how the data is being rendered into html I'll guess it is something like this?

```<code>echo '<textarea>' . $row[2] . '</textarea>';
</code>```

If so, check the "view source" option in your browser and double check that it is actually outputting what you expect. If the data in $row[2] contains any interesting characters like < or > or anything that resembles an html tag, you might have to escape the output like this:

```<code>echo '<textarea>' . htmlspecialchars($row[2]) . '</textarea>';
</code>```

Body:
I am attempting to display data in a textarea, I'm using the

$row=mysqli_fetch_array($results, MYSQLI_NUM)

to extract the record. Using $row[2] displays the correct information using the p function. Using the same syntax with textarea does not display anything. The field is not blank in the database. The code does update the field properly.

I have tried changing to change the textarea to a paragraph with no success. I have change the variable by assigning to a new variable without success. I have tried escaping the column and row quotes all to no effect.

<?php
echo '<input id="title_edit" type="text" name="ppy" value="'.$row[4].'">'
works

echo '<textarea id=prop_edit cols="65" rows="4" type="text" name="ppy" value="'.$row[7].'"></textarea>'  does not work.
?>

Should read the field in the database and display it on the screen. But the screen field is blank. There is data in the database.

Body:
I'd try:

var_dump($row[2]);

to make sure it actually has the data I want in it.

Since you don't show how the data is being rendered into html I'll guess it is something like this?

echo '<textarea>' . $row[2] . '</textarea>';

If so, check the "view source" option in your browser and double check that it is actually outputting what you expect. If the data in $row[2] contains any interesting characters like < or > or anything that resembles an html tag, you might have to escape the output like this:

echo '<textarea>' . htmlspecialchars($row[2]) . '</textarea>';