问:
Elasticsearch with grouped query_string
```<code>{
   "query":
   {
      "query_string" :
      {
         "query" : "((name:the_search_phrase) OR (keywords:the_search_phrase)) AND (city:Sydney, Australia)"
      }
   }
}
</code>```

New to elasticsearch. Building the JSON as per the documentation here: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html

The query runs, however, results with city other that Sydney, Australia are returned too. Why the AND part is not working?

I want the search phrase to match against either or both name, keywords but the city should be strictly Sydney.

答:
What you are doing is a full text query. city:Sydney, Australia seems to be a filter query. Like a WHERE clause in a SQL. You are better off using a filter query for that.

Look at the boolean query for examples,

Something like this perhaps,

```<code>    {
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "the_search_term",
            "fields": [
              "name",
              "keywords"
            ]
          }
        }
      ],
      "filter": [
        {
          "match": {
            "city": "Sydney, Australia"
          }
        }
      ]
    }
  }
}
</code>```

Title: Elasticsearch with grouped query_string

Body:
{
   "query":
   {
      "query_string" :
      {
         "query" : "((name:the_search_phrase) OR (keywords:the_search_phrase)) AND (city:Sydney, Australia)"
      }
   }
}

New to elasticsearch. Building the JSON as per the documentation here: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html

The query runs, however, results with city other that Sydney, Australia are returned too. Why the AND part is not working?

I want the search phrase to match against either or both name, keywords but the city should be strictly Sydney.

Body:
What you are doing is a full text query. city:Sydney, Australia seems to be a filter query. Like a WHERE clause in a SQL. You are better off using a filter query for that.

Look at the boolean query for examples,

Something like this perhaps,

    {
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "the_search_term",
            "fields": [
              "name",
              "keywords"
            ]
          }
        }
      ],
      "filter": [
        {
          "match": {
            "city": "Sydney, Australia"
          }
        }
      ]
    }
  }
}


来源: stackexchange

问:
How to transform multiple view to same location(CGPoint)
I've got multiple UIImageViews, spread across in a view.

```<code>@IBOutlet var leftIVs: [UIImageView]!
@IBOutlet var topIVs: [UIImageView]!
@IBOutlet var rightIVs: [UIImageView]!
</code>```

I'm trying to create a function using UIView.animate... functions and 'transform' property which brings all of these UIImageViews at the center of the superview. I'm using the following code:

```<code>let performInitialTransformation: ((UIImageView)->()) = { (card) in
    let cardCenter = CGPoint(x: card.frame.midX, y: card.frame.midY)
    let viewCenter = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
    let deltaPoint = cardCenter - viewCenter //also tried (viewCenter - cardCenter)
    UIView.animate(withDuration: 0.5, animations: {
        card.transform = CGAffineTransform.init(translationX: deltaPoint.x, y: deltaPoint.y)
    }) { (done) in
    }
}

for card in topIVs {
    performInitialTransformation(card)
}

for card in leftIVs {
    performInitialTransformation(card)
}

for card in rightIVs {
    performInitialTransformation(card)
}
</code>```

I'm using this static function:

```<code>extension CGPoint {
    static func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
        return CGPoint(x: rhs.x - lhs.x, y: rhs.y - lhs.y)
    }
}
</code>```

NOTE: Also, I will be bringing those images back to there original position afterward for which I will use CGAffineTransform.identity

The images are not being shown in the center. How can I achieve this? Thanks in advance!

答:
What is about to use center

```<code>UIView.animate(withDuration: 0.5) {
    images.forEach { $0.center = superview.center }
}
</code>```

The full example

```<code>var subviewes = [UIView]()
var view = UIView(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))
view.backgroundColor = .yellow
subviewes.append(view)

view = UIView(frame: CGRect.init(x: 0, y: 0, width: 20, height: 20))
view.backgroundColor = .green
subviewes.append(view)

view = UIView(frame: CGRect.init(x: 0, y: 0, width: 10, height: 10))
view.backgroundColor = .red
subviewes.append(view)

subviewes.forEach { self.view.addSubview($0) }

UIView.animate(withDuration: 0.5) {
    subviewes.forEach { $0.center = self.view.center }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got multiple UIImageViews, spread across in a view.

@IBOutlet var leftIVs: [UIImageView]!
@IBOutlet var topIVs: [UIImageView]!
@IBOutlet var rightIVs: [UIImageView]!

I'm trying to create a function using UIView.animate... functions and 'transform' property which brings all of these UIImageViews at the center of the superview. I'm using the following code:

let performInitialTransformation: ((UIImageView)->()) = { (card) in
    let cardCenter = CGPoint(x: card.frame.midX, y: card.frame.midY)
    let viewCenter = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
    let deltaPoint = cardCenter - viewCenter //also tried (viewCenter - cardCenter)
    UIView.animate(withDuration: 0.5, animations: {
        card.transform = CGAffineTransform.init(translationX: deltaPoint.x, y: deltaPoint.y)
    }) { (done) in
    }
}

for card in topIVs {
    performInitialTransformation(card)
}

for card in leftIVs {
    performInitialTransformation(card)
}

for card in rightIVs {
    performInitialTransformation(card)
}

I'm using this static function:

extension CGPoint {
    static func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
        return CGPoint(x: rhs.x - lhs.x, y: rhs.y - lhs.y)
    }
}

NOTE: Also, I will be bringing those images back to there original position afterward for which I will use CGAffineTransform.identity

The images are not being shown in the center. How can I achieve this? Thanks in advance!

Body:
What is about to use center

UIView.animate(withDuration: 0.5) {
    images.forEach { $0.center = superview.center }
}

The full example

var subviewes = [UIView]()
var view = UIView(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))
view.backgroundColor = .yellow
subviewes.append(view)

view = UIView(frame: CGRect.init(x: 0, y: 0, width: 20, height: 20))
view.backgroundColor = .green
subviewes.append(view)

view = UIView(frame: CGRect.init(x: 0, y: 0, width: 10, height: 10))
view.backgroundColor = .red
subviewes.append(view)

subviewes.forEach { self.view.addSubview($0) }

UIView.animate(withDuration: 0.5) {
    subviewes.forEach { $0.center = self.view.center }
}


问:
Use a server with a localhost SSL certificate
I have a software running on my server which is called Gitlab. The service is accessible through a SSH, HTTP and a HTTPS endpoint. All three access points are reachable through a SSH tunnel, so binded to 127.0.0.1.

```<code>> 127.0.0.1:80 # HTTP
> 127.0.0.1:443 # HTTPS
> 127.0.0.1:1234 # SSH
</code>```

To enable HTTPS, I created my own SSL certificate but of course there is no authority which confirms its authenticity. So even if I satisfy my server to work with it, I am wondering if I should even continue using it.

There are a lot of services on the server, or client tools which connect to it, and all would need to respect their system keychain where the public key is stored in as "trustworthy". Does anyone have experience with this constellation?

答:
Using a self-signed certificate is the default configuration, to speed up the startup process, and it's up to you to decide if you want to install a trusted certificate from a third party CA, or a local CA (maybe your AD integrated CA). If a service is local or internal to your company, you can decide to keep it self-signed.

In the environments i was involved with, there was a AD integrated CA and we signed everything with that.

Further informations: https://docs.gitlab.com/ee/user/project/pages/custom_domains_ssl_tls_certification/ssl_tls_concepts.html

Body:
I have a software running on my server which is called Gitlab. The service is accessible through a SSH, HTTP and a HTTPS endpoint. All three access points are reachable through a SSH tunnel, so binded to 127.0.0.1.

> 127.0.0.1:80 # HTTP
> 127.0.0.1:443 # HTTPS
> 127.0.0.1:1234 # SSH

To enable HTTPS, I created my own SSL certificate but of course there is no authority which confirms its authenticity. So even if I satisfy my server to work with it, I am wondering if I should even continue using it.

There are a lot of services on the server, or client tools which connect to it, and all would need to respect their system keychain where the public key is stored in as "trustworthy". Does anyone have experience with this constellation?


问:
Getting started with PHP in Eclipse IDE
I am a Java programmer, but recently got a job working with PHP and mySQL. I looked up good IDEs for this (I previously used Netbeans) and Eclipse was recommended.

When I tried to start working, I got the following error message:

```<code>Error launching 'firstfile'

The debug session could not be started.
Please make sure that the debugger is properly configured as a php.ini directive."
</code>```

I looked this up on Google and tried a bunch of the solutions proposed. I even re-installed Eclipse.

I have the following:

eclipse-php-helios-win32 (full)

WampServer2.1

My configuration is under Window->Settings->PHP->PHP Executables is:

```<code>Name: exec-wamp
Executable Path: C:\wamp\bin\php\php5.3.5\php.exe
PHP ini file: C:\wamp\bin\php\php5.3.5\php.ini
SATI Type: CLI
PHP debugger: XDebug
</code>```

NOTE: I tried to switch debuggers to Zend Debugger and this did not help.

答:
Check out the resource at http://www.xdebug.org/docs/install#configure-php and make sure you have everything configured as-described.

Specifically:

Ensure that your debugger is set up correctly in php.ini

Uncomment the string in php.ini

Restart your web-server (if you are on modphp)

Make sure that in your phpinfo() you have set xdebug

ContentLicense: CC BY-SA 3.0

Title: Getting started with PHP in Eclipse IDE

Body:
I am a Java programmer, but recently got a job working with PHP and mySQL. I looked up good IDEs for this (I previously used Netbeans) and Eclipse was recommended.

When I tried to start working, I got the following error message:

Error launching 'firstfile'

The debug session could not be started.
Please make sure that the debugger is properly configured as a php.ini directive."

I looked this up on Google and tried a bunch of the solutions proposed. I even re-installed Eclipse.

I have the following:

eclipse-php-helios-win32 (full)

WampServer2.1

My configuration is under Window->Settings->PHP->PHP Executables is:

Name: exec-wamp
Executable Path: C:\wamp\bin\php\php5.3.5\php.exe
PHP ini file: C:\wamp\bin\php\php5.3.5\php.ini
SATI Type: CLI
PHP debugger: XDebug

NOTE: I tried to switch debuggers to Zend Debugger and this did not help.


问:
How to free() an array of structs allocated by malloc()?
I've been working on a project that uses structs as storage for strings. I declared a struct consists of char type members:

```<code>struct datastore1
{
    char name[50];
    char address[50];
    char email[50];
    char number[50];
    char idnum[50];
};
</code>```

I'm aware that I can just do char *name, char *address... but let's say we specified it with max length of 50. Then on my function which uses the struct, I malloc'ed it with index size of 30:

```<code>struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));
</code>```

Supposedly I finished copying all strings into the struct by accessing each index, How should i free the allocated memory that was used after calling malloc? I tried doing free(dsdata) on the end of the program but I am not sure if it's the right way. Should i free each indexes individually? Please enlighten me. Thank you in advance for the feedback!

答:
1.

How should I free the allocated memory that was used after calling malloc?

I tried doing free(dsdata) on the end of the program but I am not sure if it's the right way.

free(dsdata) is fine, since you allocated the whole space by just one call to malloc with:

```<code>struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));
</code>```

To cite the standard (C18), 7.22.3.4 - "The malloc function" (emphasize mine):

7.22.3.4   The malloc function

Synopsis

1

```<code> #include <stdlib.h>
 void* malloc(size_t size);
