问:
How to pass two different objects to a POST request in postman to test RESTful API?
This is actually a two part question, one is, how to pass two JSON objects, anther one is how to create object from two different classand pass that object to a POST method.

I am trying to test a POST method of RESTful API by passing two different objects in postman. I could successfully test only a POST method with one object, but when I am trying to send two different object to POST method where two different objects  , postman say's bad request.

Here is my two entity class: First one is Cleint class:

```<code>import lombok.Data;
import org.zevgma.api.entities.user.User;

import javax.persistence.*;
import java.util.Date;

@Data
@Entity
@Table(name = "client")
public class Client {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_pk_generator")
    @SequenceGenerator(name = "user_pk_generator", sequenceName = "users_user_id_seq", allocationSize = 1)
    @Column(name = "id", unique = true, nullable = false,  columnDefinition = "serial")
    private int id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(nullable = false)
    private String email;

    @Column(nullable = false)
    private Date userDateCreate;

 }
</code>```

Second one is about ClientAddress:

```<code>import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Data
@Entity
public class ClientAddress {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private int streetID;
    private String streetName;
    private int streetNumber;
}
</code>```

I have tried different POST request with JSON objets or JSON nested threads in Stackoverflow and youtube, but could not find my solution.
Spceially I have tried instructions from these threads:

https://it.mathworks.com/help/thingspeak/bulkwritejsondata.html

Post Multiple JSON Objects Simultaneously with Express and Postman

Here is the POST method of RESTful API which one I want to test:

```<code>@PostMapping(value = "/api/employees", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> createClient(@RequestBody Client client,
                                           @RequestBody ClientAddress clientAddress){
    clientService.save(client);
    clientAddressService.save(clientAddress);
    return new ResponseEntity<>(client.getName() + " and "+ clientAddress.getStreetName() + " successfully added",
            HttpStatus.OK);
}
</code>```

So far I have tried with this JSON object:

[
{
     "name": "Bilbo",
      "email": "bilbo@gmail.com"
    },

  {
     "streetName": "Central Street",
     "streetNumber": "31"
   }
]```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>[
 {
  "client":{
               "name": "Bilbo",
                "email": "bilbo@gmail.com"
              },

  "clientAddress":{
                      "streetName": "Central Street",
                      "streetNumber": "31"
                     }
   }
]</code>```

By Pre-Request Script:

 //Pre-request Script
 var client = {
     "name": "Bilbo",
     "email": "bilbo@mail.com"
 }

var address = {
    "streetName": "New Street",
    "streetNumber": "3"
}

pm.environment.set("client", JSON.stringify(client));
pm.environment.set("address", JSON.stringify(address));

//Body
[
{{client}},{{address}}
]```
</div>
</div>
</p>

<p>Now the second part of questions: What if I want to create a new object, ClientData from the above two mentioned class, Client and ClientAddress and pass this ClientData object to a POST method, how to do it.</p>

<p>Here is the ClientData class:</p>

<p>import lombok.Data;</p>

```@Data
public class ClientData {