</code>```

Description

2 The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

Returns

3 The malloc function returns either a null pointer or a pointer to the allocated space.

It is correct to use free(dsdata) because malloc allocated all of the required space at once and returned a pointer to the first structure variable of this array which is assigned to the pointer of dsdata.

The free() function "knows" that dsdata is a reference to the whole allocated space. You do not need to free each of the 30 structures of type struct datastore1 in memory individually.

2.

Should I free each indexes individually?

No, you do not need and even more important you should not do so; this would be Undefined Behavior:

Citation from the current standard (C18), 7.22.3.5/3 - "The free function" (emphasize mine):

Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

Body:
I've been working on a project that uses structs as storage for strings. I declared a struct consists of char type members:

struct datastore1
{
    char name[50];
    char address[50];
    char email[50];
    char number[50];
    char idnum[50];
};

I'm aware that I can just do char *name, char *address... but let's say we specified it with max length of 50. Then on my function which uses the struct, I malloc'ed it with index size of 30:

struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));

Supposedly I finished copying all strings into the struct by accessing each index, How should i free the allocated memory that was used after calling malloc? I tried doing free(dsdata) on the end of the program but I am not sure if it's the right way. Should i free each indexes individually? Please enlighten me. Thank you in advance for the feedback!

Body:
1.

How should I free the allocated memory that was used after calling malloc?

I tried doing free(dsdata) on the end of the program but I am not sure if it's the right way.

free(dsdata) is fine, since you allocated the whole space by just one call to malloc with:

struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));

To cite the standard (C18), 7.22.3.4 - "The malloc function" (emphasize mine):

7.22.3.4   The malloc function

Synopsis

1

 #include <stdlib.h>
 void* malloc(size_t size);

Description

2 The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

Returns

3 The malloc function returns either a null pointer or a pointer to the allocated space.

It is correct to use free(dsdata) because malloc allocated all of the required space at once and returned a pointer to the first structure variable of this array which is assigned to the pointer of dsdata.

The free() function "knows" that dsdata is a reference to the whole allocated space. You do not need to free each of the 30 structures of type struct datastore1 in memory individually.

2.

Should I free each indexes individually?

No, you do not need and even more important you should not do so; this would be Undefined Behavior:

Citation from the current standard (C18), 7.22.3.5/3 - "The free function" (emphasize mine):

Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.


问:
Wordpress custom hierarchy of breadcrumbs (and no hierarchy of slug / URLs)
I am trying to create a hierarchy of pages in Wordpress for the breadcrumbs. The simplest way to do it, is by using the "Parent Page" attribute. However, when using this feature, it also creates a hierarchy in the slugs (which means that change in the hierarchy requires to maintain a list of 301's and changing the internal links in the website).

For example, let's say that I have to following hierarchy:

Water

Glass of Water

Bottled Water

Fire

Light a Fire

The URL for the Glass of Water page will be: /water/glass-of-water/. how can I keep all the slugs "flat", while still have the hierarchy in the breadcrumbs (in this case Home > Water > Glass of Water and keep the url /glass-of-water)?

I found many WP websites that use this practice. For example the following post in the Yoast SEO website:

https://yoast.com/what-is-storytelling-and-why-should-you-use-it/

Has the following breadcrumbs:
Home » SEO blog » Content SEO » What is storytelling and why should you use it?

How can I set a custom breadcrumb hierarchy both for pages and for posts, regardless of the slug?

I use the latest version of Wordpress (Currently 5.3.X), with Yoast SEO plugin, the free version. If needed, I will install other plugins (free of paid), however I am trying to avoid plugins that are not popular or don't have enough reputation.

答:
I was facing the same issue a few days before I have one solution to create a breadcrumb.
Yoast Provides The Facility to create breadcrumb.

Code:

```<code><?php
if ( function_exists('yoast_breadcrumb') ) {
  yoast_breadcrumb( '<p id="breadcrumbs">','</p>' );
}
?>
</code>```

enter code here

here is link.

https://www.elegantthemes.com/blog/tips-tricks/how-to-add-breadcrumbs-to-your-wordpress-website

Body:
I was facing the same issue a few days before I have one solution to create a breadcrumb.
Yoast Provides The Facility to create breadcrumb.

Code:

<?php
if ( function_exists('yoast_breadcrumb') ) {
  yoast_breadcrumb( '<p id="breadcrumbs">','</p>' );
}
?>

enter code here

here is link.

https://www.elegantthemes.com/blog/tips-tricks/how-to-add-breadcrumbs-to-your-wordpress-website


问:
jquery selector problem
I'm using this code:

```<code>$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':"52px"});
    $(switches).parent().css({'background-position': "147px -37px"});
}})
</code>```

But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?

Thanks for your help :)

EDIT:
here is the HTML

```<code><fieldset>
        <input checked="checked" />
        <label></label>
        <div class="toggle_box">
            <div class="switch" state="on"></div>
        </div>
    </fieldset>
    <fieldset>
        <input/>
        <label></label>
        <div class="toggle_box">
            <div class="switch"></div>
        </div>
    </fieldset>
</code>```

答:
This piece of code is doing it...

```<code>$(this).attr('checked','checked')
</code>```

...which returns the set in order for the cascade to work. An Object is always truthy in JavaScript.

Try...

```<code>this.checked
</code>```

...which returns whether the checkbox is checked or not. If you wanted to do it the jQuery way, use $(this).is(':checked'). I wouldn't though, it's more verbose and less performant.

Title: jquery selector problem

Body:
I'm using this code:

$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':"52px"});
    $(switches).parent().css({'background-position': "147px -37px"});
}})

But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?

Thanks for your help :)

EDIT:
here is the HTML

<fieldset>
        <input checked="checked" />

    </fieldset>
    <fieldset>
        <input/>

    </fieldset>

Body:
This piece of code is doing it...

$(this).attr('checked','checked')

...which returns the set in order for the cascade to work. An Object is always truthy in JavaScript.

Try...

this.checked

...which returns whether the checkbox is checked or not. If you wanted to do it the jQuery way, use $(this).is(':checked'). I wouldn't though, it's more verbose and less performant.


问:
hide tab bar when navigating via stack navigator
I have a problem with react-navigation, hiding the tab bar on specific screens.

I have a bottom tabs navigator with 3 screens:

Mainscreen

Camerascreen

Postscreen

I also have a second (stack) navigator with 2 screens:

Mainscreen

Camerascreen

It should be possible to navigate from the Mainscreen to the Camerascreen via the tabs at the bottom of the screen, but I also need a button at the top of the screen to navigate to the Camerascreen. That's why I created the stack navigator.

My code on Camerascreen.js to hide the tab bar (this works when I navigate through the bottom tabs):

```<code>CameraScreen.navigationOptions = NavigationData => ({
    header: null,
    tabBarVisible: false
});
</code>```

What is the problem?

The problem is that when I navigate from the Mainscreen to the Camerascreen via the button (so not the bottom tabs), the bottom tabs are not hidden on the Camerascreen. When I navigate from the Mainscreen to the Camerascreen via the bottom tabs, the are hidden. I want them also to be hidden when I navigate via the stack navigator (and not only via the bottom tabs navigator).

I've checked the following question: https://reactnavigation.org/docs/en/navigation-options-resolution.html#a-tab-navigator-contains-a-stack-and-you-want-to-hide-the-tab-bar-on-specific-screens, but I cannot get it to work.

答:
You can use this logic to hide the tabBar on specific screens.

```<code>navigationOptions: ({navigation}) => {
        let tabBarVisible = true;
        if (navigation.state.routes.length > 1) {
          tabBarVisible = false;
        }
        return {
          tabBarVisible,
        };
      },
</code>```

as a example, in your stackNavigater

```<code>const HomeNavigation = createStackNavigator(
    {
      Home: {
        screen: HomeScreen,
        navigationOptions: ({navigation}) => {
          return {
            headerTitle: (
              <Header
                navigate={navigation.navigate}
              />
            ),
            headerStyle: {
              backgroundColor: '#d63921',
            },
            headerRight: (
              <HeaderRight
                navigate={navigation.navigate}
              />
            ),
          };
        },
      },
    },
    **{
      navigationOptions: ({navigation}) => {
        let tabBarVisible = true;
        if (navigation.state.routes.length > 1) {
          tabBarVisible = false;
        }
        return {
          tabBarVisible,
        };
      },**
      initialRouteName: 'Home',
      mode: 'card',
      lazy: false,
    },
  );

</code>```

Feel free for doubts

Body:
I have a problem with react-navigation, hiding the tab bar on specific screens.

I have a bottom tabs navigator with 3 screens:

Mainscreen

Camerascreen

Postscreen

I also have a second (stack) navigator with 2 screens:

Mainscreen

Camerascreen

It should be possible to navigate from the Mainscreen to the Camerascreen via the tabs at the bottom of the screen, but I also need a button at the top of the screen to navigate to the Camerascreen. That's why I created the stack navigator.

My code on Camerascreen.js to hide the tab bar (this works when I navigate through the bottom tabs):

CameraScreen.navigationOptions = NavigationData => ({
    header: null,
    tabBarVisible: false
});

What is the problem?

The problem is that when I navigate from the Mainscreen to the Camerascreen via the button (so not the bottom tabs), the bottom tabs are not hidden on the Camerascreen. When I navigate from the Mainscreen to the Camerascreen via the bottom tabs, the are hidden. I want them also to be hidden when I navigate via the stack navigator (and not only via the bottom tabs navigator).

I've checked the following question: https://reactnavigation.org/docs/en/navigation-options-resolution.html#a-tab-navigator-contains-a-stack-and-you-want-to-hide-the-tab-bar-on-specific-screens, but I cannot get it to work.

Body:
You can use this logic to hide the tabBar on specific screens.

navigationOptions: ({navigation}) => {
        let tabBarVisible = true;
        if (navigation.state.routes.length > 1) {
          tabBarVisible = false;
        }
        return {
          tabBarVisible,
        };
      },

as a example, in your stackNavigater

const HomeNavigation = createStackNavigator(
    {
      Home: {
        screen: HomeScreen,
        navigationOptions: ({navigation}) => {
          return {
            headerTitle: (
              <Header
                navigate={navigation.navigate}
              />
            ),
            headerStyle: {
              backgroundColor: '#d63921',
            },
            headerRight: (
              <HeaderRight
                navigate={navigation.navigate}
              />
            ),
          };
        },
      },
    },
    **{
      navigationOptions: ({navigation}) => {
        let tabBarVisible = true;
        if (navigation.state.routes.length > 1) {
          tabBarVisible = false;
        }
        return {
          tabBarVisible,
        };
      },**
      initialRouteName: 'Home',
      mode: 'card',
      lazy: false,
    },
  );

Feel free for doubts


问:
Typescript: Mapped type to make every property readonly except chosen properties
I ran into a challenge where I didn't want to keep rewriting multiple interfaces.

I need one interface to be fully writable, and also have a "copy" of that interface where all fields are readonly except those that I select to be writeable.

Typescript has mapped types which may allow this.

答:
export type DeepReadOnly<T> = { readonly [key in keyof T]: DeepReadOnly<T[key]> };
export type DeepMutable<T> = { -readonly [key in keyof T]: DeepMutable<T[key]> };
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type DeepKeepMutable<T, K extends keyof T> = DeepReadOnly<Omit<T, K>> & DeepMutable<Pick<T, K>>;

// use as follows
let o: DeepKeepMutable<Metadata, 'time' | 'payload'>;
// this will keep time and payload writeable while the rest are readonly

// it is also possible to extend and modify these types with index signatures, optional properties and level of depth

```


问:
global variable become null when listener run
I try to send calendar date that I get from the activity and send it to fragment  recyclerView via bundle and I received the date correctly but when I press a checkbox and alert the fragment by listener the date value becomes null

this is the Viewholder code

```<code>    private class addStudentViewHolder extends RecyclerView.ViewHolder {
        private MaterialCheckBox checkBox;
        private MaterialTextView nameTv;
        private int id;
        private List<StudentAttendeesDataModel> models = new ArrayList<>();

        private addStudentViewHolder(View itemView) {
            super(itemView);
            checkBox = itemView.findViewById(R.id.take_attendees);
            nameTv = itemView.findViewById(R.id.person_name);
        }

    private void bind(int position) {
        final StudentDataModel dataModel = dataModels.get(position);
        nameTv.setText(dataModel.getName());
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                id = dataModel.getId();
                Toast.makeText(context, "in" + calendarDate, Toast.LENGTH_SHORT).show();
                if (isChecked) {
                    StudentAttendeesDataModel model = new StudentAttendeesDataModel(id, calendarDate, 1);
                    models.add(model);
                    mListener.onCheckedChanged(models);
                } else {
                    StudentAttendeesDataModel model = new StudentAttendeesDataModel(id, calendarDate, 0);
                    models.remove(model);
                    mListener.onCheckedChanged(models);
                }
            }
        });
    }
}
</code>```

and this is code in the fragment.

```<code>   @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle bundle = getArguments();
            if (bundle != null) {
                calendarDate = bundle.getString(DATE_CALENDAR_KEY);
            }
        }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_student_recyclerview, container, false);
        RecyclerView recyclerView = v.findViewById(R.id.fragment_recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        dataSource = new DataSource(getActivity());
        List<StudentDataModel> dataModels = new ArrayList<>();
        List<StudentAttendeesDataModel> data = dataSource.getStudentAttendenas();
        adapter = new AttendeesAdapter(2, data, getContext(), this);
        adapter.setOnCreateStudentData(dataModels);
        recyclerView.setAdapter(adapter);
        setHasOptionsMenu(true);
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        List<StudentDataModel> dataModels = dataSource.getStudent();
        adapter.setStudentData(dataModels);
    }

    @Override
    public void onCheckedChanged(List<StudentAttendeesDataModel> models) {
        this.models = models;
    }
</code>```

the value becomes null exactly when I try to put it inside the adapter.

答:
Update your Attendees adapter to set calendarDate in your adapter and then use that value in your viewholder.

AttendeesAdapter(2, data, getContext(), this, calendarDate)

Body:
I try to send calendar date that I get from the activity and send it to fragment  recyclerView via bundle and I received the date correctly but when I press a checkbox and alert the fragment by listener the date value becomes null

this is the Viewholder code

    private class addStudentViewHolder extends RecyclerView.ViewHolder {
        private MaterialCheckBox checkBox;
        private MaterialTextView nameTv;
        private int id;
        private List<StudentAttendeesDataModel> models = new ArrayList<>();

        private addStudentViewHolder(View itemView) {
            super(itemView);
            checkBox = itemView.findViewById(R.id.take_attendees);
            nameTv = itemView.findViewById(R.id.person_name);
        }

    private void bind(int position) {
        final StudentDataModel dataModel = dataModels.get(position);
        nameTv.setText(dataModel.getName());
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                id = dataModel.getId();
                Toast.makeText(context, "in" + calendarDate, Toast.LENGTH_SHORT).show();
                if (isChecked) {
                    StudentAttendeesDataModel model = new StudentAttendeesDataModel(id, calendarDate, 1);
                    models.add(model);
                    mListener.onCheckedChanged(models);
                } else {
                    StudentAttendeesDataModel model = new StudentAttendeesDataModel(id, calendarDate, 0);
                    models.remove(model);
                    mListener.onCheckedChanged(models);
                }
            }
        });
    }
}

and this is code in the fragment.

   @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle bundle = getArguments();
            if (bundle != null) {
                calendarDate = bundle.getString(DATE_CALENDAR_KEY);
            }
        }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_student_recyclerview, container, false);
        RecyclerView recyclerView = v.findViewById(R.id.fragment_recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        dataSource = new DataSource(getActivity());
        List<StudentDataModel> dataModels = new ArrayList<>();
        List<StudentAttendeesDataModel> data = dataSource.getStudentAttendenas();
        adapter = new AttendeesAdapter(2, data, getContext(), this);
        adapter.setOnCreateStudentData(dataModels);
        recyclerView.setAdapter(adapter);
        setHasOptionsMenu(true);
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        List<StudentDataModel> dataModels = dataSource.getStudent();
        adapter.setStudentData(dataModels);
    }

    @Override
    public void onCheckedChanged(List<StudentAttendeesDataModel> models) {
        this.models = models;
    }

the value becomes null exactly when I try to put it inside the adapter.


问:
copy(\\DESKTOP-O2ERE3M\EPSON TM-T82 Receipt): failed to open stream: No such file or directory ESC POS
Hello to those who are using mike42/escpos and Laravel. When I test first on my local computer it works fine, it would print. But when I deploy it on the server, it would produce an error copy(\DESKTOP-O2ERE3M\EPSON TM-T82 Receipt): failed to open stream: No such file or directory.  For instance, after I deploy my project in the windows server, which I would access now my project through the internet, I was not able to print from my printer which connected to my computer and thus it produces an error that I mentioned above The printer is already a shared one. For short I'm trying to print the receipt using my printer installed in my computer from the server through the internet. I'm using a Laravel framework

```<code>$connector = new WindowsPrintConnector("EPSON TM-T82 Receipt");
$printer = new Printer($connector);
$printer -> text("Hello World\n");
$printer -> cut();
$printer -> close();
</code>```

I'm also using XAMPP on my server.

答:
Include the library

Composer

This library is designed for use with the composer PHP dependency manager. Simply add the mike42/escpos-php package to get started:

```<code>composer require mike42/escpos-php
</code>```

If you haven't used composer before, you can read about it at getcomposer.org.

Requirements

This project has few hard dependencies:

```<code>PHP 7.0 or newer.
json extension, used to load bundled printer definitions (see documentation)
intl extension, used for character encoding (see documentation)
zlib extension, used for de-compressing bundled resources (see documentation).
It is also suggested that you install either imagick or gd, as these can be used to
speed up image processing.
</code>```

A number of optional extensions can be added to enable more specific features. These are described in the "suggest" section of composer.json.

The 'Hello World' receipt
To make use of this driver, your server (where PHP is installed) must be able to communicate with your printer. Start by generating a simple receipt and sending it to your printer using the command-line.

```<code><?php
/* Call this file 'hello-world.php' */
require __DIR__ . '/vendor/autoload.php';
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\Printer;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
$printer -> text("Hello World!\n");
$printer -> cut();
$printer -> close();
</code>```

Some examples are below for common interfaces.

Communicate with a printer with an Ethernet interface using netcat:

```<code>php hello-world.php | nc 10.x.x.x. 9100
</code>```

Body:
Hello to those who are using mike42/escpos and Laravel. When I test first on my local computer it works fine, it would print. But when I deploy it on the server, it would produce an error copy(\DESKTOP-O2ERE3M\EPSON TM-T82 Receipt): failed to open stream: No such file or directory.  For instance, after I deploy my project in the windows server, which I would access now my project through the internet, I was not able to print from my printer which connected to my computer and thus it produces an error that I mentioned above The printer is already a shared one. For short I'm trying to print the receipt using my printer installed in my computer from the server through the internet. I'm using a Laravel framework

$connector = new WindowsPrintConnector("EPSON TM-T82 Receipt");
$printer = new Printer($connector);
$printer -> text("Hello World\n");
$printer -> cut();
$printer -> close();

I'm also using XAMPP on my server.

Body:
Include the library

Composer

This library is designed for use with the composer PHP dependency manager. Simply add the mike42/escpos-php package to get started:

composer require mike42/escpos-php

If you haven't used composer before, you can read about it at getcomposer.org.

Requirements

This project has few hard dependencies:

PHP 7.0 or newer.
json extension, used to load bundled printer definitions (see documentation)
intl extension, used for character encoding (see documentation)
zlib extension, used for de-compressing bundled resources (see documentation).
It is also suggested that you install either imagick or gd, as these can be used to
speed up image processing.

A number of optional extensions can be added to enable more specific features. These are described in the "suggest" section of composer.json.

The 'Hello World' receipt
To make use of this driver, your server (where PHP is installed) must be able to communicate with your printer. Start by generating a simple receipt and sending it to your printer using the command-line.

<?php
/* Call this file 'hello-world.php' */
require __DIR__ . '/vendor/autoload.php';
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\Printer;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
$printer -> text("Hello World!\n");
$printer -> cut();
$printer -> close();

Some examples are below for common interfaces.

Communicate with a printer with an Ethernet interface using netcat:

php hello-world.php | nc 10.x.x.x. 9100


问:
Why does a CSS transition not work well with another animation based on jQuery's animate method?
I have a button that I wish to move when it is clicked, and while moving it should also flip. So there are two animations that take place at the same time, and have the same duration. I also have a CSS transition set up for all the properties of the button. It seems to me that only the CSS scale transform works when I use both jQuery's animate method and the CSS transition effect. When I remove one of the animations, the other one works well.

// find elements
var button = $("button");