    private Client client;
    private ClientAddress address;
}
```

<p>And here is the POST method where I want to pass a ClientData object:</p>

```  @PostMapping(value = "/api/employees", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> createClient(@RequestBody ClientData clientData){
               Client client = clientData.getClient();
                clientService.save(client);
            ClientAddress clientAddress = clientData.getAddress();
            clientAddressService.save(clientAddress);

        return new ResponseEntity<>(client.getName() + " and "+ clientAddress.getStreetName() + " successfully added",
                HttpStatus.OK);
    }
```

To test method in postman I should create these complex ClientData JSON object and how to pass the it?

答:
Your ClientData class is

```<code>@Data
public class ClientData {

    private Client client;
    private ClientAddress address;
}
</code>```

So you request payload should look like

```<code>    {
        "client":{
               "name": "Bilbo",
                "email": "bilbo@gmail.com"
              },

        "address":{
                      "streetName": "Central Street",
                      "streetNumber": "31"
                     }
      }
</code>```

Notice address instead of clientAddress.
Also you don't need to pass it as array it will be just a json object (not [])

Body:
This is actually a two part question, one is, how to pass two JSON objects, anther one is how to create object from two different classand pass that object to a POST method.

I am trying to test a POST method of RESTful API by passing two different objects in postman. I could successfully test only a POST method with one object, but when I am trying to send two different object to POST method where two different objects  , postman say's bad request.

Here is my two entity class: First one is Cleint class:

import lombok.Data;
import org.zevgma.api.entities.user.User;

import javax.persistence.*;
import java.util.Date;

@Data
@Entity
@Table(name = "client")
public class Client {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_pk_generator")
    @SequenceGenerator(name = "user_pk_generator", sequenceName = "users_user_id_seq", allocationSize = 1)
    @Column(name = "id", unique = true, nullable = false,  columnDefinition = "serial")
    private int id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(nullable = false)
    private String email;

    @Column(nullable = false)
    private Date userDateCreate;

 }

Second one is about ClientAddress:

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Data
@Entity
public class ClientAddress {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private int streetID;
    private String streetName;
    private int streetNumber;
}

I have tried different POST request with JSON objets or JSON nested threads in Stackoverflow and youtube, but could not find my solution.
Spceially I have tried instructions from these threads:

https://it.mathworks.com/help/thingspeak/bulkwritejsondata.html

Post Multiple JSON Objects Simultaneously with Express and Postman

Here is the POST method of RESTful API which one I want to test:

@PostMapping(value = "/api/employees", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> createClient(@RequestBody Client client,
                                           @RequestBody ClientAddress clientAddress){
    clientService.save(client);
    clientAddressService.save(clientAddress);
    return new ResponseEntity<>(client.getName() + " and "+ clientAddress.getStreetName() + " successfully added",
            HttpStatus.OK);
}

So far I have tried with this JSON object:

[
{
     "name": "Bilbo",
      "email": "bilbo@gmail.com"
    },

  {
     "streetName": "Central Street",
     "streetNumber": "31"
   }
]

[
 {
  "client":{
               "name": "Bilbo",
                "email": "bilbo@gmail.com"
              },

  "clientAddress":{
                      "streetName": "Central Street",
                      "streetNumber": "31"
                     }
   }
]

By Pre-Request Script:

 //Pre-request Script
 var client = {
     "name": "Bilbo",
     "email": "bilbo@mail.com"
 }

var address = {
    "streetName": "New Street",
    "streetNumber": "3"
}

pm.environment.set("client", JSON.stringify(client));
pm.environment.set("address", JSON.stringify(address));

//Body
[
{{client}},{{address}}
]

Now the second part of questions: What if I want to create a new object, ClientData from the above two mentioned class, Client and ClientAddress and pass this ClientData object to a POST method, how to do it.

Here is the ClientData class:

import lombok.Data;

@Data
public class ClientData {

    private Client client;
    private ClientAddress address;
}

And here is the POST method where I want to pass a ClientData object:

  @PostMapping(value = "/api/employees", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> createClient(@RequestBody ClientData clientData){
               Client client = clientData.getClient();
                clientService.save(client);
            ClientAddress clientAddress = clientData.getAddress();
            clientAddressService.save(clientAddress);

        return new ResponseEntity<>(client.getName() + " and "+ clientAddress.getStreetName() + " successfully added",
                HttpStatus.OK);
    }

To test method in postman I should create these complex ClientData JSON object and how to pass the it?

Body:
Your ClientData class is

@Data
public class ClientData {

    private Client client;
    private ClientAddress address;
}

So you request payload should look like

    {
        "client":{
               "name": "Bilbo",
                "email": "bilbo@gmail.com"
              },

        "address":{
                      "streetName": "Central Street",
                      "streetNumber": "31"
                     }
      }

Notice address instead of clientAddress.
Also you don't need to pass it as array it will be just a json object (not [])


来源: stackexchange

问:
Create reversible YAML from JSON in python
While trying to create YAML from a JSON in python, using the PyYAML  library, I am able to convert the JSON into YAML. However, in the YAML I receive as a result, all the brackets of JSON are unfolded whereas I want to retain few square brackets (lists) from JSON to converted YAML. How can I request this library call to not unfold lists from JSON into YAML, but rather retain it as a list?

A snapshot of my issue follows:

```<code>import yaml
import json

original_json = {'a': {'next': ['b'], 'prev': []},
 'b': {'next': ['c'], 'prev': ['a']},
 'c': {'next': ['d', 'e'], 'prev': ['b']},
 'd': {'next': [], 'prev': ['c']},
 'e': {'next': ['f'], 'prev': ['c']},
 'f': {'next': [], 'prev': ['e']}}

obtained_yaml = yaml.dump(yaml.load(json.dumps(original_json)), default_flow_style=False)

# obtained_yaml looks like
#
# a:
#   next:
#   - b
#   prev: []
# b:
#   next:
#   - c
#   prev:
#   - a
# c:
#   next:
#   - d
#   - e
#   prev:
#   - b
# d:
#   next: []
#   prev:
#   - c
# e:
#   next:
#   - f
#   prev:
#   - c
# f:
#   next: []
#   prev:
#   - e

# expected yaml should look like
#
# a:
#   next:
#   - ["b"]
#   prev: []
# b:
#   next:
#   - ["c"]
#   prev:
#   - ["a"]
# c:
#   next:
#   - ["d"]
#   - ["e"]
#   prev:
#   - ["b"]
# d:
#   next: []
#   prev:
#   - ["c"]
# e:
#   next:
#   - ["f"]
#   prev:
#   - ["c"]
# f:
#   next: []
#   prev:
#   - ["e"]
</code>```

I tried few ways to solve this out but all that did not work in the way expected json should come out. Need suggestions on how to get it done.

答:
Only YAML 1.2 is a superset of JSON, YAML 1.1 is not and although YAML 1.2 was released in
2009, unfortunately PyYAML has not been updated since then. Your example
is a JSON subset that is compatible with YAML 1.1, but in general it is not a good idea
to try and use PyYAML for this.

There are other native libraries for Python, another one is
ruamel.yaml (disclaimer: I am the author of that package) and that
implements YAML 1.2 and gives you full control over block vs flow
style dumping of individual collections. Of course you still have
the general YAML restriction that you cannot have a block style
collection within a flow style collection).

PyYAML, and ruamel.yaml in non-round-trip-mode, only allow you to have all block, or all flow, or all block with leaf-nodes in flow style. But the default, round-trip-mode, allows finer grained control using the .fa attribute on collections:

```<code>import sys
import json
import ruamel.yaml

original_json = {'a': {'next': ['b'], 'prev': []},
 'b': {'next': ['c'], 'prev': ['a']},
 'c': {'next': ['d', 'e'], 'prev': ['b']},
 'd': {'next': [], 'prev': ['c']},
 'e': {'next': ['f'], 'prev': ['c']},
 'f': {'next': [], 'prev': ['e']}}

json_string = json.dumps(original_json)

yaml = ruamel.yaml.YAML()
# yaml.indent(mapping=4, sequence=4, offset=2)
# yaml.preserve_quotes = True
data = yaml.load(json_string)

# the following sets flow-style for the root level mapping only
data.fa.set_block_style()
yaml.dump(data, sys.stdout)
</code>```

which gives:

```<code>a: {next: [b], prev: []}
b: {next: [c], prev: [a]}
c: {next: [d, e], prev: [b]}
d: {next: [], prev: [c]}
e: {next: [f], prev: [c]}
f: {next: [], prev: [e]}
</code>```

you can of course recursively traverse your data structure and call .fa.set_block_style() depending on any criteria you want.

ContentLicense: CC BY-SA 4.0

Body:
While trying to create YAML from a JSON in python, using the PyYAML  library, I am able to convert the JSON into YAML. However, in the YAML I receive as a result, all the brackets of JSON are unfolded whereas I want to retain few square brackets (lists) from JSON to converted YAML. How can I request this library call to not unfold lists from JSON into YAML, but rather retain it as a list?

A snapshot of my issue follows:

import yaml
import json

original_json = {'a': {'next': ['b'], 'prev': []},
 'b': {'next': ['c'], 'prev': ['a']},
 'c': {'next': ['d', 'e'], 'prev': ['b']},
 'd': {'next': [], 'prev': ['c']},
 'e': {'next': ['f'], 'prev': ['c']},
 'f': {'next': [], 'prev': ['e']}}

obtained_yaml = yaml.dump(yaml.load(json.dumps(original_json)), default_flow_style=False)

# obtained_yaml looks like
#
# a:
#   next:
#   - b
#   prev: []
# b:
#   next:
#   - c
#   prev:
#   - a
# c:
#   next:
#   - d
#   - e
#   prev:
#   - b
# d:
#   next: []
#   prev:
#   - c
# e:
#   next:
#   - f
#   prev:
#   - c
# f:
#   next: []
#   prev:
#   - e

# expected yaml should look like
#
# a:
#   next:
#   - ["b"]
#   prev: []
# b:
#   next:
#   - ["c"]
#   prev:
#   - ["a"]
# c:
#   next:
#   - ["d"]
#   - ["e"]
#   prev:
#   - ["b"]
# d:
#   next: []
#   prev:
#   - ["c"]
# e:
#   next:
#   - ["f"]
#   prev:
#   - ["c"]
# f:
#   next: []
#   prev:
#   - ["e"]

I tried few ways to solve this out but all that did not work in the way expected json should come out. Need suggestions on how to get it done.

Body:
Only YAML 1.2 is a superset of JSON, YAML 1.1 is not and although YAML 1.2 was released in
2009, unfortunately PyYAML has not been updated since then. Your example
is a JSON subset that is compatible with YAML 1.1, but in general it is not a good idea
to try and use PyYAML for this.

There are other native libraries for Python, another one is
ruamel.yaml (disclaimer: I am the author of that package) and that
implements YAML 1.2 and gives you full control over block vs flow
style dumping of individual collections. Of course you still have
the general YAML restriction that you cannot have a block style
collection within a flow style collection).

PyYAML, and ruamel.yaml in non-round-trip-mode, only allow you to have all block, or all flow, or all block with leaf-nodes in flow style. But the default, round-trip-mode, allows finer grained control using the .fa attribute on collections:

import sys
import json
import ruamel.yaml

original_json = {'a': {'next': ['b'], 'prev': []},
 'b': {'next': ['c'], 'prev': ['a']},
 'c': {'next': ['d', 'e'], 'prev': ['b']},
 'd': {'next': [], 'prev': ['c']},
 'e': {'next': ['f'], 'prev': ['c']},
 'f': {'next': [], 'prev': ['e']}}

json_string = json.dumps(original_json)

yaml = ruamel.yaml.YAML()
# yaml.indent(mapping=4, sequence=4, offset=2)
# yaml.preserve_quotes = True
data = yaml.load(json_string)

# the following sets flow-style for the root level mapping only
data.fa.set_block_style()
yaml.dump(data, sys.stdout)

which gives:

a: {next: [b], prev: []}
b: {next: [c], prev: [a]}
c: {next: [d, e], prev: [b]}
d: {next: [], prev: [c]}
e: {next: [f], prev: [c]}
f: {next: [], prev: [e]}

you can of course recursively traverse your data structure and call .fa.set_block_style() depending on any criteria you want.


问:
Compare objects and search in list
I use Python 3 and PySide2 (Qt for Python) (both up to date). I have a list of PySide2 objects and have to check if an item exists in the list. If I try to do this, I get the error:

NotImplementedError: operator not implemented.
```

<pre class="lang-py prettyprint-override"><code>from PySide2 import QtGui
item = QtGui.QStandardItem()
item1 = QtGui.QStandardItem()

item == item1 # creates error

list1 = [item, item1]
item1 in list1 # creats error
</code>```

What do I wrong? How can I do this? Do I have to implement the "==" operator myself?
Thank you in advance for your help!

答:
The operator == is equivalent with __eq__. The usage is like a.__eq__(b) or a == b. And the exception is saying the class has no implementation of that method.

And the doc does say:

Reimplement operator if you want to control the semantics of item comparison. operator determines the sorted order when sorting items with sortChildren() or with sort().

Title: Compare objects and search in list

Body:
I use Python 3 and PySide2 (Qt for Python) (both up to date). I have a list of PySide2 objects and have to check if an item exists in the list. If I try to do this, I get the error:

NotImplementedError: operator not implemented.

from PySide2 import QtGui
item = QtGui.QStandardItem()
item1 = QtGui.QStandardItem()

item == item1 # creates error

list1 = [item, item1]
item1 in list1 # creats error

What do I wrong? How can I do this? Do I have to implement the "==" operator myself?
Thank you in advance for your help!


问:
Gallery software for a website that will resize based on height, with a click on image to navigate
I was looking at this gallery:
http://www.orangegirlphotographs.com/portfolio.cfm?galleryID=4

And just loved the way it looked, anyone have any idea how to get a similar effect using ideally CSS/JS and if not then using flash? Furthermore it would be excellent if you could move to the next slide by clicking on the image itself.

I'm also wondering how she is able to maintain height of the images when resizing (unless she is doing it manually which I doubt now days).

I normally use Gallery3 for my image uploading, automatic resizing with AnotherSlider to get a sliding effect but I would really appreciate it if you guys could direct me to something like this?

答:
jQuery's probably your best bet here. I've used the Cycle plugin with slideshows before: http://jquery.malsup.com/cycle/

Look at the examples and you'll get an idea of what it can do: http://jquery.malsup.com/cycle/more.html?v2.23

For the height, either all the images have the same height, or simply setting it in html will keep the ratio. It's better to have them all the same height and resize them in something like Photoshop as the results will be smoother

ContentLicense: CC BY-SA 3.0


问:
How can I put something in the prompt and get the output inside of a node program?
I'm trying to use the World Time API in my program. However, to use that I need to write "curl http://worldtimeapi.org/api/timezone/:area/:location[/:region]" in the prompt and receive a output. How can I write and get the output?

I tried do something with console.log but without success.

答:
If you want to test your API without writing an actual program that calls it,
Postman is the best app to use. Watch quick tutorials on youtube on how to use it. Its not that complicated.</p>


问:
Insert rows corresponding to each month in an yearly data
I have a dataframe with yearly data from 2014 to 2018. I wish to expand this dataframe into monthly values and basically divide each variable's value by 12 as each month's value.
Please note: There is no month column in my dataframe as of now.
So, if there are 5 products, I have 5*5 rows and 5 columns :"year", "Product_ID", "Var1", "Var2" and "Var3" as the columns.

Eventually, I want 5*12 rows and 6 column with "month" inserted as well.

I have tried this code but it isnt working:

```<code>df_new$date <- NA
df_new <- complete(df,Product_ID, date = full_seq(2014,1))
</code>```

Any suggestions?

答:
One option is to use uncount to repeat rows 12 times, create a new column month to take 1:12 value for each year and then divide Var columns by 12.

```<code>library(dplyr)
library(tidyr)

df %>%
  uncount(12) %>%
  group_by(year) %>%
  mutate(month = 1:12) %>%
  mutate_at(vars(Var1, Var2), ~./12)

# Groups:   year [3]
#    year Product_ID  Var1  Var2 month
#   <int> <chr>      <dbl> <dbl> <int>
# 1  2013 A          0.833     5     1
# 2  2013 A          0.833     5     2
# 3  2013 A          0.833     5     3
# 4  2013 A          0.833     5     4
# 5  2013 A          0.833     5     5
# 6  2013 A          0.833     5     6
# 7  2013 A          0.833     5     7
# 8  2013 A          0.833     5     8
# 9  2013 A          0.833     5     9
#10  2013 A          0.833     5    10
# … with 26 more rows
</code>```

Or another option with complete and fill

```<code>df %>%
  mutate(month = 1) %>%
  complete(year, month = 1:12) %>%
  fill(Product_ID, Var1, Var2) %>%
  mutate_at(vars(Var1, Var2), ~./12)
</code>```

data

```<code>df <- data.frame(year = 2013:2015, Product_ID = c("A", "B", "C"),
      Var1 = c(10, 20, 30), Var2 = c(60, 80, 120), stringsAsFactors = FALSE)
</code>```

Body:
I have a dataframe with yearly data from 2014 to 2018. I wish to expand this dataframe into monthly values and basically divide each variable's value by 12 as each month's value.
Please note: There is no month column in my dataframe as of now.
So, if there are 5 products, I have 5*5 rows and 5 columns :"year", "Product_ID", "Var1", "Var2" and "Var3" as the columns.

Eventually, I want 5*12 rows and 6 column with "month" inserted as well.

I have tried this code but it isnt working:

df_new$date <- NA
df_new <- complete(df,Product_ID, date = full_seq(2014,1))

Any suggestions?

Body:
One option is to use uncount to repeat rows 12 times, create a new column month to take 1:12 value for each year and then divide Var columns by 12.

library(dplyr)
library(tidyr)

df %>%
  uncount(12) %>%
  group_by(year) %>%
  mutate(month = 1:12) %>%
  mutate_at(vars(Var1, Var2), ~./12)

# Groups:   year [3]
#    year Product_ID  Var1  Var2 month
#   <int> <chr>      <dbl> <dbl> <int>
# 1  2013 A          0.833     5     1
# 2  2013 A          0.833     5     2
# 3  2013 A          0.833     5     3
# 4  2013 A          0.833     5     4
# 5  2013 A          0.833     5     5
# 6  2013 A          0.833     5     6
# 7  2013 A          0.833     5     7
# 8  2013 A          0.833     5     8
# 9  2013 A          0.833     5     9
#10  2013 A          0.833     5    10
# … with 26 more rows

Or another option with complete and fill

df %>%
  mutate(month = 1) %>%
  complete(year, month = 1:12) %>%
  fill(Product_ID, Var1, Var2) %>%
  mutate_at(vars(Var1, Var2), ~./12)

data

df <- data.frame(year = 2013:2015, Product_ID = c("A", "B", "C"),
      Var1 = c(10, 20, 30), Var2 = c(60, 80, 120), stringsAsFactors = FALSE)


问:
How to use ImageField and descriptionField in ng2-completor in angular 4+?
I am developing project in angular 6 and I am using ng2-completor in my search Box. I have used completerService.local that contains list of string.

```<code><div><ng2-completer [datasource]="countryLists" id="global_search"
    [openOnFocus]="true"
    [minSearchLength]="1" [clearSelected]="true"
    [clearUnselected]="true" [openOnFocus]='false' (click)="onFocus()"
    placeholder="{{ 'Search '}}"
    [fillHighlighted]="false" (selected)="searchMyCountry($event)"></ng2-completer>
</div>
</code>```

Now, I want to add an image and description like they have given in their demo link

Demo Link

But I am unable to find how to use this.

How do I do this?

答:
Hello use below example:HTML

```<code><form class="example-form">
<mat-form-field class="example-full-width">
<input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
<img style="vertical-align:middle;" aria-hidden src="{{state.flag}}" height="25" />
<span>{{ state.name }}</span> |
<small>Population: {{state.population}}</small>
</mat-option>
</mat-autocomplete>
</mat-form-field>
<br />
<mat-slide-toggle
[checked]="stateCtrl.disabled"
(change)="stateCtrl.disabled ? stateCtrl.enable() : stateCtrl.disable()">
Disable Input?
</mat-slide-toggle>
</form>

</code>```

And TS

```<code>import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
export class State {
constructor(public name: string, public population: string, public flag: string) { }
}
/**
* @title Autocomplete overview
*/
@Component({
selector: 'autocomplete-overview-example',
templateUrl: 'autocomplete-overview-example.html',
styleUrls: ['autocomplete-overview-example.css']
})
export class AutocompleteOverviewExample {
stateCtrl: FormControl;
filteredStates: Observable<any[]>;
states: State[] = [
{
name: 'Arkansas',
population: '2.978M',
// https://commons.wikimedia.org/wiki/File:Flag_of_Arkansas.svg
flag: 'https://upload.wikimedia.org/wikipedia/commons/9/9d/Flag_of_Arkansas.svg'
},
{
name: 'California',
population: '39.14M',
// https://commons.wikimedia.org/wiki/File:Flag_of_California.svg
flag: 'https://upload.wikimedia.org/wikipedia/commons/0/01/Flag_of_California.svg'
},
{
name: 'Florida',
population: '20.27M',
// https://commons.wikimedia.org/wiki/File:Flag_of_Florida.svg
flag: 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Flag_of_Florida.svg'
},
{
name: 'Texas',
population: '27.47M',
// https://commons.wikimedia.org/wiki/File:Flag_of_Texas.svg
flag: 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Flag_of_Texas.svg'
}
];
constructor() {
this.stateCtrl = new FormControl();
this.filteredStates = this.stateCtrl.valueChanges
.pipe(
startWith(''),
map(state => state ? this.filterStates(state) : this.states.slice())
);
}
filterStates(name: string) {
return this.states.filter(state =>
state.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
}

</code>```

Body:
I am developing project in angular 6 and I am using ng2-completor in my search Box. I have used completerService.local that contains list of string.

<ng2-completer [datasource]="countryLists" id="global_search"
    [openOnFocus]="true"
    [minSearchLength]="1" [clearSelected]="true"
    [clearUnselected]="true" [openOnFocus]='false' (click)="onFocus()"
    placeholder="{{ 'Search '}}"
    [fillHighlighted]="false" (selected)="searchMyCountry($event)"></ng2-completer>

Now, I want to add an image and description like they have given in their demo link

Demo Link

But I am unable to find how to use this.

How do I do this?

Body:
Hello use below example:HTML

<form class="example-form">
<mat-form-field class="example-full-width">
<input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
<img style="vertical-align:middle;" aria-hidden src="{{state.flag}}" height="25" />
<span>{{ state.name }}</span> |
<small>Population: {{state.population}}</small>
</mat-option>
</mat-autocomplete>
</mat-form-field>
<br />
<mat-slide-toggle
[checked]="stateCtrl.disabled"
(change)="stateCtrl.disabled ? stateCtrl.enable() : stateCtrl.disable()">
Disable Input?
</mat-slide-toggle>
</form>

And TS

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
export class State {
constructor(public name: string, public population: string, public flag: string) { }
}
/**
* @title Autocomplete overview
*/
@Component({
selector: 'autocomplete-overview-example',
templateUrl: 'autocomplete-overview-example.html',
styleUrls: ['autocomplete-overview-example.css']
})
export class AutocompleteOverviewExample {
stateCtrl: FormControl;
filteredStates: Observable<any[]>;
states: State[] = [
{
name: 'Arkansas',
population: '2.978M',
// https://commons.wikimedia.org/wiki/File:Flag_of_Arkansas.svg
flag: 'https://upload.wikimedia.org/wikipedia/commons/9/9d/Flag_of_Arkansas.svg'
},
{
name: 'California',
population: '39.14M',
// https://commons.wikimedia.org/wiki/File:Flag_of_California.svg
flag: 'https://upload.wikimedia.org/wikipedia/commons/0/01/Flag_of_California.svg'
},
{
name: 'Florida',
population: '20.27M',
// https://commons.wikimedia.org/wiki/File:Flag_of_Florida.svg
flag: 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Flag_of_Florida.svg'
},
{
name: 'Texas',
population: '27.47M',
// https://commons.wikimedia.org/wiki/File:Flag_of_Texas.svg
flag: 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Flag_of_Texas.svg'
}
];
constructor() {
this.stateCtrl = new FormControl();
this.filteredStates = this.stateCtrl.valueChanges
.pipe(
startWith(''),
map(state => state ? this.filterStates(state) : this.states.slice())
);
}
filterStates(name: string) {
return this.states.filter(state =>
state.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
}


问:
How to check if slice of custom struct is sorted?
We can check if a slice of strings is sorted with

```<code>var slice = []string { "a", "b }

sort.StringsAreSorted(slice)
</code>```

But what about when you have struct and you want to know if a slice of that struct is sorted by a certain member?

```<code>type Person struct {
  Name string
  LastName string
}

var p = []Person{ {"John", "Smith" }, { "Ben", "Smith" } }

sort.StringsAreSorted(p???)
</code>```

答:
If your type implements sort.Interface, simply use the sort.IsSorted() function.

If not, you may use sort.SliceIsSorted(), passing a less() function which decides / specifies the order(ing):

```<code>sortedByName := sort.SliceIsSorted(p, func(i, j int) bool {
    return p[i].Name < p[j].Name
})
fmt.Println("Sorted by name:", sortedByName)

sortedByLastName := sort.SliceIsSorted(p, func(i, j int) bool {
    return p[i].LastName < p[j].LastName
})
fmt.Println("Sorted by last name:", sortedByLastName)
</code>```

This will output (try it on the Go Playground):

```<code>Sorted by name: false
Sorted by last name: true
</code>```

If you look into the implementation of these functions, they use a simple loop to iterate over the elements and tell if the ones being next to each other does not violate the ordering (less() function). You may just as easily use a for loop too.

Body:
We can check if a slice of strings is sorted with

var slice = []string { "a", "b }

sort.StringsAreSorted(slice)

But what about when you have struct and you want to know if a slice of that struct is sorted by a certain member?

type Person struct {
  Name string
  LastName string
}

var p = []Person{ {"John", "Smith" }, { "Ben", "Smith" } }

sort.StringsAreSorted(p???)

Body:
If your type implements sort.Interface, simply use the sort.IsSorted() function.

If not, you may use sort.SliceIsSorted(), passing a less() function which decides / specifies the order(ing):

sortedByName := sort.SliceIsSorted(p, func(i, j int) bool {
    return p[i].Name < p[j].Name
})
fmt.Println("Sorted by name:", sortedByName)

sortedByLastName := sort.SliceIsSorted(p, func(i, j int) bool {
    return p[i].LastName < p[j].LastName
})
fmt.Println("Sorted by last name:", sortedByLastName)

This will output (try it on the Go Playground):

Sorted by name: false
Sorted by last name: true

If you look into the implementation of these functions, they use a simple loop to iterate over the elements and tell if the ones being next to each other does not violate the ordering (less() function). You may just as easily use a for loop too.


问:
Limit number of web service calls within timeframe
I have an asmx web service which takes a few simple types as input, calls an oracle stored procedure from which it gets a response and then passes this response back to the caller.

I would like to take the inputs to the service and assuming that they are valid and the required operation is completed successfully, I'd like to store the inputs somehow (in an efficient way, so not hitting a database for example) for an agreed timespan, then refuse any attempts to call the service with the same data until after that timespan has expired. I hope that's clear.

So by way of pseudo code...

```<code>[WebMethod]
public Response DoThings(int someInt, string someString, DateTime someDateTime)
{
  if(!Stored(someInt, someString, someDateTime))
    {
       var response = new OracleRepository().CallStoredProcedure(someInt, someString, someDateTime);
       StoreInputs(someInt, someString, someDateTime);

       return response;
    }
  else return Response.TryLater;

}

private void StoreInputs(int someInt, string someString, DateTime, someDateTime)
  {
     Store(int someInt, string someString, DateTime, someDateTime);
  }

private bool Stored(int someInt, string someString, DateTime, someDateTime)
  {
     //some code to find out if the data is stored
  }
</code>```

I'm not a complete beginner, but I am quite new to C#, so not quite sure where to start. Any help would be greatly appreciated.

Thanks.

答:
using HttpContext.Current.Cache you should be able to cache the result of your stored procedure call and then on the next request query it for data and if found return that data instead of doing a new stored procedure call.

the .Add method on the cache class has parameters for data max age see: http://msdn.microsoft.com/en-us/library/system.web.caching.cache.add.aspx

Body:
I have an asmx web service which takes a few simple types as input, calls an oracle stored procedure from which it gets a response and then passes this response back to the caller.

I would like to take the inputs to the service and assuming that they are valid and the required operation is completed successfully, I'd like to store the inputs somehow (in an efficient way, so not hitting a database for example) for an agreed timespan, then refuse any attempts to call the service with the same data until after that timespan has expired. I hope that's clear.

So by way of pseudo code...

[WebMethod]
public Response DoThings(int someInt, string someString, DateTime someDateTime)
{
  if(!Stored(someInt, someString, someDateTime))
    {
       var response = new OracleRepository().CallStoredProcedure(someInt, someString, someDateTime);
       StoreInputs(someInt, someString, someDateTime);

       return response;
    }
  else return Response.TryLater;

}

private void StoreInputs(int someInt, string someString, DateTime, someDateTime)
  {
     Store(int someInt, string someString, DateTime, someDateTime);
  }

private bool Stored(int someInt, string someString, DateTime, someDateTime)
  {
     //some code to find out if the data is stored
  }

I'm not a complete beginner, but I am quite new to C#, so not quite sure where to start. Any help would be greatly appreciated.

Thanks.


问:
How to pass Bean shell processor variable in to HTTP Request body data in jmeter
I need to pass the Date format variable data from Bean shell processor to http request body

Below is my code and json where I passed variable data but it is not working

```<code>import java.text.SimpleDateFormat;
import java.util.Date;

Date enrolmentDate = new Date();
enrolmentDate.setDate(enrolmentDate.getDate());//+ ${__Random(1,50,)});
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String formattedDate = df.format(enrolmentDate);
vars.put("StartDate",formattedDate);
log.info("########################"+formattedDate);
</code>```

Below is the Http Request Body data

```<code>{
"articleId":""${ArticleId}",
"startDate":"${formattedDate}",
"endDate":"${Carttodates}"
}
</code>```

When i run it Start date and end date is shown as ${formattedDate}, what will be the solution?

and in my JSON body data i want to send Start and End Date like "27/05/2019 14:34 "

Below is the Request I got

```<code>PUT data:
{
"articleId":"7694b207-936b-40b9-9c80-4b8097e67da1",
"startDate":"${formattedDate}",
"endDate":"${Carttodates}"
}
</code>```

答:
You need to put formattedDate as the variable name also:

```<code>vars.put("formattedDate", formattedDate);
</code>```

Body:
I need to pass the Date format variable data from Bean shell processor to http request body

Below is my code and json where I passed variable data but it is not working

import java.text.SimpleDateFormat;
import java.util.Date;

Date enrolmentDate = new Date();
enrolmentDate.setDate(enrolmentDate.getDate());//+ ${__Random(1,50,)});
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String formattedDate = df.format(enrolmentDate);
vars.put("StartDate",formattedDate);
log.info("########################"+formattedDate);

Below is the Http Request Body data

{
"articleId":""${ArticleId}",
"startDate":"${formattedDate}",
"endDate":"${Carttodates}"
}

When i run it Start date and end date is shown as ${formattedDate}, what will be the solution?

and in my JSON body data i want to send Start and End Date like "27/05/2019 14:34 "

Below is the Request I got

PUT data:
{
"articleId":"7694b207-936b-40b9-9c80-4b8097e67da1",
"startDate":"${formattedDate}",
"endDate":"${Carttodates}"
}

Body:
You need to put formattedDate as the variable name also:

vars.put("formattedDate", formattedDate);


问:
UWP Printing Long Datagrid that need to extend to multiple pages
I am making an accounting program using ( uwp , c#, MySQL ), I want to know when printing the reports if the datagrid is long how to extend the rest to new pages so that all report will be printed on multiple pages.

i used printhelp.cs that is in the printing sample: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/Printing , but it printed the datagrid only on one page and didn't extend the rest to more pages.

UWP XAML:

```<code><Grid>
    <controls:DataGrid Grid.Row="2" Grid.RowSpan="5" Grid.ColumnSpan="2"
        x:Name="TextContent"
        Foreground="Black"
        Background="White"
        ItemsSource="{x:Bind SelectSOA()}"
        AutoGenerateColumns="False"
        GridLinesVisibility="Horizontal">

        <controls:DataGrid.Columns>
            <controls:DataGridTextColumn   Header="ID" Binding="{Binding ID}" />
            <controls:DataGridTextColumn Header="Account" Binding="{Binding Principal}" />
            <controls:DataGridTextColumn Header="Balance" Binding="{Binding Client}" />
        </controls:DataGrid.Columns>
</code>```

```<code>    <RichTextBlockOverflow  x:Name="FirstLinkedContainer" OverflowContentTarget="{Binding ElementName=ContinuationPageLinkedContainer}" Grid.Row="2" Grid.Column="0"/>
    <RichTextBlockOverflow x:Name="ContinuationPageLinkedContainer" Grid.Row="3" Grid.ColumnSpan="2"/>

</Grid>
</code>```

i expect when printing if the Datagrid is long to extend to next page. but it only prints the first page and does not extend the rest to new pages.

答:
You could use the Print Helper class to print the DataGrid, but you still need to manually paging your data in code-behind.

Please see the Windows Community Toolkit PrintHelper sample to learn how to use this class to print the XAML control.

According to that sample, I do a little changes to make a simple code sample for your reference:

```<code><Grid>
    <Grid x:Name="RootGrid"
          HorizontalAlignment="Center"
          VerticalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid x:Name="Container"
              Grid.RowSpan="2"
              Opacity="0" />
        <Grid x:Name="CustomPrintContainer"
              Opacity="0" />
        <Grid x:Name="DirectPrintContainer">
            <Grid x:Name="PrintableContent">
                <Grid x:Name="XamlRoot" />
            </Grid>
        </Grid>
    </Grid>
    <Button Content="Print" Click="Button_Click" VerticalAlignment="Bottom"></Button>
</Grid>
</code>```

public List<Person> Persons { get; set; }

    public MainPage()
    {
        this.InitializeComponent();

        Persons = new List<Person>();
        for (int i = 0; i < 100; i++)
        {
            Persons.Add(new Person
            {
                PersonId = i,
                FirstName = "FirstName" + i,
                LastName = "LastName" + i,
                Position = "Network Administrator " + i
            });
        }
    }

    private PrintHelper _printHelper;

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        _printHelper = new PrintHelper(CustomPrintContainer);

        var pageNumber = 0;

        for (int i = 0; i < Persons.Count; i = i + 10)
        {
            var grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
            grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            // Static header
            var header = new TextBlock { Text = "Custom Print", Margin = new Thickness(0, 0, 0, 20) };
            Grid.SetRow(header, 0);
            grid.Children.Add(header);

            // Main content with layout from data template
            var dataGrid = new DataGrid();
            dataGrid.AutoGenerateColumns = true;
            dataGrid.ItemsSource = Persons.Skip(i).Take(10);
            Grid.SetRow(dataGrid, 1);
            grid.Children.Add(dataGrid);

            // Footer with page number
            pageNumber++;
            var footer = new TextBlock { Text = string.Format("page {0}", pageNumber), Margin = new Thickness(0, 20, 0, 0) };
            Grid.SetRow(footer, 2);
            grid.Children.Add(footer);

            _printHelper.AddFrameworkElementToPrint(grid);
        }

        _printHelper.OnPrintCanceled += _printHelper_OnPrintCanceled;
        _printHelper.OnPrintFailed += _printHelper_OnPrintFailed;
        _printHelper.OnPrintSucceeded += _printHelper_OnPrintSucceeded;

        var printHelperOptions = new PrintHelperOptions(false);
        printHelperOptions.Orientation = Windows.Graphics.Printing.PrintOrientation.Default;
        printHelperOptions.AddDisplayOption(StandardPrintTaskOptions.Orientation);
        await _printHelper.ShowPrintUIAsync("print sample", printHelperOptions);
    }
```

<pre class="lang-cs prettyprint-override"><code>public class Person
{
    public int PersonId { get; set; }
    public int DepartmentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Position { get; set; }
}
</code>```

Body:
I am making an accounting program using ( uwp , c#, MySQL ), I want to know when printing the reports if the datagrid is long how to extend the rest to new pages so that all report will be printed on multiple pages.

i used printhelp.cs that is in the printing sample: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/Printing , but it printed the datagrid only on one page and didn't extend the rest to more pages.

UWP XAML:

<Grid>
    <controls:DataGrid Grid.Row="2" Grid.RowSpan="5" Grid.ColumnSpan="2"
        x:Name="TextContent"
        Foreground="Black"
        Background="White"
        ItemsSource="{x:Bind SelectSOA()}"
        AutoGenerateColumns="False"
        GridLinesVisibility="Horizontal">

        <controls:DataGrid.Columns>
            <controls:DataGridTextColumn   Header="ID" Binding="{Binding ID}" />
            <controls:DataGridTextColumn Header="Account" Binding="{Binding Principal}" />
            <controls:DataGridTextColumn Header="Balance" Binding="{Binding Client}" />
        </controls:DataGrid.Columns>

    <RichTextBlockOverflow  x:Name="FirstLinkedContainer" OverflowContentTarget="{Binding ElementName=ContinuationPageLinkedContainer}" Grid.Row="2" Grid.Column="0"/>
    <RichTextBlockOverflow x:Name="ContinuationPageLinkedContainer" Grid.Row="3" Grid.ColumnSpan="2"/>

</Grid>

i expect when printing if the Datagrid is long to extend to next page. but it only prints the first page and does not extend the rest to new pages.

Body:
You could use the Print Helper class to print the DataGrid, but you still need to manually paging your data in code-behind.

Please see the Windows Community Toolkit PrintHelper sample to learn how to use this class to print the XAML control.

According to that sample, I do a little changes to make a simple code sample for your reference:

<Grid>
    <Grid x:Name="RootGrid"
          HorizontalAlignment="Center"
          VerticalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid x:Name="Container"
              Grid.RowSpan="2"
              Opacity="0" />
        <Grid x:Name="CustomPrintContainer"
              Opacity="0" />
        <Grid x:Name="DirectPrintContainer">
            <Grid x:Name="PrintableContent">
                <Grid x:Name="XamlRoot" />
            </Grid>
        </Grid>
    </Grid>
    <Button Content="Print" Click="Button_Click" VerticalAlignment="Bottom"></Button>
</Grid>

public List<Person> Persons { get; set; }

    public MainPage()
    {
        this.InitializeComponent();

        Persons = new List<Person>();
        for (int i = 0; i < 100; i++)
        {
            Persons.Add(new Person
            {
                PersonId = i,
                FirstName = "FirstName" + i,
                LastName = "LastName" + i,
                Position = "Network Administrator " + i
            });
        }
    }

    private PrintHelper _printHelper;

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        _printHelper = new PrintHelper(CustomPrintContainer);

        var pageNumber = 0;

        for (int i = 0; i < Persons.Count; i = i + 10)
        {
            var grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
            grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            // Static header
            var header = new TextBlock { Text = "Custom Print", Margin = new Thickness(0, 0, 0, 20) };
            Grid.SetRow(header, 0);
            grid.Children.Add(header);

            // Main content with layout from data template
            var dataGrid = new DataGrid();
            dataGrid.AutoGenerateColumns = true;
            dataGrid.ItemsSource = Persons.Skip(i).Take(10);
            Grid.SetRow(dataGrid, 1);
            grid.Children.Add(dataGrid);

            // Footer with page number
            pageNumber++;
            var footer = new TextBlock { Text = string.Format("page {0}", pageNumber), Margin = new Thickness(0, 20, 0, 0) };
            Grid.SetRow(footer, 2);
            grid.Children.Add(footer);

            _printHelper.AddFrameworkElementToPrint(grid);
        }

        _printHelper.OnPrintCanceled += _printHelper_OnPrintCanceled;
        _printHelper.OnPrintFailed += _printHelper_OnPrintFailed;
        _printHelper.OnPrintSucceeded += _printHelper_OnPrintSucceeded;

        var printHelperOptions = new PrintHelperOptions(false);
        printHelperOptions.Orientation = Windows.Graphics.Printing.PrintOrientation.Default;
        printHelperOptions.AddDisplayOption(StandardPrintTaskOptions.Orientation);
        await _printHelper.ShowPrintUIAsync("print sample", printHelperOptions);
    }

public class Person
{
    public int PersonId { get; set; }
    public int DepartmentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Position { get; set; }
}


问:
django.contrib.message Translation
Need to translate the django contrib messages into diffrent languages.

Here is the code i tried:

In Views.py

from django.utils.translation import gettext as _

messages.success(self.request, _("Sample text"))
```

<p>In template:</p>

<pre class="lang-html prettyprint-override"><code>{% for message in messages %}
   <div class="alert alert-{{ message.tags }}">
      ×
      {{ message }}
   </div>
{% endfor %}
</code>```

But the text is not getting translated. Is there any particular way to translate this? I am using python3 and django 1.11

答:
settings.py

```<code>MIDDLEWARE = [
    ...
    'django.middleware.locale.LocaleMiddleware',
    ...
]
LANGUAGE_CODE = 'en'
LANGUAGES = (
    ('en', 'English'),
    ('fr', 'French')
)
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)
TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True
</code>```

then :

python manage.py makemessages -l fr

translate messages in locale folder for french language

and then python manage.py compilemessages -l fr

Title: django.contrib.message Translation

Body:
Need to translate the django contrib messages into diffrent languages.

Here is the code i tried:

In Views.py

from django.utils.translation import gettext as _

messages.success(self.request, _("Sample text"))

In template:

{% for message in messages %}

      ×
      {{ message }}

{% endfor %}

But the text is not getting translated. Is there any particular way to translate this? I am using python3 and django 1.11

Body:
settings.py

MIDDLEWARE = [
    ...
    'django.middleware.locale.LocaleMiddleware',
    ...
]
LANGUAGE_CODE = 'en'
LANGUAGES = (
    ('en', 'English'),
    ('fr', 'French')
)
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)
TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

then :

python manage.py makemessages -l fr

translate messages in locale folder for french language

and then python manage.py compilemessages -l fr


问:
BillingClient.FeatureType - Which Type to Use
The google play billing overview states:

before your app enters the billing flow, call isFeatureSupported() to
  check that the device supports the products you want to sell. For a
  list of product types, see BillingClient.FeatureType.

The documentation for Feature type lists the following types:

IN_APP_ITEMS_ON_VR

PRICE_CHANGE_CONFIRMATION

SUBSCRIPTIONS

SUBSCRIPTIONS_ON_VR

SUBSCRIPTIONS_UPDATE

What is meant by "ON_VR"?  The documentation does not elaborate on this.

Since there is only one IN_APP_ITEMS* possibility, am I to assume that this should be used to verify device support for all in-app items?  The documentation states "Purchase/query for in-app items on VR." which isn't very helpful.

If I wanted to confirm support for subscriptions, which one would I use, SUBSCRIPTIONS or SUBSCRIPTIONS_ON_VR?  Why would I choose one over the other?

Here is the link:

BillingClient.FeatureType

Thanks in advance for any help clarifying this

答:
IN_APP_ITEMS_ON_VR and SUBSCRIPTIONS_ON_VR maybe reserved for future use, because I didn't see any mention of them in Google docs about in-app billing (in the web too).

All versions of Play Store support regular in-app products ("Managed products" in Google Play Console), so you can't check whether they are supported or not. Subscriptions support should be checked via SUBSCRIPTIONS feature.


问:
Which is better for Android MVVM package by feature or package by layer?
Another "which is better" question, I know these are highly subjective.  My definition for better would be:

Being used by the best dev teams

Best for unit testing

Most modular / easiest to build out a prod app

What Google recommends (this is where I'm most confused)

All of the Android blueprints use package-by-feature:

https://github.com/googlesamples/android-architecture

```<code>/tasks
/addedittask
/taskdetail
</code>```

and all of the architecture components samples using package by layer:

https://github.com/googlesamples/android-architecture-components

```<code>/db
/model
/ui
/persistence
</code>```

I'm confused because at the bottom of the Architecture Components site, it actually has links to the Android MVP and MVVM blueprint samples, which seems to me to be contradictory.

答:
Based on Android Architecture guide, and on Clean Architecture, I would suggest this approach

```<code>data/
    model/
    remote/
    local/
    Repository
domain/
    usecases/
        GetUserListUseCase
presentation/
    screen1/
        screen1Activity
        screen1Fragment
        screen1ViewModel
    screen2/
        screen2Activity
        screen2Fragment
        screen2ViewModel
core
    common/
    di/
</code>```

More here: https://www.toptal.com/android/android-apps-mvvm-with-clean-architecture

Body:
Another "which is better" question, I know these are highly subjective.  My definition for better would be:

Being used by the best dev teams

Best for unit testing

Most modular / easiest to build out a prod app

What Google recommends (this is where I'm most confused)

All of the Android blueprints use package-by-feature:

https://github.com/googlesamples/android-architecture

/tasks
/addedittask
/taskdetail

and all of the architecture components samples using package by layer:

https://github.com/googlesamples/android-architecture-components

/db
/model
/ui
/persistence

I'm confused because at the bottom of the Architecture Components site, it actually has links to the Android MVP and MVVM blueprint samples, which seems to me to be contradictory.

Body:
Based on Android Architecture guide, and on Clean Architecture, I would suggest this approach

data/
    model/
    remote/
    local/
    Repository
domain/
    usecases/
        GetUserListUseCase
presentation/
    screen1/
        screen1Activity
        screen1Fragment
        screen1ViewModel
    screen2/
        screen2Activity
        screen2Fragment
        screen2ViewModel
core
    common/
    di/

More here: https://www.toptal.com/android/android-apps-mvvm-with-clean-architecture


问:
How to exclude properties from Swift Codable?
Swift's Encodable/Decodable protocols, released with Swift 4, make JSON (de)serialization quite pleasant. However, I have not yet found a way to have fine-grained control over which properties should be encoded and which should get decoded.

I have noticed that excluding the property from the accompanying CodingKeys enum excludes the property from the process altogether, but is there a way to have more fine-grained control?

答:
If we need to exclude decoding of a couple of properties from a large set of properties in the structure, declare them as optional properties. Code to unwrapping optionals is less than writing a lot of keys under CodingKey enum.

I would recommend using extensions to add computed instance properties and computed type properties. It separates codable comforming properties from other logic hence provides better readability.


问:
Layout in list tile - flutter
Current output:

Expected output:

Code:

```<code>SizedBox(
      width: 380,
      height: 180,
      child: Swiper(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return Column(
            children: <Widget>[
              Expanded(
                child: Card(
                  child: ListTile(
                    title: Text(
                      '${items[index].title}',
                    ),
                    subtitle: Text(
                      '${items[index].body}',
                    ),
                    trailing: Column(
                      children: <Widget>[
                        CircleAvatar(
                          backgroundColor: HexColor("#0087a8"),
                          child: IconButton(
                            icon: Icon(Icons.add),
                      ],
                    ),
                  ),
                ),
              )
            ],
          );
        },
        viewportFraction: 0.8,
        scale: 0.9,
        control: SwiperControl(color: Colors.white),
      ),
    );
</code>```

I am unable to create the icon button to be that way. As when i put in padding, it says that the pixels overflowed. I need to get the add button on the bottom right hand side.

答:
As already pointed out, you shouldn't use a ListTile for this, as you want to use more than just a title, subtitle for your content.

The reason I've picked a Stack over a Column here, is that it allows you to safely use it in different size screens whilst assuring the view won't overflow. With Column, it would use the button diameter as the whole space to use (vertically), even though it is restrict to the right side of the box.

I believe this is what you're looking for.

```<code>class MyListTile extends StatelessWidget {
  const MyListTile({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 180.0,
      color: const Color(0xff0087a8),
      child: Container(
        padding: const EdgeInsets.all(20.0),
        margin: const EdgeInsets.all(10.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
          color: const Color.fromRGBO(19, 12, 117, 1.0),
        ),
        child: Stack(
          children: <Widget>[
            Text(
              'EUR - USD',
              style: Theme.of(context).textTheme.display2.copyWith(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
            ),
            Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Forex',
                style: TextStyle(color: Colors.white, fontSize: 20.0),
              ),
            ),
            Align(
              alignment: Alignment.bottomRight,
              child: FloatingActionButton(
                backgroundColor: const Color(0xff0087a8),
                onPressed: () {},
                child: Icon(
                  Icons.add,
                  color: Colors.white,
                  size: 50.0,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
</code>```

Title: Layout in list tile - flutter

Body:
Current output:

Expected output:

Code:

SizedBox(
      width: 380,
      height: 180,
      child: Swiper(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return Column(
            children: <Widget>[
              Expanded(
                child: Card(
                  child: ListTile(
                    title: Text(
                      '${items[index].title}',
                    ),
                    subtitle: Text(
                      '${items[index].body}',
                    ),
                    trailing: Column(
                      children: <Widget>[
                        CircleAvatar(
                          backgroundColor: HexColor("#0087a8"),
                          child: IconButton(
                            icon: Icon(Icons.add),
                      ],
                    ),
                  ),
                ),
              )
            ],
          );
        },
        viewportFraction: 0.8,
        scale: 0.9,
        control: SwiperControl(color: Colors.white),
      ),
    );

I am unable to create the icon button to be that way. As when i put in padding, it says that the pixels overflowed. I need to get the add button on the bottom right hand side.

Body:
As already pointed out, you shouldn't use a ListTile for this, as you want to use more than just a title, subtitle for your content.

The reason I've picked a Stack over a Column here, is that it allows you to safely use it in different size screens whilst assuring the view won't overflow. With Column, it would use the button diameter as the whole space to use (vertically), even though it is restrict to the right side of the box.

I believe this is what you're looking for.

class MyListTile extends StatelessWidget {
  const MyListTile({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 180.0,
      color: const Color(0xff0087a8),
      child: Container(
        padding: const EdgeInsets.all(20.0),
        margin: const EdgeInsets.all(10.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
          color: const Color.fromRGBO(19, 12, 117, 1.0),
        ),
        child: Stack(
          children: <Widget>[
            Text(
              'EUR - USD',
              style: Theme.of(context).textTheme.display2.copyWith(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
            ),
            Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Forex',
                style: TextStyle(color: Colors.white, fontSize: 20.0),
              ),
            ),
            Align(
              alignment: Alignment.bottomRight,
              child: FloatingActionButton(
                backgroundColor: const Color(0xff0087a8),
                onPressed: () {},
                child: Icon(
                  Icons.add,
                  color: Colors.white,
                  size: 50.0,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}


问:
How can i Send response to authorize client?
Just finished my first WCF service.

I want to limit the client to get service from my WCF server - so i want to response just to client that have the right password ( password will send as string in one of the argument field ) or just response to client that have specific ip address.

How can i do it in WCF ?

Thanks for any help.

答:
The "normal" expected behavior would be for the WCF service to:

return a valid result for those users who are authorized to call that service

throw a FaultException (possibly a typed FaultException<SecurityNegotiationException>) for those users who are not authorized


问:
Python - Remote Webdriver with Extension installed in it
I want to test one extension on different browser versions using BrowserStack.
This is a function that returns driver with specified capabilities.
I have a .crx file for Chrome and an .xpi file for Firefox on my local machine.
I want to use Remote Webdriver with a corresponding extension installed, using Python.

```<code>def my_webdriver(browser, browser_version, os, os_version):
    caps = {}
    caps["browser"] = browser
    caps["browser_version"] = browser_version
    caps["os"] = os
    caps["os_version"] = os_version
    caps["browserstack.debug"] = "true"
    driver = webdriver.Remote(
    ¦   command_executor = 'blahblahblah',
    ¦   desired_capabilities = caps)
    driver.maximize_window()
    return driver
</code>```

答:
E.Z.'s answer for chrome works if you use caps.update:

```<code>from selenium.webdriver.chrome.options import Options as ChromeOptions
chrome_options = ChromeOptions()
chrome_options.add_extension('/path/to/your/extension.crx')
caps.update(chrome_options.to_capabilities())
driver = RemoteWebDriver(..., desired_capabilities=caps)
</code>```

Body:
I want to test one extension on different browser versions using BrowserStack.
This is a function that returns driver with specified capabilities.
I have a .crx file for Chrome and an .xpi file for Firefox on my local machine.
I want to use Remote Webdriver with a corresponding extension installed, using Python.

def my_webdriver(browser, browser_version, os, os_version):
    caps = {}
    caps["browser"] = browser
    caps["browser_version"] = browser_version
    caps["os"] = os
    caps["os_version"] = os_version
    caps["browserstack.debug"] = "true"
    driver = webdriver.Remote(
    ¦   command_executor = 'blahblahblah',
    ¦   desired_capabilities = caps)
    driver.maximize_window()
    return driver

Body:
E.Z.'s answer for chrome works if you use caps.update:

from selenium.webdriver.chrome.options import Options as ChromeOptions
chrome_options = ChromeOptions()
chrome_options.add_extension('/path/to/your/extension.crx')
caps.update(chrome_options.to_capabilities())
driver = RemoteWebDriver(..., desired_capabilities=caps)


问:
How to center items in a Recyclerview?
I am using RecyclerView with Cardview items inside it. I set the  GridLayoutManager to show 2 items at each row and I want it to be centered on all phones like this :

expected result

But I have currently these :

Actual result

I tried different poor solutions (paddingLeft...) but it works on phones with bigger screens and doesn't work on smaller phones.

content_main.xml looks like this :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:queryHint="Rechercher un film"
        android:iconifiedByDefault="false"
        android:layout_marginTop="65dp"
        android:layout_marginBottom="10dp"
        android:layout_height="30dp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/movies_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/searchView"
        android:scrollbars="vertical"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true" />

</RelativeLayout>
</code>```

movie_card.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<android.support.v7.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="170dip"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/item_movie_poster"
            android:layout_width="170dip"
            android:layout_height="256dip"
            android:layout_centerHorizontal="true"
            android:contentDescription="@string/movie_image_description"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/item_movie_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/item_movie_poster"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="10dip"
            android:layout_marginTop="5dip"
            android:textSize="15sp"
            android:textAlignment="center"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:textStyle="bold" />

    </RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</code>```

And app_bar_main.xml which includes the content_main.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
set right or left margin in your recyler view :- </p>

```<code><android.support.v7.widget.RecyclerView
        android:id="@+id/movies_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/searchView"
        android:scrollbars="vertical"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true" />
</code>```

Title: How to center items in a Recyclerview?

Body:
I am using RecyclerView with Cardview items inside it. I set the  GridLayoutManager to show 2 items at each row and I want it to be centered on all phones like this :

expected result

But I have currently these :

Actual result

I tried different poor solutions (paddingLeft...) but it works on phones with bigger screens and doesn't work on smaller phones.

content_main.xml looks like this :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:queryHint="Rechercher un film"
        android:iconifiedByDefault="false"
        android:layout_marginTop="65dp"
        android:layout_marginBottom="10dp"
        android:layout_height="30dp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/movies_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/searchView"
        android:scrollbars="vertical"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true" />

</RelativeLayout>

movie_card.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<android.support.v7.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="170dip"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/item_movie_poster"
            android:layout_width="170dip"
            android:layout_height="256dip"
            android:layout_centerHorizontal="true"
            android:contentDescription="@string/movie_image_description"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/item_movie_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/item_movie_poster"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="10dip"
            android:layout_marginTop="5dip"
            android:textSize="15sp"
            android:textAlignment="center"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:textStyle="bold" />

    </RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

And app_bar_main.xml which includes the content_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

Body:
set right or left margin in your recyler view :-

<android.support.v7.widget.RecyclerView
        android:id="@+id/movies_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/searchView"
        android:scrollbars="vertical"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true" />


问:
How to skip certain period of time in X-axis (stock market lunch break)
I used the following code to plot the graph.
The stock market lunch break is 12:00 - 13:00

You can see the graph is a little bit ugly as there is gap around lunch break.
How to skip 12:00 - 13:00 in X-axis so that the Y-axis data is continuous and there is no such gap in the graph?

```<code>import pandas as pd
import pandas_datareader.data
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import HourLocator
import datetime

today_s = datetime.date.today().strftime('%Y%m%d')

df = pd.read_csv('futures-sample.txt', names=['Time', 'HSIF', 'Volume'], delim_whitespace=True)
df['Time'] = pd.to_datetime(df['Time'])

# RSI
window_length = 14
df['Delta'] = df['HSIF'].diff().shift(0)
df['DeltaUp'] = df['Delta'].apply(lambda x: x if x > 0 else 0)
df['DeltaDown'] = df['Delta'].apply(lambda x: -x if x < 0 else 0)
df['RollUp'] = df['DeltaUp'].rolling(window_length).mean()
df['RollDown'] = df['DeltaDown'].rolling(window_length).mean()
df['RS'] = df['RollUp'] / df['RollDown']
df['RSI'] = 100.0 - (100.0 / (1.0 + df['RS']))
pd.set_option('display.max_rows', 10000)

df = df.set_index('Time')

fig , ax1 = plt.subplots()
ax1.set_xlabel('Time')
ax1.set_ylabel('HSIF', color='blue')
ax1.plot(df['HSIF'], color='blue')
ax1.tick_params(axis='y', labelcolor='blue')
ax2= ax1.twinx()
ax2.set_ylabel('RSI', color='orchid')
ax2.plot(df['RSI'], color='orchid')
ax2.tick_params(axis='y', labelcolor='orchid')

fig = ax2.get_figure()
fig.set_size_inches(10, 7)
fig.savefig('/var/www/html/temp.png', dpi=100)
</code>```

Here is the content of futures-sample.txt

```<code># cat futures-samples.txt
2019/05/16-09:15 27830 2031
2019/05/16-09:16 27815 995
2019/05/16-09:17 27829 961
2019/05/16-09:18 27848 663
2019/05/16-09:19 27873 869
2019/05/16-09:20 27847 854
2019/05/16-09:21 27828 784
...
2019/05/16-11:52 28087 175
2019/05/16-11:53 28076 346
2019/05/16-11:54 28089 223
2019/05/16-11:55 28096 137
2019/05/16-11:56 28102 175
2019/05/16-11:57 28110 294
2019/05/16-11:58 28089 256
2019/05/16-11:59 28089 235
2019/05/16-12:59 28070 108
2019/05/16-13:00 28061 800
2019/05/16-13:01 28070 470
2019/05/16-13:02 28051 326
2019/05/16-13:03 28058 699
2019/05/16-13:04 28059 296
2019/05/16-13:05 28064 369
2019/05/16-13:06 28046 683
2019/05/16-13:07 28051 457
2019/05/16-13:08 28049 340
</code>```

答:
I think it should work, but I am not sure if it is the best method. </p>

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import HourLocator
import datetime

today_s = datetime.date.today().strftime('%Y%m%d')

df = pd.read_csv(r'test.txt', names=['Time', 'HSIF', 'Volume'], delim_whitespace=True)

df['Time'] = pd.to_datetime(df['Time'])
df["Time"] = df['Time'].apply(lambda x: x.strftime('%d %H:%M'))
# RSI
window_length = 14
df['Delta'] = df['HSIF'].diff().shift(0)
df['DeltaUp'] = df['Delta'].apply(lambda x: x if x > 0 else 0)
df['DeltaDown'] = df['Delta'].apply(lambda x: -x if x < 0 else 0)
df['RollUp'] = df['DeltaUp'].rolling(window_length).mean()
df['RollDown'] = df['DeltaDown'].rolling(window_length).mean()
df['RS'] = df['RollUp'] / df['RollDown']
df['RSI'] = 100.0 - (100.0 / (1.0 + df['RS']))
pd.set_option('display.max_rows', 10000)

#df = df.set_index('Time')
#print (type(df['Time']))
fig , ax1 = plt.subplots()
ax1.set_xlabel('Time')
#ax1.set_xticklabels(df['Time'])
ax1.set_ylabel('HSIF', color='blue')
ax1.plot(df['Time'], df['HSIF'], color='blue')
ax1.tick_params(axis='y', labelcolor='blue')
ax2= ax1.twinx()
ax2.set_ylabel('RSI', color='orchid')
ax2.plot(df['Time'], df['RSI'], color='orchid')
ax2.tick_params(axis='y', labelcolor='orchid')

# set xtick interval
tick_start, tick_end = ax1.get_xlim()
ax1.xaxis.set_ticks(np.arange(tick_start, tick_end, 2))

fig = ax2.get_figure()
fig.set_size_inches(10, 7)
plt.show()
</code>```

Body:
I used the following code to plot the graph.
The stock market lunch break is 12:00 - 13:00

You can see the graph is a little bit ugly as there is gap around lunch break.
How to skip 12:00 - 13:00 in X-axis so that the Y-axis data is continuous and there is no such gap in the graph?

import pandas as pd
import pandas_datareader.data
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import HourLocator
import datetime

today_s = datetime.date.today().strftime('%Y%m%d')

df = pd.read_csv('futures-sample.txt', names=['Time', 'HSIF', 'Volume'], delim_whitespace=True)
df['Time'] = pd.to_datetime(df['Time'])

# RSI
window_length = 14
df['Delta'] = df['HSIF'].diff().shift(0)
df['DeltaUp'] = df['Delta'].apply(lambda x: x if x > 0 else 0)
df['DeltaDown'] = df['Delta'].apply(lambda x: -x if x < 0 else 0)
df['RollUp'] = df['DeltaUp'].rolling(window_length).mean()
df['RollDown'] = df['DeltaDown'].rolling(window_length).mean()
df['RS'] = df['RollUp'] / df['RollDown']
df['RSI'] = 100.0 - (100.0 / (1.0 + df['RS']))
pd.set_option('display.max_rows', 10000)

df = df.set_index('Time')

fig , ax1 = plt.subplots()
ax1.set_xlabel('Time')
ax1.set_ylabel('HSIF', color='blue')
ax1.plot(df['HSIF'], color='blue')
ax1.tick_params(axis='y', labelcolor='blue')
ax2= ax1.twinx()
ax2.set_ylabel('RSI', color='orchid')
ax2.plot(df['RSI'], color='orchid')
ax2.tick_params(axis='y', labelcolor='orchid')

fig = ax2.get_figure()
fig.set_size_inches(10, 7)
fig.savefig('/var/www/html/temp.png', dpi=100)

Here is the content of futures-sample.txt

# cat futures-samples.txt
2019/05/16-09:15 27830 2031
2019/05/16-09:16 27815 995
2019/05/16-09:17 27829 961
2019/05/16-09:18 27848 663
2019/05/16-09:19 27873 869
2019/05/16-09:20 27847 854
2019/05/16-09:21 27828 784
...
2019/05/16-11:52 28087 175
2019/05/16-11:53 28076 346
2019/05/16-11:54 28089 223
2019/05/16-11:55 28096 137
2019/05/16-11:56 28102 175
2019/05/16-11:57 28110 294
2019/05/16-11:58 28089 256
2019/05/16-11:59 28089 235
2019/05/16-12:59 28070 108
2019/05/16-13:00 28061 800
2019/05/16-13:01 28070 470
2019/05/16-13:02 28051 326
2019/05/16-13:03 28058 699
2019/05/16-13:04 28059 296
2019/05/16-13:05 28064 369
2019/05/16-13:06 28046 683
2019/05/16-13:07 28051 457
2019/05/16-13:08 28049 340

Body:
I think it should work, but I am not sure if it is the best method.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import HourLocator
import datetime

today_s = datetime.date.today().strftime('%Y%m%d')

df = pd.read_csv(r'test.txt', names=['Time', 'HSIF', 'Volume'], delim_whitespace=True)

df['Time'] = pd.to_datetime(df['Time'])
df["Time"] = df['Time'].apply(lambda x: x.strftime('%d %H:%M'))
# RSI
window_length = 14
df['Delta'] = df['HSIF'].diff().shift(0)
df['DeltaUp'] = df['Delta'].apply(lambda x: x if x > 0 else 0)
df['DeltaDown'] = df['Delta'].apply(lambda x: -x if x < 0 else 0)
df['RollUp'] = df['DeltaUp'].rolling(window_length).mean()
df['RollDown'] = df['DeltaDown'].rolling(window_length).mean()
df['RS'] = df['RollUp'] / df['RollDown']
df['RSI'] = 100.0 - (100.0 / (1.0 + df['RS']))
pd.set_option('display.max_rows', 10000)

#df = df.set_index('Time')
#print (type(df['Time']))
fig , ax1 = plt.subplots()
ax1.set_xlabel('Time')
#ax1.set_xticklabels(df['Time'])
ax1.set_ylabel('HSIF', color='blue')
ax1.plot(df['Time'], df['HSIF'], color='blue')
ax1.tick_params(axis='y', labelcolor='blue')
ax2= ax1.twinx()
ax2.set_ylabel('RSI', color='orchid')
ax2.plot(df['Time'], df['RSI'], color='orchid')
ax2.tick_params(axis='y', labelcolor='orchid')

# set xtick interval
tick_start, tick_end = ax1.get_xlim()
ax1.xaxis.set_ticks(np.arange(tick_start, tick_end, 2))

fig = ax2.get_figure()
fig.set_size_inches(10, 7)
plt.show()


问:
Changing Button Color using Listbox
I need to change background color of Button using ListBox. I have 3 ListBoxItems for 3 colors ( green, yellow and red). I am not sure how to do this. Any help will be greatly appreciated.</p>

```<code><StackPanel Grid.Column="1" Grid.Row="3">
  <ToggleButton Height="50" Content="Change!" Name="button">
   </ToggleButton>
    <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
     <Border Background="LightYellow">
       <ListBox>
        <ListBoxItem>Green</ListBoxItem>
         <ListBoxItem>Yellow</ListBoxItem>
        <ListBoxItem>Red</ListBoxItem>
      </ListBox>
    </Border>
  </Popup>
</StackPanel>
</code>```

答:
Here's a solution that uses no code-behind. It binds with the listbox. It shows better without the popup as you will have to remove focus from the button to see the change with the popup.

```<code>   <StackPanel Grid.Column="1" Grid.Row="3">
        <ToggleButton  Height="50" Content="Change!" Name="button">
            <ToggleButton.Background>
                <Binding ElementName="lb" Path="SelectedItem.Content" />
            </ToggleButton.Background>
        </ToggleButton>
        <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
            <Border Background="LightYellow">
                <ListBox Name="lb" >
                    <ListBoxItem>Green</ListBoxItem>
                    <ListBoxItem>Yellow</ListBoxItem>
                    <ListBoxItem>Red</ListBoxItem>
                </ListBox>
            </Border>
        </Popup>
    </StackPanel>
</code>```

Remove the <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False"> and </Popup> lines which will put the listbox directly under the button. This will show the color change immediately.

Title: Changing Button Color using Listbox

Body:
I need to change background color of Button using ListBox. I have 3 ListBoxItems for 3 colors ( green, yellow and red). I am not sure how to do this. Any help will be greatly appreciated.

<StackPanel Grid.Column="1" Grid.Row="3">
  <ToggleButton Height="50" Content="Change!" Name="button">
   </ToggleButton>
    <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
     <Border Background="LightYellow">
       <ListBox>
        <ListBoxItem>Green</ListBoxItem>
         <ListBoxItem>Yellow</ListBoxItem>
        <ListBoxItem>Red</ListBoxItem>
      </ListBox>
    </Border>
  </Popup>
</StackPanel>

Body:
Here's a solution that uses no code-behind. It binds with the listbox. It shows better without the popup as you will have to remove focus from the button to see the change with the popup.

   <StackPanel Grid.Column="1" Grid.Row="3">
        <ToggleButton  Height="50" Content="Change!" Name="button">
            <ToggleButton.Background>
                <Binding ElementName="lb" Path="SelectedItem.Content" />
            </ToggleButton.Background>
        </ToggleButton>
        <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
            <Border Background="LightYellow">
                <ListBox Name="lb" >
                    <ListBoxItem>Green</ListBoxItem>
                    <ListBoxItem>Yellow</ListBoxItem>
                    <ListBoxItem>Red</ListBoxItem>
                </ListBox>
            </Border>
        </Popup>
    </StackPanel>

Remove the <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False"> and </Popup> lines which will put the listbox directly under the button. This will show the color change immediately.


问:
Error with Report Page in Oracle Application Express
I have a report based on a SQL Query, the report has 3 columns from v$session.

```<code>select distinct to_char(SQL_EXEC_START, 'DD/MM/YYYY HH24:MI') TIME_STARTED, module REPORT_NAME, action CURRENT_STEP from v$session where module like '%BOB%'
</code>```

In SQL Developer, the query brings up what you would expect. However in the APEX report page, no matter what is in v$session, I always get (in addition) the following displayed at the top of the report page, in the actual report columns:

```<code><DATE>  Processes - point: BEFORE_BOX_BODY  BOB01/APEX:APP 104:7
</code>```

Can anyone tell me how to get rid of it, and simply output the query results into the report page, and nothing else?

答:
It seems that it displays current report as well. So - remove it, e.g.</p>

```<code>select distinct
  to_char(SQL_EXEC_START, 'DD/MM/YYYY HH24:MI') TIME_STARTED,
  module REPORT_NAME,
  action CURRENT_STEP
from v$session
where module like '%BOB%'
  -- add this
  and module not like '%104:7%'
  and current_step not like '%BEFORE_BOX_BODY%'
</code>```

Body:
I have a report based on a SQL Query, the report has 3 columns from v$session.

select distinct to_char(SQL_EXEC_START, 'DD/MM/YYYY HH24:MI') TIME_STARTED, module REPORT_NAME, action CURRENT_STEP from v$session where module like '%BOB%'

In SQL Developer, the query brings up what you would expect. However in the APEX report page, no matter what is in v$session, I always get (in addition) the following displayed at the top of the report page, in the actual report columns:

<DATE>  Processes - point: BEFORE_BOX_BODY  BOB01/APEX:APP 104:7

Can anyone tell me how to get rid of it, and simply output the query results into the report page, and nothing else?

Body:
It seems that it displays current report as well. So - remove it, e.g.

select distinct
  to_char(SQL_EXEC_START, 'DD/MM/YYYY HH24:MI') TIME_STARTED,
  module REPORT_NAME,
  action CURRENT_STEP
from v$session
where module like '%BOB%'
  -- add this
  and module not like '%104:7%'
  and current_step not like '%BEFORE_BOX_BODY%'


问:
kubernetes stack not writable
I was able to follow all instructions mentioned here and create a cluster.

https://github.com/digitalocean/doks-example

I changed the image to my own, custom image.

```<code># /usr/local/bin/kubectl --kubeconfig="k8s-1-14-2-do-0-blr1-1558848628228-kubeconfig.yaml" apply -f manifest1.yaml
service/doks-example1 created
deployment.extensions/doks-example1 created
</code>```

The new app is deployed successfully...

```<code># /usr/local/bin/kubectl --kubeconfig="k8s-1-14-2-do-0-blr1-1558848628228-kubeconfig.yaml" get service
NAME            TYPE           CLUSTER-IP      EXTERNAL-IP     PORT(S)          AGE
doks-example    LoadBalancer   10.245.92.169   139.59.48.36    80:31378/TCP     14m
doks-example1   LoadBalancer   10.245.250.95   139.59.49.155   8887:32137/TCP   3m1s
kubernetes      ClusterIP      10.245.0.1      <none>          443/TCP          22m
</code>```

But I am not able to create a new jupyter notebook after logging in. I get a "Forbidden" error.

How do I make the container writable?

答: This seems related to cache issue discussed in this issue. Pressing F5 worked quickly with your configuration

Title: kubernetes stack not writable

Body:
I was able to follow all instructions mentioned here and create a cluster.

https://github.com/digitalocean/doks-example

I changed the image to my own, custom image.

# /usr/local/bin/kubectl --kubeconfig="k8s-1-14-2-do-0-blr1-1558848628228-kubeconfig.yaml" apply -f manifest1.yaml
service/doks-example1 created
deployment.extensions/doks-example1 created

The new app is deployed successfully...

# /usr/local/bin/kubectl --kubeconfig="k8s-1-14-2-do-0-blr1-1558848628228-kubeconfig.yaml" get service
NAME            TYPE           CLUSTER-IP      EXTERNAL-IP     PORT(S)          AGE
doks-example    LoadBalancer   10.245.92.169   139.59.48.36    80:31378/TCP     14m
doks-example1   LoadBalancer   10.245.250.95   139.59.49.155   8887:32137/TCP   3m1s
kubernetes      ClusterIP      10.245.0.1      <none>          443/TCP          22m

But I am not able to create a new jupyter notebook after logging in. I get a "Forbidden" error.

How do I make the container writable?


问:
SSH to Google Compute instance using NodeJS, without gcloud
I'm trying to create a SSH tunnel into a compute instance, from an environment that doesn't have gcloud installed (App Engine Standard NodeJS Environment).

What are the steps needed to do that? How does gcloud compute ssh command does it? Is there a NodeJS library that already does it?

答: You can use ssh2 to do that in nodejs.</p>

Body: You can use ssh2 to do that in nodejs.


问:
How to Develop a get end-point with spring boot that support interruption (pause, connection lost, …)?
I'm trying  to develop an endpoint that download files from a server. My endpoint should support interruption (pause, connection lost, …).

For the moment i have no idea how to do it. I just develop a simple get endpoint.

  @GetMapping("/self/{fileName}")
   public ResponseEntity<Resource> getFile(@PathVariable("fileName") String fileName,
                                           @RequestParam(value ="checksum", required = false) String checksumParam,
                                           @RequestHeader HttpHeaders headers,
                                           HttpServletRequest request) throws Exception {

           Resource resource;
           String contentType = null;
           String country = headers
            .getFirst(fileStorageProperties.getHeaderCountryField())
            .toLowerCase();

           try {

               contentType = request
                 .getServletContext()
                 .getMimeType(resource.getFile().getAbsolutePath());

           } catch ( IOException ex) {
               this.log.error(ex.getMessage());
           }

           if(contentType == null) {
               contentType = "application/octet-stream";
           }

           HttpHeaders responseHeaders = new HttpHeaders();
                responseHeaders
.set(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\"" + resource.getFilename() + "\"");

               return ResponseEntity.ok()
                       .contentType(MediaType.parseMediaType(contentType))
                       .headers(responseHeaders)
                       .body(resource);

   }
```

I would like to resume the download from where it was stopped if the download is stopped because of connection lost or if the user choose to stop it.

答: What about using Http header Range? Implement your get method to check for that header and if exists then just cut that number of bytes from your file.</p>

Body:
I'm trying  to develop an endpoint that download files from a server. My endpoint should support interruption (pause, connection lost, …).

For the moment i have no idea how to do it. I just develop a simple get endpoint.

  @GetMapping("/self/{fileName}")
   public ResponseEntity<Resource> getFile(@PathVariable("fileName") String fileName,
                                           @RequestParam(value ="checksum", required = false) String checksumParam,
                                           @RequestHeader HttpHeaders headers,
                                           HttpServletRequest request) throws Exception {

           Resource resource;
           String contentType = null;
           String country = headers
            .getFirst(fileStorageProperties.getHeaderCountryField())
            .toLowerCase();

           try {

               contentType = request
                 .getServletContext()
                 .getMimeType(resource.getFile().getAbsolutePath());

           } catch ( IOException ex) {
               this.log.error(ex.getMessage());
           }

           if(contentType == null) {
               contentType = "application/octet-stream";
           }

           HttpHeaders responseHeaders = new HttpHeaders();
                responseHeaders
.set(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\"" + resource.getFilename() + "\"");

               return ResponseEntity.ok()
                       .contentType(MediaType.parseMediaType(contentType))
                       .headers(responseHeaders)
                       .body(resource);

   }

I would like to resume the download from where it was stopped if the download is stopped because of connection lost or if the user choose to stop it.


答:
Check below code. You need to remove android:layout_alignParentStart="true" and add
        android:layout_centerInParent="true" in your RecyclerView

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:queryHint="Rechercher un film"
        android:iconifiedByDefault="false"
        android:layout_marginTop="65dp"
        android:layout_marginBottom="10dp"
        android:layout_height="30dp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/movies_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:layout_centerInParent="true"
        android:layout_below="@+id/searchView"
        android:scrollbars="vertical"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true" />

    </RelativeLayout>
</code>```

I hope that will works for you.

Title: How to center items in a Recyclerview?

Body:
Check below code. You need to remove android:layout_alignParentStart="true" and add
        android:layout_centerInParent="true" in your RecyclerView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:queryHint="Rechercher un film"
        android:iconifiedByDefault="false"
        android:layout_marginTop="65dp"
        android:layout_marginBottom="10dp"
        android:layout_height="30dp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/movies_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:layout_centerInParent="true"
        android:layout_below="@+id/searchView"
        android:scrollbars="vertical"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true" />

    </RelativeLayout>

I hope that will works for you.