// handle click
button.on("click", function() {
  button.css({
    "transform": "scaleX(0)"
  });

 // the bug: the following animation is not visible
  button.animate({
    "top": "-100px" // I tried without "px" too
  }, 0.15 * 1000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;

  position: relative;
  transition: all 0.15s;
}</code>```

Hello World

  <button>Click me</button>

```

The JSFiddle is here.

Thank you.

答:
```<code>Please see the code on JS fiddle for smooth animation:
</code>```

https://jsfiddle.net/harshsetia/tvcb4mso/8/

Body:
I have a button that I wish to move when it is clicked, and while moving it should also flip. So there are two animations that take place at the same time, and have the same duration. I also have a CSS transition set up for all the properties of the button. It seems to me that only the CSS scale transform works when I use both jQuery's animate method and the CSS transition effect. When I remove one of the animations, the other one works well.

// find elements
var button = $("button");

// handle click
button.on("click", function() {
  button.css({
    "transform": "scaleX(0)"
  });

 // the bug: the following animation is not visible
  button.animate({
    "top": "-100px" // I tried without "px" too
  }, 0.15 * 1000);
});

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;

  position: relative;
  transition: all 0.15s;
}

Hello World

  <button>Click me</button>

The JSFiddle is here.

Thank you.

Body:
Please see the code on JS fiddle for smooth animation:

https://jsfiddle.net/harshsetia/tvcb4mso/8/


问:
Not able to configure OIDC with lua nginx
Am following below blog (https://developers.redhat.com/blog/2018/10/08/configuring-nginx-keycloak-oauth-oidc/) to setup an NGINX lua oidc.
Below is my installation and setup, am unable to run below commands

```<code>Install all the Lua modules using luarocks:

# luarocks install lua-cjson
# luarocks install lua-resty-openidc
</code>```

Results:

```<code>[root@samplesys nginx-lua]# yum install luarocks
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirror.netdepot.com
 * epel: mirror.lax.genesisadaptive.com
 * extras: mirror.netdepot.com
 * updates: mirror.netdepot.com
Package luarocks-2.3.0-1.el7.x86_64 already installed and latest version
Nothing to do

[root@sample nginx-lua]# luarocks install lua-cjson
Warning: falling back to curl - install luasec to get native HTTPS support
Warning: Failed searching manifest: Failed fetching manifest for https://luarocks.org - Failed downloading https://luarocks.org/manifest-5.1 - /var/cache/luarocks/https___luarocks.org/manifest-5.1
Warning: Failed searching manifest: Failed fetching manifest for https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/ - Failed downloading https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/manifest-5.1 - /var/cache/luarocks/https___raw.githubusercontent.com_rocks-moonscript-org_moonrocks-mirror_master_/manifest-5.1
Warning: Failed searching manifest: Failed extracting manifest file: failed extracting /var/cache/luarocks/http___luafr.org_moonrocks_/manifest-5.1.zip
Warning: Failed searching manifest: Failed extracting manifest file: failed extracting /var/cache/luarocks/http___luarocks.logiceditor.com_rocks/manifest-5.1.zip
lua-cjson not found for Lua 5.1.
Checking if available for other Lua versions...
Checking for Lua 5.2...
Checking for Lua 5.3...
Checking for Lua 5.4...

Error: No results matching query were found for Lua 5.1.

[root@sample nginx-lua]# luarocks install lua-resty-openidc
Warning: falling back to curl - install luasec to get native HTTPS support
Warning: Failed searching manifest: Failed fetching manifest for https://luarocks.org - Failed downloading https://luarocks.org/manifest-5.1 - /var/cache/luarocks/https___luarocks.org/manifest-5.1
Warning: Failed searching manifest: Failed fetching manifest for https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/ - Failed downloading https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/manifest-5.1 - /var/cache/luarocks/https___raw.githubusercontent.com_rocks-moonscript-org_moonrocks-mirror_master_/manifest-5.1
Warning: Failed searching manifest: Failed extracting manifest file: failed extracting /var/cache/luarocks/http___luafr.org_moonrocks_/manifest-5.1.zip
Warning: Failed searching manifest: Failed extracting manifest file: failed extracting /var/cache/luarocks/http___luarocks.logiceditor.com_rocks/manifest-5.1.zip
lua-resty-openidc not found for Lua 5.1.
Checking if available for other Lua versions...
Checking for Lua 5.2...
Checking for Lua 5.3...
Checking for Lua 5.4...

Error: No results matching query were found for Lua 5.1.
</code>```

答:
There's a few things that are wrong here:

Compiling nginx and manually adding lua-nginx-module is not the recommended way to install openresty. Quoting the readme:

It is highly recommended to use OpenResty releases which bundle Nginx, ngx_lua (this module), LuaJIT, as well as other powerful companion Nginx modules and Lua libraries.

The Lua version used in the tutorial seems to be PUC Lua 5.1, which really doesn't have anything going for it anymore; the reason people use 5.1 is that LuaJIT implements that version. I don't remember to which extent openresty even still supports that version, but later versions of it are certainly built mainly to work with LuaJIT.

You don't need to install lua-cjson if you're using an openresty release, as it already comes bundled (see readme)

Looking at the error you're getting Failed fetching manifest for https://luarocks.org - Failed downloading https://luarocks.org/manifest-5.1 it seems that luarocks can't download the manifest file, which is either a temporary problem with luarocks.org (It works for me as I am writing this answer), or a problem with your network. Try downloading the URL from the error message using a tool like wget or curl and see if that works (is curl even installed?)

Body:
Am following below blog (https://developers.redhat.com/blog/2018/10/08/configuring-nginx-keycloak-oauth-oidc/) to setup an NGINX lua oidc.
Below is my installation and setup, am unable to run below commands

Install all the Lua modules using luarocks:

# luarocks install lua-cjson
# luarocks install lua-resty-openidc

Results:

[root@samplesys nginx-lua]# yum install luarocks
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirror.netdepot.com
 * epel: mirror.lax.genesisadaptive.com
 * extras: mirror.netdepot.com
 * updates: mirror.netdepot.com
Package luarocks-2.3.0-1.el7.x86_64 already installed and latest version
Nothing to do

[root@sample nginx-lua]# luarocks install lua-cjson
Warning: falling back to curl - install luasec to get native HTTPS support
Warning: Failed searching manifest: Failed fetching manifest for https://luarocks.org - Failed downloading https://luarocks.org/manifest-5.1 - /var/cache/luarocks/https___luarocks.org/manifest-5.1
Warning: Failed searching manifest: Failed fetching manifest for https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/ - Failed downloading https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/manifest-5.1 - /var/cache/luarocks/https___raw.githubusercontent.com_rocks-moonscript-org_moonrocks-mirror_master_/manifest-5.1
Warning: Failed searching manifest: Failed extracting manifest file: failed extracting /var/cache/luarocks/http___luafr.org_moonrocks_/manifest-5.1.zip
Warning: Failed searching manifest: Failed extracting manifest file: failed extracting /var/cache/luarocks/http___luarocks.logiceditor.com_rocks/manifest-5.1.zip
lua-cjson not found for Lua 5.1.
Checking if available for other Lua versions...
Checking for Lua 5.2...
Checking for Lua 5.3...
Checking for Lua 5.4...

Error: No results matching query were found for Lua 5.1.

[root@sample nginx-lua]# luarocks install lua-resty-openidc
Warning: falling back to curl - install luasec to get native HTTPS support
Warning: Failed searching manifest: Failed fetching manifest for https://luarocks.org - Failed downloading https://luarocks.org/manifest-5.1 - /var/cache/luarocks/https___luarocks.org/manifest-5.1
Warning: Failed searching manifest: Failed fetching manifest for https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/ - Failed downloading https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/manifest-5.1 - /var/cache/luarocks/https___raw.githubusercontent.com_rocks-moonscript-org_moonrocks-mirror_master_/manifest-5.1
Warning: Failed searching manifest: Failed extracting manifest file: failed extracting /var/cache/luarocks/http___luafr.org_moonrocks_/manifest-5.1.zip
Warning: Failed searching manifest: Failed extracting manifest file: failed extracting /var/cache/luarocks/http___luarocks.logiceditor.com_rocks/manifest-5.1.zip
lua-resty-openidc not found for Lua 5.1.
Checking if available for other Lua versions...
Checking for Lua 5.2...
Checking for Lua 5.3...
Checking for Lua 5.4...

Error: No results matching query were found for Lua 5.1.


问:
how to break querySnapshot on Firestore?
I need to break querysnapshot loop. Is it possible?

I tried with for loop. but the below error is coming.

How to fix this error or Is there any way to break snapshot loop?

code

```<code>  return query.get()
    .then((snapshot) => {
      for(const doc of snapshot) {
        let data = doc.data()
        if (data.age == 16) {
            break;
        }
  }
</code>```

error

Type 'QuerySnapshot' must have a 'Symbol.iterator' method that returns an iterator.

答: Docs say that QuerySnapshot<T> is not an iterator/async iterator so you can't use it like one. Seems like the only way to iterate over it is with forEach which doesn't seem to provide a way of "early breaking".

Body:
I need to break querysnapshot loop. Is it possible?

I tried with for loop. but the below error is coming.

How to fix this error or Is there any way to break snapshot loop?

code

  return query.get()
    .then((snapshot) => {
      for(const doc of snapshot) {
        let data = doc.data()
        if (data.age == 16) {
            break;
        }
  }

error

Type 'QuerySnapshot' must have a 'Symbol.iterator' method that returns an iterator.


问:
Design Tips for PHP Function Include Files
Good design dictates only writing each function once.  In PHP I'm doing this by using include files (like Utils.php and Authenticate.php), with the PHP command include_once.  However I haven't been able to find any standards or best practices for PHP include files.  What would you at StackOverflow suggest?

I'm looking for:

Naming Standards

Code Standards

Design Patterns

Suggestions for defining return types of common functions
(now I'm just using associative arrays).

答:
Some such standards have been written already.  Most large projects will follow and standard of their own.

Here is one written by Zend and is the standard used in the Zend framework.
http://framework.zend.com/manual/en/coding-standard.html

Also, PEAR always had some fairly strict coding standards:
http://pear.php.net/manual/en/standards.php

My preferred answer though is that for your own project you should use what you feel comfortable with, and be internally consistent.  For other projects, follow their rules.  The consistency allows for greatest code readability.  My own standards are not the same as the PEAR ones.  I do not indent with four spaces (I use tabs) and I never use camel case like function names, but nonetheless if I am editing something from another project I'll go with whatever that project does.

OwnerDisplayName: C. Ross

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: thomasrutter

LastEditorDisplayName: thomasrutter


问:
How to create a SSL certificate for a host without domain?
I am testing and debugging a system where application A submits a POST request to a URL when some event occurs. One of my programs, application B, must react to this event.

Application A requires that the URL uses HTTPS. I don't want to use a self-signed certificate because it may cause problems (curl complains about the self-signed certificate when I test it locally).

Letsencrypt can create a SSL certificate for free, but requires a domain. This is a problem for me because application B runs on a virtual machine. Whenever the machine is restarted, it gets a different IP address. Currently, there is no domain associated with that machine (i. e. you can only access it via a URL like http://aaa.bbb.ccc.ddd/).

Is there a way to use a non-self-signed certificate for an application without domain (i. e. one that runs on a URL like http://aaa.bbb.ccc.ddd/)? If not, what is the easiest way to make a Spring boot application (application B) support a non-self-signed SSL certificate?

There is one answer suggesting to create one's own certificate authority and installing it on all machines that access the URL. This is not an option for me because I have no control over application A.

Update 1: Application B runs on an EC2 instance in AWS.

答:
Letsencrypt can create a SSL certificate for free, but requires a domain. This is a problem for me because application B runs on a virtual machine. Whenever the machine is restarted, it gets a different IP address.

It does not matter if the IP changes since all what is checked is the domain name. Thus, if the machine gets a new IP address you need to update the DNS to point to this new domain name.

In general the client will check if the subject/SAN of the certificate matches the domain in the URL. It is not possible to get a certificate which is generic enough to cover all the IP addresses you could get. Thus, having your own fixed domain name with a dynamic IP address behind it is the way to go if you want to use normal clients to access the site.


问:
Issue with parsing @odata values using Swift
My service response is following:

```<code>{
"@odata.context" = "https://xxx-d.www.com/odata/$metadata#Members";
"@odata.count" = 1;
 value = ({
        email = "Suamasu@xxx.com";
        memberType = User;
        name = "Suse";
        title = "Manager";
   });
}
</code>```

I am able to decode value which using Decodable swift type, however I need "@odata.count" value to be decoded from response.

```<code>struct Members: Decodable {
    let value: [Member]
}

struct Member: Decodable {
    let name: String?
    let email: String
    let memberType: String?
    let title: String?
}
</code>```

答:
Can you try to add coding keys to Members?

```<code>struct Members: Decodable {
    let context: String
    let count: Int
    let value: [Member]

    enum CodingKeys: String, CodingKey {
        case context = "@odata.context"
        case count = "@odata.count"
        case value
    }
}
</code>```

More info: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

Body:
My service response is following:

{
"@odata.context" = "https://xxx-d.www.com/odata/$metadata#Members";
"@odata.count" = 1;
 value = ({
        email = "Suamasu@xxx.com";
        memberType = User;
        name = "Suse";
        title = "Manager";
   });
}

I am able to decode value which using Decodable swift type, however I need "@odata.count" value to be decoded from response.

struct Members: Decodable {
    let value: [Member]
}

struct Member: Decodable {
    let name: String?
    let email: String
    let memberType: String?
    let title: String?
}

Body:
Can you try to add coding keys to Members?

struct Members: Decodable {
    let context: String
    let count: Int
    let value: [Member]

    enum CodingKeys: String, CodingKey {
        case context = "@odata.context"
        case count = "@odata.count"
        case value
    }
}

More info: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types


问:
Page redirects incorrectly if a user is logged in
I'm currently working on a login functionality of a web application.

I have the "Login Page" when I load the http://localhost:8080/test/, which can only be accessed if a user is not logged in.
Once the user is successfully logged in, he should now see the "Welcome Page" on http://localhost:8080/test/welcome, displaying a "Name" link.
Clicking the "Name" link should go to http://localhost:8080/test/welcome/name.
If the user have not logged out but visited the http://localhost:8080/test/, he should be redirected to "Welcome Page".

(The function is like the Facebook app. If you haven't logged out on Tab 1, you can still view your News Feed if you visited Facebook on Tab 2 of your browser.)

Here's the problem. While logged in, I'm able to load the "Welcome Page" when I visited http://localhost:8080/test/.
However, when I clicked on the "Name" link on the "Welcome Page", I was just redirected to http://localhost:8080/test/welcome, which is the link for the "Welcome Page". It seems that it just reloaded the page.

Here are some code sample:

Login.tsx

```<code><Switch>
    {checkLoginUserId() != null ?
        <Redirect to="/welcome" />
        : <Redirect to="/" />}
</Switch>
<Route path="/welcome" component={Welcome} />
<Route exact path="/" component={Login} />
</code>```

Welcome.tsx

```<code><Route exact={true} path="/welcome" component={Welcome} />
<Route path="/welcome/name" component={Name} />
</code>```

I don't know why it goes to the other route. It seems that the answer to my problem is very easy but I cannot pinpoint the culprit.

答:
It seems you'd be passing the actual name in the to prop of Link tag like
 to="/welcome/abc"

Change your route in Welcome.tsx to this

```<code><Route path="/welcome/:name" component={Name} /> //:name accepts any name
</code>```

Body:
I'm currently working on a login functionality of a web application.

I have the "Login Page" when I load the http://localhost:8080/test/, which can only be accessed if a user is not logged in.
Once the user is successfully logged in, he should now see the "Welcome Page" on http://localhost:8080/test/welcome, displaying a "Name" link.
Clicking the "Name" link should go to http://localhost:8080/test/welcome/name.
If the user have not logged out but visited the http://localhost:8080/test/, he should be redirected to "Welcome Page".

(The function is like the Facebook app. If you haven't logged out on Tab 1, you can still view your News Feed if you visited Facebook on Tab 2 of your browser.)

Here's the problem. While logged in, I'm able to load the "Welcome Page" when I visited http://localhost:8080/test/.
However, when I clicked on the "Name" link on the "Welcome Page", I was just redirected to http://localhost:8080/test/welcome, which is the link for the "Welcome Page". It seems that it just reloaded the page.

Here are some code sample:

Login.tsx

<Switch>
    {checkLoginUserId() != null ?
        <Redirect to="/welcome" />
        : <Redirect to="/" />}
</Switch>
<Route path="/welcome" component={Welcome} />
<Route exact path="/" component={Login} />

Welcome.tsx

<Route exact={true} path="/welcome" component={Welcome} />
<Route path="/welcome/name" component={Name} />

I don't know why it goes to the other route. It seems that the answer to my problem is very easy but I cannot pinpoint the culprit.

Body:
It seems you'd be passing the actual name in the to prop of Link tag like
 to="/welcome/abc"

Change your route in Welcome.tsx to this

<Route path="/welcome/:name" component={Name} /> //:name accepts any name


答:
You're passing the checked value to attr() as the second argument. That causes it to be set. What's then returned is the jQuery object with that input, which is always a truthy value.

Your if condition should look like this (use the :checked pseudo-class instead):

```<code>if ($(this).is(':checked')) {
</code>```

On a side note, your inner code can be refactored to this:

```<code>$(this).parent().find('.switch')
    .attr('state', 'on')
    .css({ 'left': "52px" })
    .parent()
        .css({ 'background-position': "147px -37px" });
</code>```

If you have to use a cached variable (i.e. switches), you can, but don't wrap it in the jQuery function. It's a jQuery object itself, so needs not be wrapped.

Title: jquery selector problem

Body:
You're passing the checked value to attr() as the second argument. That causes it to be set. What's then returned is the jQuery object with that input, which is always a truthy value.

Your if condition should look like this (use the :checked pseudo-class instead):

if ($(this).is(':checked')) {

On a side note, your inner code can be refactored to this:

$(this).parent().find('.switch')
    .attr('state', 'on')
    .css({ 'left': "52px" })
    .parent()
        .css({ 'background-position': "147px -37px" });

If you have to use a cached variable (i.e. switches), you can, but don't wrap it in the jQuery function. It's a jQuery object itself, so needs not be wrapped.


问:
How to route nodejs requests to another nodejs application?
Hi I am trying to build a really simple "API-gateway" to demonstrate a small scale microservice project. I am using Nodejs and Express and I wanted to write a really simple public facing api-gateway server to route requests to my different microservices. For example lets say I have microservice A B and C. I wanted requests to localhost:3000/api/A to go to microservice A and return the result and then all other requests to localhost:3000/api/B go to microservice B and return the result ect. I wanted to write this instead of using NGINX, could someone help me understand how I can achieve this? (Most of my other "microservices" are also nodejs/express apis)

Could I get a quick simple example in code? I would love to see a GET request to google and then the client be able to get the GET request. (use of other libraries or modules would be cool too! :D)

答: If all micro-services are deployed on the same machine(different machines just need a bit more syncing to know ports/ips but that should not be an issue), you just use a common file to store ops/ports and then just redirect calls from route ip:3000/api/A to ipA:portA</p>


问:
UIPageViewController overlapping other view [Swift - UIStoryBoard]
I am trying add UIPageView with static position counter. But UIPageView page hiding Counter Label

Following code - I am creating PageViewController in my ControllerView.

```<code>func createPageViewController(){
    let pageVC = self.storyboard?.instantiateViewController(identifier:
    Constant.storyIdPageViewIdentifier) as! UIPageViewController

    pageVC.dataSource = self

    if carsArray.count>0 {
        let imageController = getImageViewController(withIndex: 0)!

        let imageControllers = [imageController]
        pageVC.setViewControllers(imageControllers, direction: .forward, animated: true, completion: nil)
    }

    pageViewController = pageVC

    self.addChild(pageViewController!)
    self.view.addSubview(pageViewController!.view)
    pageViewController?.didMove(toParent: self)

}
</code>```

答: Try using   self.view.bringSubviewToFront(counterlabel)

Body:
I am trying add UIPageView with static position counter. But UIPageView page hiding Counter Label

Following code - I am creating PageViewController in my ControllerView.

func createPageViewController(){
    let pageVC = self.storyboard?.instantiateViewController(identifier:
    Constant.storyIdPageViewIdentifier) as! UIPageViewController

    pageVC.dataSource = self

    if carsArray.count>0 {
        let imageController = getImageViewController(withIndex: 0)!

        let imageControllers = [imageController]
        pageVC.setViewControllers(imageControllers, direction: .forward, animated: true, completion: nil)
    }

    pageViewController = pageVC

    self.addChild(pageViewController!)
    self.view.addSubview(pageViewController!.view)
    pageViewController?.didMove(toParent: self)

}


答:
You can run B on port 3001, C on 3002.

Then dispach all request by A on port 3000.

You can use Http client like axios in A to request B or C.

Example

A.js

const express = require('express')
const axios = require('axios')

const app = express()

app.get('/api/B', (req, res) => {
  axios.get('http://localhost:3001/dosomething', {
    params: {...req.query, name: 'Device A'}, //Fetch datas from params
  }).then(result => {
    res.send(result)
  })
})

app.get('/api/C', (_, res) => {
  axios.get('http://localhost:3002/dosomething').then(result => {
    res.send(result)
  })
})

app.listen(3000, () => console.log('On 3000'))
```

<p>B.js</p>

<pre class="lang-js prettyprint-override"><code>const express = require('express')
const app = express()

app.get('/dosomething', (req, res) => {
  const data = req.query
  //Do something with data fetched here you know...
  res.send('No worry, I will do something for ' + data.name)
})

app.listen(3001, () => console.log('On 3001'))
</code>```

Title: How to route nodejs requests to another nodejs application?

Body:
Hi I am trying to build a really simple "API-gateway" to demonstrate a small scale microservice project. I am using Nodejs and Express and I wanted to write a really simple public facing api-gateway server to route requests to my different microservices. For example lets say I have microservice A B and C. I wanted requests to localhost:3000/api/A to go to microservice A and return the result and then all other requests to localhost:3000/api/B go to microservice B and return the result ect. I wanted to write this instead of using NGINX, could someone help me understand how I can achieve this? (Most of my other "microservices" are also nodejs/express apis)

Could I get a quick simple example in code? I would love to see a GET request to google and then the client be able to get the GET request. (use of other libraries or modules would be cool too! :D)

Body:
You can run B on port 3001, C on 3002.

Then dispach all request by A on port 3000.

You can use Http client like axios in A to request B or C.

Example

A.js

const express = require('express')
const axios = require('axios')

const app = express()

app.get('/api/B', (req, res) => {
  axios.get('http://localhost:3001/dosomething', {
    params: {...req.query, name: 'Device A'}, //Fetch datas from params
  }).then(result => {
    res.send(result)
  })
})

app.get('/api/C', (_, res) => {
  axios.get('http://localhost:3002/dosomething').then(result => {
    res.send(result)
  })
})

app.listen(3000, () => console.log('On 3000'))

B.js

const express = require('express')
const app = express()

app.get('/dosomething', (req, res) => {
  const data = req.query
  //Do something with data fetched here you know...
  res.send('No worry, I will do something for ' + data.name)
})

app.listen(3001, () => console.log('On 3001'))


问:
How long does the Dependency Injection Object exists(Scoped & Transient) in the server
I want to know some details about, how long the service object retains the value like is there any Time constraint for the service objects especially for Scoped and Transient.

Scoped: It retains the value for particular request (think of a browser tab).

Transient: It retains the value for the particular Component.

What if i stays long (not doing any action) in the particular Component(Page) where i have used Scoped and Transient service object.

Will the value be retained forever ? or will it dispose automatically after some time ?

答:
What if i stays long (not doing any action) in the particular Component(Page) where i have used Scoped and Transient service object.

A request lasts from the point you hit enter in the url (or a link or button) until the page is loaded. After that, the request ends.

HTTP is stateless, it doesn't have any permanent connection or state. If a page takes 50 ms to load, after that the request ends and services get disposed. When you click a link, a new request starts with new dependencies instantiated.

Every request will always have a new instance, so don't "store" data in services that you need for next request. If you need stuff for next request only, use TempData and if it needs to persist more than until next time its accessed, use Sessions

Will the value be retained forever ? or will it dispose automatically after some time?

After end of the request, its not save to access the services anymore. Disposing releases all unmanaged resources (connection, file handles, unmanaged memory).

The object itself remains some (unspecified) time in memory until the garbage collection kicks in and frees the object and the memory. That assumes you are not holding any reference to the service after the request ends, since only objects that have no references can be garbage collected.

That's how managed runtimes work. Garbage collection is not deterministic, so it can happen at any time when the conditions to trigger it are happened.


问:
PostgreSQL/psycopg2 Password Authentication using SSH Tunneling
I am trying to connect to a PostgreSQL Database via ssh tunnel. It is set up to listen on port 3333 and forward to port 5432 on the machine with the database. I am able to connect using the psql command with password authentication via the tunnel, but for some reason when I attempt to connect using psycopg2 via the tunnel, I get the error FATAL:  password authentication failed for user database_user. I have tried putting quotes around user names and passwords to no avail.

Successful psql command:

```<code>psql -h localhost -p 3333 -U database_name database_user
#This command brings up password prompt
</code>```

Failed pscyopg2 command:

psycopg2.connect("dbname='database_name' user='database_user' host='localhost' password='database_password' port=3333")

Output:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/database_user/.local/share/virtualenvs/project-QNhT-Vzg/lib/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL:  password authentication failed for user "database_user"
FATAL:  password authentication failed for user "database_user"
</code>```

Here is part of my pg_hba.conf for reference:

```<code># Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5
</code>```

答:
When debugging a connection issue it is always worthy to remember what layers we must go through before reaching the service. When you connect PostgreSQL service there will be at least three layers:

Networking: Firewall, NAT, Port Forwarding

PostgreSQL ACL

PostgreSQL login

It is important to understand what layer cause the issue, the PostgreSQL client (wrapped in psycopg2 in your scenario) error will help you to resolve this by issuing an ad-hoc error message:

Network issue will generally raise a typical: Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?which means you did not succeed to connect the PostgreSQL service at all, problem relies before the service;

ACL issue will generally raise a typical: No pg_hba.conf entry for host <hostname>, user <username>, database <database> which means you did connect the PostgreSQL service but the connection is not referenced as valid in ACL;

Login issue will generally raise the error you have got: password authentication failed for user "<user>" which means you did connect the PostgreSQL service and the connection complies with an ACL entry but the authentication failed.

In the later scenario, it is important to know which entry triggered, because it defines the authentication mode. In your case, it was a md5 entry (because there is no password in peer mode and your SSH tunnel should map the localhost so you are seen as host instead of local for a postgreSQL perspective):

```<code>host    all             all             127.0.0.1/32            md5
</code>```

Apparently your password is not what you expect it to be. To solve this, ensure:

you have set the password to the postgreSQL user and checked the LOGIN privileges (not the unix/SSH user, there are different concepts);

you use the same password in your psycopg2 connection, then you must be able to connect;

Reading your comment, it seems you may have ' quote in your password as well. So your password in your connection might be:

psycopg2.connect("dbname='database_name' user='database_user' host='localhost' password="'database_password'" port=3333")
```

Or if the quote are required it may indicate that you use some special characters that need to be escaped. You can also try simpler password to debug and then fallback on a stronger one.

Body:
I am trying to connect to a PostgreSQL Database via ssh tunnel. It is set up to listen on port 3333 and forward to port 5432 on the machine with the database. I am able to connect using the psql command with password authentication via the tunnel, but for some reason when I attempt to connect using psycopg2 via the tunnel, I get the error FATAL:  password authentication failed for user database_user. I have tried putting quotes around user names and passwords to no avail.

Successful psql command:

psql -h localhost -p 3333 -U database_name database_user
#This command brings up password prompt

Failed pscyopg2 command:

psycopg2.connect("dbname='database_name' user='database_user' host='localhost' password='database_password' port=3333")

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/database_user/.local/share/virtualenvs/project-QNhT-Vzg/lib/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL:  password authentication failed for user "database_user"
FATAL:  password authentication failed for user "database_user"

Here is part of my pg_hba.conf for reference:

# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5

Body:
When debugging a connection issue it is always worthy to remember what layers we must go through before reaching the service. When you connect PostgreSQL service there will be at least three layers:

Networking: Firewall, NAT, Port Forwarding

PostgreSQL ACL

PostgreSQL login

It is important to understand what layer cause the issue, the PostgreSQL client (wrapped in psycopg2 in your scenario) error will help you to resolve this by issuing an ad-hoc error message:

Network issue will generally raise a typical: Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?which means you did not succeed to connect the PostgreSQL service at all, problem relies before the service;

ACL issue will generally raise a typical: No pg_hba.conf entry for host <hostname>, user <username>, database <database> which means you did connect the PostgreSQL service but the connection is not referenced as valid in ACL;

Login issue will generally raise the error you have got: password authentication failed for user "<user>" which means you did connect the PostgreSQL service and the connection complies with an ACL entry but the authentication failed.

In the later scenario, it is important to know which entry triggered, because it defines the authentication mode. In your case, it was a md5 entry (because there is no password in peer mode and your SSH tunnel should map the localhost so you are seen as host instead of local for a postgreSQL perspective):

host    all             all             127.0.0.1/32            md5

Apparently your password is not what you expect it to be. To solve this, ensure:

you have set the password to the postgreSQL user and checked the LOGIN privileges (not the unix/SSH user, there are different concepts);

you use the same password in your psycopg2 connection, then you must be able to connect;

Reading your comment, it seems you may have ' quote in your password as well. So your password in your connection might be:

psycopg2.connect("dbname='database_name' user='database_user' host='localhost' password="'database_password'" port=3333")

Or if the quote are required it may indicate that you use some special characters that need to be escaped. You can also try simpler password to debug and then fallback on a stronger one.


问:
Ionic ios app not emulating to ios simulator through cli commands
I am starting to create new app with latest ionic version.

I got the following info through ionic info command

```<code>Ionic:

   Ionic CLI                     : 6.1.0 (/usr/local/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.0.0
   @angular-devkit/build-angular : 0.803.25
   @angular-devkit/schematics    : 8.3.25
   @angular/cli                  : 8.3.25
   @ionic/angular-toolkit        : 2.1.2

Cordova:

   Cordova CLI       : not installed
   Cordova Platforms : not available
   Cordova Plugins   : not available

Utility:

   cordova-res : not installed
   native-run  : 0.3.0

System:

   ios-deploy : 1.10.0
   ios-sim    : 8.0.2
   NodeJS     : v12.16.0 (/usr/local/bin/node)
   npm        : 6.13.7
   OS         : macOS Catalina
   Xcode      : Xcode 11.3.1 Build version 11C504
</code>```

I just followed the following steps

```<code>npm install -g @ionic/cli
ionic start myApp tabs
cd myApp
ionic serve
</code>```

when i run ionic serve i get the web page opened automatically.

and then i have added the ios developer account to the xcode

```<code>xcode-select --install
npm install -g ios-sim
brew install ios-deploy
ionic cordova prepare ios
ionic cordova run ios -l --external
</code>```

so finally when i run the cli command. I get the simulator opened automatically and some popup verifying myapp.app and close after few seconds after that app not installed in simulator.

It works when I run manually from xcode.

Please help me to get the "ionic cordova run ios -l --external" command run successfully.

When i run cordova in the terminal i get the following error but cordova is installed globally using the sudo command and cordova folder is exist in the npm modules.

cordova

/usr/local/lib/node_modules/cordova/node_modules/write-file-atomic/index.js:236
      throw err
      ^

Error: EACCES: permission denied, open
  '/Users/soundhar/Library/Preferences/insight-nodejs/insight-cordova.json.2409298856'
      at Object.openSync (fs.js:457:3)
      at Function.writeFileSync [as sync] (/usr/local/lib/node_modules/cordova/node_modules/write-file-atomic/index.js:212:13)
      at Conf.set store [as store] (/usr/local/lib/node_modules/cordova/node_modules/conf/index.js:142:19)
      at new Conf (/usr/local/lib/node_modules/cordova/node_modules/conf/index.js:44:14)
      at new Insight (/usr/local/lib/node_modules/cordova/node_modules/insight/lib/index.js:40:35)
      at Object. (/usr/local/lib/node_modules/cordova/src/telemetry.js:26:15)
      at Module._compile (internal/modules/cjs/loader.js:1157:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
      at Module.load (internal/modules/cjs/loader.js:1001:32)
      at Function.Module._load (internal/modules/cjs/loader.js:900:14) {   errno: -13,   syscall: 'open',   code: 'EACCES',   path:
  '/Users/soundhar/Library/Preferences/insight-nodejs/insight-cordova.json.2409298856'
  }

Thanks for all

答:
Try to run this two commands:</p>

```<code>sudo chown -R $USER:$GROUP ~/.npm
sudo chown -R $USER:$GROUP ~/.config
</code>```

Body:
I am starting to create new app with latest ionic version.

I got the following info through ionic info command

Ionic:

   Ionic CLI                     : 6.1.0 (/usr/local/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.0.0
   @angular-devkit/build-angular : 0.803.25
   @angular-devkit/schematics    : 8.3.25
   @angular/cli                  : 8.3.25
   @ionic/angular-toolkit        : 2.1.2

Cordova:

   Cordova CLI       : not installed
   Cordova Platforms : not available
   Cordova Plugins   : not available

Utility:

   cordova-res : not installed
   native-run  : 0.3.0

System:

   ios-deploy : 1.10.0
   ios-sim    : 8.0.2
   NodeJS     : v12.16.0 (/usr/local/bin/node)
   npm        : 6.13.7
   OS         : macOS Catalina
   Xcode      : Xcode 11.3.1 Build version 11C504

I just followed the following steps

npm install -g @ionic/cli
ionic start myApp tabs
cd myApp
ionic serve

when i run ionic serve i get the web page opened automatically.

and then i have added the ios developer account to the xcode

xcode-select --install
npm install -g ios-sim
brew install ios-deploy
ionic cordova prepare ios
ionic cordova run ios -l --external

so finally when i run the cli command. I get the simulator opened automatically and some popup verifying myapp.app and close after few seconds after that app not installed in simulator.

It works when I run manually from xcode.

Please help me to get the "ionic cordova run ios -l --external" command run successfully.

When i run cordova in the terminal i get the following error but cordova is installed globally using the sudo command and cordova folder is exist in the npm modules.

cordova

/usr/local/lib/node_modules/cordova/node_modules/write-file-atomic/index.js:236
      throw err
      ^

Error: EACCES: permission denied, open
  '/Users/soundhar/Library/Preferences/insight-nodejs/insight-cordova.json.2409298856'
      at Object.openSync (fs.js:457:3)
      at Function.writeFileSync [as sync] (/usr/local/lib/node_modules/cordova/node_modules/write-file-atomic/index.js:212:13)
      at Conf.set store [as store] (/usr/local/lib/node_modules/cordova/node_modules/conf/index.js:142:19)
      at new Conf (/usr/local/lib/node_modules/cordova/node_modules/conf/index.js:44:14)
      at new Insight (/usr/local/lib/node_modules/cordova/node_modules/insight/lib/index.js:40:35)
      at Object. (/usr/local/lib/node_modules/cordova/src/telemetry.js:26:15)
      at Module._compile (internal/modules/cjs/loader.js:1157:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
      at Module.load (internal/modules/cjs/loader.js:1001:32)
      at Function.Module._load (internal/modules/cjs/loader.js:900:14) {   errno: -13,   syscall: 'open',   code: 'EACCES',   path:
  '/Users/soundhar/Library/Preferences/insight-nodejs/insight-cordova.json.2409298856'
  }

Thanks for all

Body:
Try to run this two commands:

sudo chown -R $USER:$GROUP ~/.npm
sudo chown -R $USER:$GROUP ~/.config


答:
You can use the docs property of the QuerySnapshot, which returns an array of all the documents in the QuerySnapshot.

For example, with a for loop:

```<code>  return query.get()
    .then((snapshot) => {
      const snapshotsArray = snapshot.docs;
      for (var i = 0; i < snapshotsArray.length; i++) {
        const data = snapshotsArray[i].data()
        if (data.age == 16) {
            break;
        }
      }
  }
</code>```

or with a for-of:

```<code>  return query.get()
    .then((snapshot) => {
      const snapshotsArray = snapshot.docs;
      for (const snap of snapshotsArray) {
        const data = snap.data()
        if (data.age == 16) {
            break;
        }
      }
  }
</code>```

Title: how to break querySnapshot on Firestore?

Body:
You can use the docs property of the QuerySnapshot, which returns an array of all the documents in the QuerySnapshot.

For example, with a for loop:

  return query.get()
    .then((snapshot) => {
      const snapshotsArray = snapshot.docs;
      for (var i = 0; i < snapshotsArray.length; i++) {
        const data = snapshotsArray[i].data()
        if (data.age == 16) {
            break;
        }
      }
  }

or with a for-of:

  return query.get()
    .then((snapshot) => {
      const snapshotsArray = snapshot.docs;
      for (const snap of snapshotsArray) {
        const data = snap.data()
        if (data.age == 16) {
            break;
        }
      }
  }


问:
PayPal IPN sandbox URL is currently down?
It seems that "https://sandbox.ipnpb.paypal.com/cgi-bin/webscr" is not responding? I'm trying to post sandbox IPN notifications to it to verify them. It was working fine yesterday, but today I'm getting an error:</p>

```<code>requests.exceptions.ConnectionError: HTTPSConnectionPool(host='sandbox.ipnpb.paypal.com', port=443): Max retries exceeded with url: /cgi-bin/webscr (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fe126046450>: Failed to establish a new connection: [Errno -2] Name or service not known'))
</code>```

答:
"Name or service not known" is a DNS problem; that host does not exist

You are probably looking for ipnpb.sandbox.paypal.com/cgi-bin/webscr , which is what is documented

Body:
It seems that "https://sandbox.ipnpb.paypal.com/cgi-bin/webscr" is not responding? I'm trying to post sandbox IPN notifications to it to verify them. It was working fine yesterday, but today I'm getting an error:

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='sandbox.ipnpb.paypal.com', port=443): Max retries exceeded with url: /cgi-bin/webscr (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fe126046450>: Failed to establish a new connection: [Errno -2] Name or service not known'))


问:
how to install tkinter using pip in windows 10
When i try to install tkinter with the command pip install tkinter in windows 10 I get this  error:

Could not find a version that satisfies the requirement tkinter(from versions: )
  No matching distributions found for tkinter

答: use pip install tkintertable it also imports Tkinter


问:
Open file in new browser tab by input file value
I want to open the file in a new browser tab for previewing.

```<code><input id="myinput" type="file" onchange="oninputfileselected(this);"/>
</code>```

function oninputfileselected(obj) {
  var inputfile = document.getElementById($(obj).attr('id'));
  console.log(inputfile.files);
}
```

The console output I get doesn't contain any local path for me to open a new tab. I am not sure if there is another way to do this? Thank you

答: The only approach I can think of would be to use FileReader to read the data in the file, then generate a data: scheme URL from it, then open that URL with window.open.

Body:
I want to open the file in a new browser tab for previewing.

<input id="myinput" type="file" onchange="oninputfileselected(this);"/>

function oninputfileselected(obj) {
  var inputfile = document.getElementById($(obj).attr('id'));
  console.log(inputfile.files);
}

The console output I get doesn't contain any local path for me to open a new tab. I am not sure if there is another way to do this? Thank you


问:
How to implement versioning for Token endpoint in Web API 2
I have a Asp.Net Web API 2 using Token based authentication (OAuth2).

I have implemented Web API versioning using aspnet-api-versioning.

So now I have three different versions of my API. It's really great, I can now change V3 without affecting the current API.

But the /token endpoint is not versioned because it is not in my controller. It's in the Providers.

I searched but couldn't find anything helpful.

答:
We can register more than one token endpoint in the Startup.Auth.cs

So here's what I did:

```<code>        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(TokenExpirationInDays),
            AllowInsecureHttp = true, //Allow HTTP to send username password.
        };
        app.UseOAuthBearerTokens(OAuthOptions);

        OAuthOptionsV3 = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/api/V3/Accounts/Token"),
            Provider = new ApplicationOAuthProvider2(PublicClientId),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(TokenExpirationInDays),
            AllowInsecureHttp = true, //Allow HTTP to send username password.
        };
        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptionsV3);
</code>```

So now I have different token endpoint for each version.

Body:
We can register more than one token endpoint in the Startup.Auth.cs

So here's what I did:

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(TokenExpirationInDays),
            AllowInsecureHttp = true, //Allow HTTP to send username password.
        };
        app.UseOAuthBearerTokens(OAuthOptions);

        OAuthOptionsV3 = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/api/V3/Accounts/Token"),
            Provider = new ApplicationOAuthProvider2(PublicClientId),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(TokenExpirationInDays),
            AllowInsecureHttp = true, //Allow HTTP to send username password.
        };
        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptionsV3);

So now I have different token endpoint for each version.


问:
jquery selector problem
I'm using this code:

```<code>$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':"52px"});
    $(switches).parent().css({'background-position': "147px -37px"});
}})
</code>```

But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?

Thanks for your help :)

EDIT:
here is the HTML

```<code><fieldset>
        <input checked="checked" />
        <label></label>
        <div class="toggle_box">
            <div class="switch" state="on"></div>
        </div>
    </fieldset>
    <fieldset>
        <input/>
        <label></label>
        <div class="toggle_box">
            <div class="switch"></div>
        </div>
    </fieldset>
</code>```

答: if($(this).attr('checked','checked')) would be your problem.  You're assigning checked to each checkbox instead of checking if it's checked.

Title: jquery selector problem

Body:
I'm using this code:

$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':"52px"});
    $(switches).parent().css({'background-position': "147px -37px"});
}})

But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?

Thanks for your help :)

EDIT:
here is the HTML

<fieldset>
        <input checked="checked" />

    </fieldset>
    <fieldset>
        <input/>

    </fieldset>


问:
How to convert timestamp date to java.util date(yyyy-mm-dd) in java
I am getting date from Oracle is in Timestamp but I need to convert it in to this format 2020-02-17 (yyyy-mm-dd) format, but currently in postman I am receiving date as "2020-02-17T09:40:37.850+0000" in this format.

Any help on this would be really appreciated

答:
```<code> private String  getZonedDateTime(String startTime){
  // input -> startTime: 2020-02-17T09:40:37.850+0000
  // output -> 2020-02-17
  return ZonedDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"))
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
 }
</code>```

Just pass the Date String which you have and get it in what format you want.

Body:
 private String  getZonedDateTime(String startTime){
  // input -> startTime: 2020-02-17T09:40:37.850+0000
  // output -> 2020-02-17
  return ZonedDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"))
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
 }

Just pass the Date String which you have and get it in what format you want.


问:
Reagent configuration for multi-page applications
My project.clj has,

```<code>  :cljsbuild {:builds
              {:app
               {:source-paths ["src/cljs" "src/cljc"]
                :compiler {:output-to "target/cljsbuild/public/js/app.js"
                           :output-dir "target/cljsbuild/public/js/out"
                           :main "my.core"
                           :asset-path "/js/out"
                           :optimizations :none
                           :source-map true
                           :pretty-print true}}}}
</code>```

and I include app.js in my list.html, using Selmer, like so,

```<code>{% block page-scripts %}
{% script "/js/app.js" %}
{% endblock %}
</code>```

at the end of my list.cljs, I have

```<code>(r/render [list] (.getElementById js/document "content"))
</code>```

so far so good.

Now, I would like to have another page, say detail.cljs, that I also like to render similarly,

```<code>(r/render [detail] (.getElementById js/document "content"))
</code>```

The problem is, I just have a single app.js and including that in detail.html will render list content there too. Btw, I want one url for list page, and another for detail.

Question:

How should I go about it?

答:
ClojureScript development for the past 2 years is much easier to do using the Deps/CLI facility along with Figwheel Main (a.k.a Figwheel 2.0) rather than the older Leiningen method.  Just look at the page Create a Build at figwheel.org, and then create multiple *.cljs.edn files such as:

```<code>some-page.cljs.edn
another-page.cljs.edn
...
</code>```

Each of these can be as simple as:

```<code>{:main some-page.core}
</code>```

and compile via:

```<code>clojure -m figwheel.main --build-once some-page
</code>```

which will produce an output file

```<code>target/public/cljs-out/some-page-main.js
</code>```

Be sure to see Code Splitting documentation for Figwheel, and Code Splitting on clojurescript.org. Of course, be sure to go through all of the Tutorial and Documentation from the start.  Enjoy!

For shadow-cljs, there is Code Splitting ClojureScript example app and a blog entry.

Note: You could also look at the Extra Mains feature, but this is more limited.

Body:
My project.clj has,

  :cljsbuild {:builds
              {:app
               {:source-paths ["src/cljs" "src/cljc"]
                :compiler {:output-to "target/cljsbuild/public/js/app.js"
                           :output-dir "target/cljsbuild/public/js/out"
                           :main "my.core"
                           :asset-path "/js/out"
                           :optimizations :none
                           :source-map true
                           :pretty-print true}}}}

and I include app.js in my list.html, using Selmer, like so,

{% block page-scripts %}
{% script "/js/app.js" %}
{% endblock %}

at the end of my list.cljs, I have

(r/render [list] (.getElementById js/document "content"))

so far so good.

Now, I would like to have another page, say detail.cljs, that I also like to render similarly,

(r/render [detail] (.getElementById js/document "content"))

The problem is, I just have a single app.js and including that in detail.html will render list content there too. Btw, I want one url for list page, and another for detail.

Question:

How should I go about it?

Body:
ClojureScript development for the past 2 years is much easier to do using the Deps/CLI facility along with Figwheel Main (a.k.a Figwheel 2.0) rather than the older Leiningen method.  Just look at the page Create a Build at figwheel.org, and then create multiple *.cljs.edn files such as:

some-page.cljs.edn
another-page.cljs.edn
...

Each of these can be as simple as:

{:main some-page.core}

and compile via:

clojure -m figwheel.main --build-once some-page

which will produce an output file

target/public/cljs-out/some-page-main.js

Be sure to see Code Splitting documentation for Figwheel, and Code Splitting on clojurescript.org. Of course, be sure to go through all of the Tutorial and Documentation from the start.  Enjoy!

For shadow-cljs, there is Code Splitting ClojureScript example app and a blog entry.

Note: You could also look at the Extra Mains feature, but this is more limited.