问:
In redux-observable - How can I dispatch an action "mid-stream" without returning the value of that action?
I have searched everywhere and cannot find an answer to the following...

In my addItemEpic I would like to dispatch a "loading" action before sending the ajax request - I DO NOT want the value of the action to be returned - I just want to DO the action then return the ajax response.
This can be achieved easily with store.dispatch() as below:

```<code>export const addItemsEpic = (action$, store) =>
  action$.ofType(ADD_ITEM)
    .do(() => store.dispatch({
        type: 'layout/UPDATE_LAYOUT',
        payload: { loading: true }
    }))
    .switchMap(action => api.addItem(action.payload))
    .map(item => loadItem(item))
    .do(() => store.dispatch({
       type: 'layout/UPDATE_LAYOUT',
       payload: { loading: false }
    }))
    .catch(error => Observable.of({
       type: 'AJAX_ERROR',
       payload: error,
       error: true
   }));
</code>```

However store.dispatch() is deprecated and discouraged in redux-observable.

I have attempted to use almost every plausible operator and still I cannot dispatch the action without disrupting the return value in the next chained function. I thought something like te following should do it:

```<code>action$.ofType(ADD_ITEM)
   .concatMap(action => Observable.of(
      updateLayout({loading: true}),
      api.addItem(action.payload)).last())
   .map(item => loadItem(item))
</code>```

But unfortunately 2 problems here:

no loading-action is dispatched (the value IS returned as an observable)

api request now returns a wrapped promise instead of a mappable value

I'd really appreciate some help or advice here as I can't find any way to get this working.

Thanks in advance

答:
The second form is on the right path. The idea is to return an Observable that first emits the loading action, then after the service call, emits either the loaded action or error action, and finally emits the done loading action.

const addItemEpic = action$ => action$
  .ofType(ADD_ITEM)
  .switchMap(action => { // or use mergeMap/concatMap depending on your needs
    const apiCall$ = Observable.fromPromise(api.addItem(action.payload))
      .map(item => actions.loadItem(item))
      .catch(err => Observable.of(actions.ajaxError(err)));

    return Observable.concat(
      Observable.of(actions.updateLayout(true)),
      Observable.concat(apiCall$,
        Observable.of(actions.updateLayout(false))));
  });
```

Observable.fromPromise() converts a Promise to an Observable

Body:
I have searched everywhere and cannot find an answer to the following...

In my addItemEpic I would like to dispatch a "loading" action before sending the ajax request - I DO NOT want the value of the action to be returned - I just want to DO the action then return the ajax response.
This can be achieved easily with store.dispatch() as below:

export const addItemsEpic = (action$, store) =>
  action$.ofType(ADD_ITEM)
    .do(() => store.dispatch({
        type: 'layout/UPDATE_LAYOUT',
        payload: { loading: true }
    }))
    .switchMap(action => api.addItem(action.payload))
    .map(item => loadItem(item))
    .do(() => store.dispatch({
       type: 'layout/UPDATE_LAYOUT',
       payload: { loading: false }
    }))
    .catch(error => Observable.of({
       type: 'AJAX_ERROR',
       payload: error,
       error: true
   }));

However store.dispatch() is deprecated and discouraged in redux-observable.

I have attempted to use almost every plausible operator and still I cannot dispatch the action without disrupting the return value in the next chained function. I thought something like te following should do it:

action$.ofType(ADD_ITEM)
   .concatMap(action => Observable.of(
      updateLayout({loading: true}),
      api.addItem(action.payload)).last())
   .map(item => loadItem(item))

But unfortunately 2 problems here:

no loading-action is dispatched (the value IS returned as an observable)

api request now returns a wrapped promise instead of a mappable value

I'd really appreciate some help or advice here as I can't find any way to get this working.

Thanks in advance

Body:
The second form is on the right path. The idea is to return an Observable that first emits the loading action, then after the service call, emits either the loaded action or error action, and finally emits the done loading action.

const addItemEpic = action$ => action$
  .ofType(ADD_ITEM)
  .switchMap(action => { // or use mergeMap/concatMap depending on your needs
    const apiCall$ = Observable.fromPromise(api.addItem(action.payload))
      .map(item => actions.loadItem(item))
      .catch(err => Observable.of(actions.ajaxError(err)));

    return Observable.concat(
      Observable.of(actions.updateLayout(true)),
      Observable.concat(apiCall$,
        Observable.of(actions.updateLayout(false))));
  });

Observable.fromPromise() converts a Promise to an Observable


来源: stackexchange

问:
How to sum n % of values in Postgres
How to sum let's say 50 % of all values ordered by value in my Postgres table?

In table I have values 1, 2, 3, 4, 5, 6 and I'd like to get the sum of half values ordered by value DESC. So the result would be 4 + 5 + 6 = 15

Also, I might want to get only 1/3 of values so I would get 6 + 5 = 11

Is it possible with SQL in Postgres? Something like

```<code>SELECT sum(value)
FROM (
       SELECT value
       FROM table
       ORDER BY value DESC
       LIMIT 50%
     ) subquery
</code>```

答:
percent_rank:

```<code>with t (value) as (values (1),(2),(3),(4),(5),(6))
select sum(value)
from (
    select value, percent_rank() over (order by value) as pr
    from t
) S
where pr > 0.5
;
 sum
-----
  15
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to sum n % of values in Postgres

Body:
How to sum let's say 50 % of all values ordered by value in my Postgres table?

In table I have values 1, 2, 3, 4, 5, 6 and I'd like to get the sum of half values ordered by value DESC. So the result would be 4 + 5 + 6 = 15

Also, I might want to get only 1/3 of values so I would get 6 + 5 = 11

Is it possible with SQL in Postgres? Something like

SELECT sum(value)
FROM (
       SELECT value
       FROM table
       ORDER BY value DESC
       LIMIT 50%
     ) subquery

Body:
percent_rank:

with t (value) as (values (1),(2),(3),(4),(5),(6))
select sum(value)
from (
    select value, percent_rank() over (order by value) as pr
    from t
) S
where pr > 0.5
;
 sum
-----
  15


问:
Data persistence through NSUserDefaults
Is data persisted in NSUserDefaults between app launches? I want some small data to be persisted even if I quit and relaunch the app.</p>

答:
Yes.

Data will persist in NSUserDefaults for the entire lifetime of the app.

ContentLicense: CC BY-SA 2.5

Title: Data persistence through NSUserDefaults


问:
Bigquery Custom first day of week (defaults Monday)
I am trying to extract week from date using the function

format_timestamp('%V', DATE)

but Bigquery documentation says "Monday as the first day of the week".

Is there a way where I can specify Tuesday as first day of week.

I have achieved the same in Redshift using

date_part(week, date + interval '-1 day')

Is it possible in Bigquery?

答:
Below is for BigQuery Standard SQL

You can use WEEK(WEEKDAY) as shown below

#standardSQL
SELECT FORMAT_TIMESTAMP('%V', CURRENT_TIMESTAMP()),
EXTRACT(WEEK(SATURDAY) FROM CURRENT_TIMESTAMP())
```

This was introduced quite recently - https://cloud.google.com/bigquery/docs/release-notes#november_30_2017

Body:
Below is for BigQuery Standard SQL

You can use WEEK(WEEKDAY) as shown below

#standardSQL
SELECT FORMAT_TIMESTAMP('%V', CURRENT_TIMESTAMP()),
EXTRACT(WEEK(SATURDAY) FROM CURRENT_TIMESTAMP())

This was introduced quite recently - https://cloud.google.com/bigquery/docs/release-notes#november_30_2017


问:
css Hyphens not working in chrome
In my project paragraph (in p tag) i have give text-align:justify; but in some words there more space comes so for this solution i try:
HTML code:

```<code><p>What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</code>```

CSS code:

```<code>p{
    text-align:justify;
    word-break: break-all;
    hyphens: auto;
}
</code>```

but in this code mozilla works but not work in chrome,for this i try

```<code>p{
    text-align:justify;
    -ms-word-break: break-all;
    word-break: break-all;
    word-break: break-word;
   -webkit-hyphens: auto;
   -moz-hyphens: auto;
   hyphens: auto;
}
</code>```

below css there -webkit- is used for chrome right but still not working please help, please give the solutions......

答: This is a known bug in Chrome for Windows, Linux, and ChromeOS.</p>

Title: css Hyphens not working in chrome

Body:
In my project paragraph (in p tag) i have give text-align:justify; but in some words there more space comes so for this solution i try:
HTML code:

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

CSS code:

p{
    text-align:justify;
    word-break: break-all;
    hyphens: auto;
}

but in this code mozilla works but not work in chrome,for this i try

p{
    text-align:justify;
    -ms-word-break: break-all;
    word-break: break-all;
    word-break: break-word;
   -webkit-hyphens: auto;
   -moz-hyphens: auto;
   hyphens: auto;
}

below css there -webkit- is used for chrome right but still not working please help, please give the solutions......


问:
How to design a parallel code for a Fibonacci algorithm, but without openmp tasks?
I want to write a c++ code for calculating Fibonacci numbers in parallel, with a use of OpenMP tools. I know that, with #pragma omp task, the code will be:

```<code>int fib(int n) {
int i, j;
if (n<2)
    return n;
else {
    #pragma omp task shared(i)
    i=fib(n-1);
    #pragma omp task shared(j)
    j=fib(n-2);
    #pragma omp taskwait
    return i+j;
    }
}
</code>```

Computing this way is not cool, since each thread is waiting for its child threads to complete their work, so the whole process is still a sequential!

I want to write the parallel code, using this equation:

F(n + k) = F(n + 1) * F(k) + F(n) * F(k - 1)

Would anyone help me to do this?

答:
Below is an alternative parallel solution which directly calculates fib(n) and fib(n+1) using the golden ratio and then calculates the rest of the sequence sequentially for each thread. I got the direct solution from rosettacode.

The problem is that the direct calculations overflows for n>72 so this method is almost certainly slower than calculating the first 71 numbers sequentially and in any case 64-bit integers overflows for n>92.

```<code>#include <math.h>
#include <stdio.h>
#include <inttypes.h>
#include <omp.h>

uint64_t fib(unsigned m) { // Direct Calculation, correct for abs(m) <= 71
  double sqrt5r =  1.0 / sqrt(5.0);
  double golden = (1.0 + sqrt(5.0))/2.0;
  return rint(pow(golden, m)*sqrt5r);
}

void fib_sequence(unsigned n, uint64_t *f) {
  #pragma omp parallel
  {
    size_t t  = omp_get_thread_num();
    size_t nt = omp_get_num_threads();
    int x0 = (t+0)*n/nt;
    int x1 = (t+1)*n/nt;
    f[x0 + 0] = fib(x0 + 0);
    f[x0 + 1] = fib(x0 + 1);
    for(int i=x0+2; i<x1; i++) {
      f[i] = f[i-2] + f[i-1];
    }
  }
}

int main(void) {
  int n = 71;
  uint64_t f1[n], f2[n];
  for(int i=0; i<n; i++) f1[i] = fib(i);
  fib_sequence(n, f2);
  for(int i=0; i<n; i++) if(f1[i] != f2[i]) printf("%d\n", i);
  for(int i=0; i<n; i++) printf("F%d: %" PRId64 " %" PRId64 "\n", i, f1[i], f2[i]);
}
</code>```

Body:
I want to write a c++ code for calculating Fibonacci numbers in parallel, with a use of OpenMP tools. I know that, with #pragma omp task, the code will be:

int fib(int n) {
int i, j;
if (n<2)
    return n;
else {
    #pragma omp task shared(i)
    i=fib(n-1);
    #pragma omp task shared(j)
    j=fib(n-2);
    #pragma omp taskwait
    return i+j;
    }
}

Computing this way is not cool, since each thread is waiting for its child threads to complete their work, so the whole process is still a sequential!

I want to write the parallel code, using this equation:

F(n + k) = F(n + 1) * F(k) + F(n) * F(k - 1)

Would anyone help me to do this?

Body:
Below is an alternative parallel solution which directly calculates fib(n) and fib(n+1) using the golden ratio and then calculates the rest of the sequence sequentially for each thread. I got the direct solution from rosettacode.

The problem is that the direct calculations overflows for n>72 so this method is almost certainly slower than calculating the first 71 numbers sequentially and in any case 64-bit integers overflows for n>92.

#include <math.h>
#include <stdio.h>
#include <inttypes.h>
#include <omp.h>

uint64_t fib(unsigned m) { // Direct Calculation, correct for abs(m) <= 71
  double sqrt5r =  1.0 / sqrt(5.0);
  double golden = (1.0 + sqrt(5.0))/2.0;
  return rint(pow(golden, m)*sqrt5r);
}

void fib_sequence(unsigned n, uint64_t *f) {
  #pragma omp parallel
  {
    size_t t  = omp_get_thread_num();
    size_t nt = omp_get_num_threads();
    int x0 = (t+0)*n/nt;
    int x1 = (t+1)*n/nt;
    f[x0 + 0] = fib(x0 + 0);
    f[x0 + 1] = fib(x0 + 1);
    for(int i=x0+2; i<x1; i++) {
      f[i] = f[i-2] + f[i-1];
    }
  }
}

int main(void) {
  int n = 71;
  uint64_t f1[n], f2[n];
  for(int i=0; i<n; i++) f1[i] = fib(i);
  fib_sequence(n, f2);
  for(int i=0; i<n; i++) if(f1[i] != f2[i]) printf("%d\n", i);
  for(int i=0; i<n; i++) printf("F%d: %" PRId64 " %" PRId64 "\n", i, f1[i], f2[i]);
}


问:
Log4j2: Programmatically create file appender with timestamp in the filename
There is a possibility to create to add a timestamp to log4j2 logging files using [property] configuration:

```<code>appender.FILE.type = FILE
appender.FILE.name = FILE
appender.FILE.fileName = file-with-date-${date:yyyy-MM-dd}.log
appender.FILE.layout.type = PatternLayout
appender.FILE.layout.pattern =[%p] %m%n
</code>```

This will produce log files in the file-with-date-2017-11-30.log. How can I achieve the same behavior using programmatic configuration? This is what I have tried so far:

```<code>PatternLayout layout = PatternLayout.newBuilder()
            .withConfiguration(ctx.getConfiguration())
            .withPattern("%m%n").build();

FileAppender fileAppender = FileAppender.newBuilder()
        .withLayout(layout)
        .withFileName( "file-with-date-${date:yyyy-MM-dd}.log")
        .withName("pattern")
        .build();
</code>```

But this produces the following file: file-with-date-${date:yyyy-MM-dd}.log. So using properties configuration: a log file with current date is crated, using programmatically created appender ${date:yyyy-MM-dd}.log gets ignored.

答:
Apparently StrSubstitutor can help in this situation. </p>

```<code>final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
String fileName = config.
              getStrSubstitutor().replace("file-with-date-${date:yyyy-MM-dd}.log");

FileAppender fileAppender = FileAppender.newBuilder()
        .withLayout(layout)
        .withFileName(filename)
        .withName("pattern")
        .build();
</code>```

Body:
There is a possibility to create to add a timestamp to log4j2 logging files using [property] configuration:

appender.FILE.type = FILE
appender.FILE.name = FILE
appender.FILE.fileName = file-with-date-${date:yyyy-MM-dd}.log
appender.FILE.layout.type = PatternLayout
appender.FILE.layout.pattern =[%p] %m%n

This will produce log files in the file-with-date-2017-11-30.log. How can I achieve the same behavior using programmatic configuration? This is what I have tried so far:

PatternLayout layout = PatternLayout.newBuilder()
            .withConfiguration(ctx.getConfiguration())
            .withPattern("%m%n").build();

FileAppender fileAppender = FileAppender.newBuilder()
        .withLayout(layout)
        .withFileName( "file-with-date-${date:yyyy-MM-dd}.log")
        .withName("pattern")
        .build();

But this produces the following file: file-with-date-${date:yyyy-MM-dd}.log. So using properties configuration: a log file with current date is crated, using programmatically created appender ${date:yyyy-MM-dd}.log gets ignored.

Body:
Apparently StrSubstitutor can help in this situation.

final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
String fileName = config.
              getStrSubstitutor().replace("file-with-date-${date:yyyy-MM-dd}.log");

FileAppender fileAppender = FileAppender.newBuilder()
        .withLayout(layout)
        .withFileName(filename)
        .withName("pattern")
        .build();


问:
Connecting SFTP server using the certificate
One of our vendor is updating their Server certificate and provided us with the certificate file which when I open gets installed. Not sure where it gets installed. Earlier we were just using the username/password credentials for connecting to the server. But I am trying to check if we can the connect to the SFTP server using the certificates through the SFTP adapter. If so how do I link the SFTP adapter settings with the installed certificates.</p>

答:
For clarity, SFTP does not use Certificates.  The options are U/P with server provider key or Private Key.

So, seems they will be sending you a Private Key File they generate which you can import using the Private Key Property on SFTP Transport Properties.


问:
Firebase : php push notification to multiple devics
i am using following code to send push notifications to one Android device </p>

```<code>function send_notification($message, $token){
    define( 'API_ACCESS_KEY', 'mykey');
     $msg = array
          (
            'body'  =>$message,
            'title' => 'You have a new message ',

          );
    $fields = array
            (
                'to'        => $token,
                'notification'  => $msg
            );

    $headers = array
            (
                'Authorization: key=' . API_ACCESS_KEY,
                'Content-Type: application/json'
            );
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        echo $result;
        curl_close( $ch );
}
</code>```

<p>i am successfully sending it to one device what if i want to send it to multiple device id's where do i have to loop and what format data would be . Please help </p>

答:
try this one :</p>

```<code>for($i=0;$i<count($TokenArray);$i++){
  send_notification($message, $TokenArray[$i]);
}
</code>```

Body:
i am using following code to send push notifications to one Android device

function send_notification($message, $token){
    define( 'API_ACCESS_KEY', 'mykey');
     $msg = array
          (
            'body'  =>$message,
            'title' => 'You have a new message ',

          );
    $fields = array
            (
                'to'        => $token,
                'notification'  => $msg
            );

    $headers = array
            (
                'Authorization: key=' . API_ACCESS_KEY,
                'Content-Type: application/json'
            );
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        echo $result;
        curl_close( $ch );
}

i am successfully sending it to one device what if i want to send it to multiple device id's where do i have to loop and what format data would be . Please help

Body:
try this one :

for($i=0;$i<count($TokenArray);$i++){
  send_notification($message, $TokenArray[$i]);
}


问:
How can I pass some Data from another activity android
I'm trying to pass some data from one activity to another in my android app, however some errors occur when I try to run the code.
I'm passing data this way:

```<code> Intent pod= new Intent(ACTION_NAME);
 Bundle extras = new Bundle();
 extras.putString("nume", NUME_VAL);
 extras.putString("prenume", PRENUME_VAL);
 startActivity(pod);
</code>```

And recive this:

```<code>public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     Bundle data = getIntent().getExtras();
     String nume = data.getStringExtra("nume");
     String prenume = data.getStringExtra("prenume");
}
</code>```

答:
Your error is in how you send.

Add after extras.putString("prenume", PRENUME_VAL); the code:
pod.putExtras(extras);

And to read on the second activity:

```<code>public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     Bundle data = getIntent().getExtras();
     String nume = data.getStringExtra("nume");
     String prenume = data.getStringExtra("prenume");
}
</code>```

Body:
I'm trying to pass some data from one activity to another in my android app, however some errors occur when I try to run the code.
I'm passing data this way:

 Intent pod= new Intent(ACTION_NAME);
 Bundle extras = new Bundle();
 extras.putString("nume", NUME_VAL);
 extras.putString("prenume", PRENUME_VAL);
 startActivity(pod);

And recive this:

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     Bundle data = getIntent().getExtras();
     String nume = data.getStringExtra("nume");
     String prenume = data.getStringExtra("prenume");
}

Body:
Your error is in how you send.

Add after extras.putString("prenume", PRENUME_VAL); the code:
pod.putExtras(extras);

And to read on the second activity:

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     Bundle data = getIntent().getExtras();
     String nume = data.getStringExtra("nume");
     String prenume = data.getStringExtra("prenume");
}


问:
Inflated button has wrong width and height
I'm building a navigation fragment. There is a button which is always present (main button) and others which are dynamically added and removed.

I have a xml resource file from which I inflate a button, change it's icon and add it to the fragments root layout.

Almost everything works, except for the button size. Button size after is 0 (getWidth()/getHeight()).

button_navigation.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/navigation_button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:background="@drawable/icon_test"
    android:backgroundTint="@drawable/selector_bar_button"></Button>
</code>```

inflating code

```<code>Button butt = (Button) inflater.inflate(R.layout.button_navigation, null, false);

buttons.add(butt);
root_view.addView(butt);
</code>```

creating inflater

```<code>public void setParent(MainActivity activity){
        parent = activity;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
</code>```

variables

```<code>MainActivity parent;
LayoutInflater inflater;

int index;

ArrayList<Button> buttons;
Button button_main;
LinearLayout root_view;
</code>```

Main button, has the exact code as button_navigation.xml and occurs in the layout file of the fragment. The main button's size is good.

答: Try using this in your java code button.setLayoutParams (new LayoutParams(60,60);

Body:
I'm building a navigation fragment. There is a button which is always present (main button) and others which are dynamically added and removed.

I have a xml resource file from which I inflate a button, change it's icon and add it to the fragments root layout.

Almost everything works, except for the button size. Button size after is 0 (getWidth()/getHeight()).

button_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/navigation_button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:background="@drawable/icon_test"
    android:backgroundTint="@drawable/selector_bar_button"></Button>

inflating code

Button butt = (Button) inflater.inflate(R.layout.button_navigation, null, false);

buttons.add(butt);
root_view.addView(butt);

creating inflater

public void setParent(MainActivity activity){
        parent = activity;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

variables

MainActivity parent;
LayoutInflater inflater;

int index;

ArrayList<Button> buttons;
Button button_main;
LinearLayout root_view;

Main button, has the exact code as button_navigation.xml and occurs in the layout file of the fragment. The main button's size is good.


问:
Does .beeline serve the same purpose as the .hiverc?
My office is currently transitioning from hive to beeline.

I currently have a .hiverc file that loads some JAR files for me and I would like to transition everything in the .hiverc to beeline if possible.

Currently the only file in my directory that seems relevant is the .beeline (unless I am looking for .beelinerc, haha). Does beeline support what hive supported with the .hiverc file?

.hiverc contents:

```<code>set hive.cli.print.header=true;
set hive.cli.print.current.db=true;
set hive.variable.substitute=true;
set hive.groupby.orderby.position.alias=true;
--set hive.execution.engine=spark;
set hive.execution.engine=mr;
set mapreduce.map.output.compress=true;
set mapreduce.map.output.compress.codec=org.apache.hadoop.io.compress.SnappyCodec;
set hive.exec.compress.intermediate=true;
set hive.exec.compress.output=true;
set hive.auto.convert.join=false;
set mapreduce.map.memory.mb=2048;
set mapreduce.reduce.memory.mb=2048;
set mapreduce.map.java.opts=-Xmx4916m;
set mapreduce.reduce.java.opts=-Xmx4916m;
set mapreduce.task.io.sort.mb=600;
set mapred.reduce.tasks=199;
set hive.exec.dynamic.partition.mode=nonstrict;
set hive.vectorized.execution.enabled=false;
set hive.optimize.sort.dynamic.partition=false;
set hive.optimize.index.filter=false;
set hive.exec.reducers.max=2999;
set hive.exec.orc.default.buffer.size=131072;
set hive.exec.reducers.bytes.per.reducer=64000000;
set hive.exec.orc.default.buffer.size=65536;
set hive.exec.dynamic.partition.mode=nonstrict;
set hive.vectorized.execution.enabled=true;
set hive.optimize.index.filter=false;
set fs.hdfs.impl.disable.cache=false;
--
set mapreduce.job.queuename=Three;
set mapred.job.queue.name=Three;
--add jar hdfs:///user/user_A/esri/spatial-sdk-hadoop.jar;
add jar hdfs:///user/user_A/esri/esri-geometry-api.jar;
add jar hdfs:///user/user_A/esri/spatial-sdk-hive-1.1.1-SNAPSHOT.jar;
add jar hdfs:///user/user_A/esri/spatial-sdk-json-1.1.1-SNAPSHOT.jar;
source /home/user_A/esri/function-ddl.sql;
add jar /home/edpintdatp/jobs/data_ingestion/thirdpartyjars/json-serde-1.3.1.jar;
add jar hdfs:///user/user_A/esri/brickhouse-0.7.1-SNAPSHOT.jar;
source /home/user_A/esri/brickhouse.sql;
</code>```

答:
Use the beeline command line option -i as shown below for initialization.

```<code>beeline -i ~/.hiverc -u jdbc:hive2://hiveserver2.com:10000 $USER org.apache.hive.jdbc.HiveDriver
</code>```

Refer this wiki link

Body:
My office is currently transitioning from hive to beeline.

I currently have a .hiverc file that loads some JAR files for me and I would like to transition everything in the .hiverc to beeline if possible.

Currently the only file in my directory that seems relevant is the .beeline (unless I am looking for .beelinerc, haha). Does beeline support what hive supported with the .hiverc file?

.hiverc contents:

set hive.cli.print.header=true;
set hive.cli.print.current.db=true;
set hive.variable.substitute=true;
set hive.groupby.orderby.position.alias=true;
--set hive.execution.engine=spark;
set hive.execution.engine=mr;
set mapreduce.map.output.compress=true;
set mapreduce.map.output.compress.codec=org.apache.hadoop.io.compress.SnappyCodec;
set hive.exec.compress.intermediate=true;
set hive.exec.compress.output=true;
set hive.auto.convert.join=false;
set mapreduce.map.memory.mb=2048;
set mapreduce.reduce.memory.mb=2048;
set mapreduce.map.java.opts=-Xmx4916m;
set mapreduce.reduce.java.opts=-Xmx4916m;
set mapreduce.task.io.sort.mb=600;
set mapred.reduce.tasks=199;
set hive.exec.dynamic.partition.mode=nonstrict;
set hive.vectorized.execution.enabled=false;
set hive.optimize.sort.dynamic.partition=false;
set hive.optimize.index.filter=false;
set hive.exec.reducers.max=2999;
set hive.exec.orc.default.buffer.size=131072;
set hive.exec.reducers.bytes.per.reducer=64000000;
set hive.exec.orc.default.buffer.size=65536;
set hive.exec.dynamic.partition.mode=nonstrict;
set hive.vectorized.execution.enabled=true;
set hive.optimize.index.filter=false;
set fs.hdfs.impl.disable.cache=false;
--
set mapreduce.job.queuename=Three;
set mapred.job.queue.name=Three;
--add jar hdfs:///user/user_A/esri/spatial-sdk-hadoop.jar;
add jar hdfs:///user/user_A/esri/esri-geometry-api.jar;
add jar hdfs:///user/user_A/esri/spatial-sdk-hive-1.1.1-SNAPSHOT.jar;
add jar hdfs:///user/user_A/esri/spatial-sdk-json-1.1.1-SNAPSHOT.jar;
source /home/user_A/esri/function-ddl.sql;
add jar /home/edpintdatp/jobs/data_ingestion/thirdpartyjars/json-serde-1.3.1.jar;
add jar hdfs:///user/user_A/esri/brickhouse-0.7.1-SNAPSHOT.jar;
source /home/user_A/esri/brickhouse.sql;

Body:
Use the beeline command line option -i as shown below for initialization.

beeline -i ~/.hiverc -u jdbc:hive2://hiveserver2.com:10000 $USER org.apache.hive.jdbc.HiveDriver

Refer this wiki link


问:
Error when installing NUnit 3.9 in Visual Studio 13 with NuGet
I am trying to install NUnit 3.9 in Visual Studio 13 Professional, but I am facing the below mentioned error while installing:

```<code>'NUnit' already has a dependency defined for 'NETStandard.Library'.
</code>```

How do I solve this issue?

答:
This error is often caused by the fact that your version of NuGet is too old. Try updating NuGet.

NUnit's most recent NuGet packages include .NET Standard builds, which mean NuGet client version 2.12 or later is required. From the next version of NUnit, you'll get a more helpful error message for this.

Body:
I am trying to install NUnit 3.9 in Visual Studio 13 Professional, but I am facing the below mentioned error while installing:

'NUnit' already has a dependency defined for 'NETStandard.Library'.

How do I solve this issue?


问:
Magento 2 Get Customer's Telephone after registration
I am new to Magento2 and I was wondering if someone could help me echo out Customer's Address information in an activation email to Admin.  Below is the code I am using to build the Customer's information.

```<code>->setTemplateVars(
            [
                'email' => $customer->getEmail(),
                'firstname' => $customer->getFirstname(),
                'lastname' => $customer->getLastname(),
                'company' => $customer->getAddress()->getCompany(), //DOESN'T WORK!!
                'telephone' => $customer->getAddress()->getTelephone(), //DOESN'T WORK!!
                'taxvat' => $customer->getTaxvat(),
                'website' => $customer->getCustomAttribute('website')->getValue(),
            ]
        );
</code>```

Email, Firstname, Lastname, TaxVat and Custom Attribute "Website" are all working and showing properly on my email.  However, I can't get the information for Company Name, Telephone, Address, etc.

I would appreciate it if anyone could help point me in the right direction.

答:
To get customer phone number and company info you need to used this things.</p>

```<code>$customer->getDefaultShippingAddress()->getTelephone(); // For Telephone

$customer->getDefaultShippingAddress()->getCompany(); // For Company
</code>```

Body:
I am new to Magento2 and I was wondering if someone could help me echo out Customer's Address information in an activation email to Admin.  Below is the code I am using to build the Customer's information.

->setTemplateVars(
            [
                'email' => $customer->getEmail(),
                'firstname' => $customer->getFirstname(),
                'lastname' => $customer->getLastname(),
                'company' => $customer->getAddress()->getCompany(), //DOESN'T WORK!!
                'telephone' => $customer->getAddress()->getTelephone(), //DOESN'T WORK!!
                'taxvat' => $customer->getTaxvat(),
                'website' => $customer->getCustomAttribute('website')->getValue(),
            ]
        );

Email, Firstname, Lastname, TaxVat and Custom Attribute "Website" are all working and showing properly on my email.  However, I can't get the information for Company Name, Telephone, Address, etc.

I would appreciate it if anyone could help point me in the right direction.

Body:
To get customer phone number and company info you need to used this things.

$customer->getDefaultShippingAddress()->getTelephone(); // For Telephone

$customer->getDefaultShippingAddress()->getCompany(); // For Company


问:
Detect if the device is iPhone X
My iOS app uses a custom height for the UINavigationBar which leads to some problems on the new iPhone X.

Does someone already know how to reliable detect programmatically (in Objective-C) if an app is running on iPhone X?

EDIT:

Of course checking the size of the screen is possible, however, I wonder if there is some "build in" method like TARGET_OS_IPHONE to detect iOS...

```<code>if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    if (screenSize.height == 812)
        NSLog(@"iPhone X");
}
</code>```

EDIT 2:

I do not think, that my question is a duplicate of the linked question. Of course, there are methods to "measure" different properties of the current device and to use the results to decide which device is used. However, this was not the actual point of my question as I tried to emphasize in my first edit.

The actual question is: "Is it possible to directly detect if the current device is an iPhone X (e.g. by some SDK feature) or do I have to use indirect measurements"?

By the answers given so far, I assume that the answer is "No, there is no direct methods. Measurements are the way to go".

答:
I elaborated on your's on else's answers and made swift extension on UIDevice. I like swift enums and "everything in order" & atomized. I've created solution that works both on device & simulator.

Advantages:
- simple interface, usage e.g. UIDevice.current.isIPhoneX
- UIDeviceModelType enum gives you ability to easily extend model specific features and constants that you want to use in your app, e.g. cornerRadius

Disadvantage:
- it's model specific solution, not resolution specific - e.g. if Apple will produce another model with the same specs, this won't work correctly and you need to add another model in order to make this work => you need to update your app.

extension UIDevice {

    enum UIDeviceModelType : Equatable {

        ///iPhoneX
        case iPhoneX

        ///Other models
        case other(model: String)

        static func type(from model: String) -> UIDeviceModelType {
            switch model {
            case "iPhone10,3", "iPhone10,6":
                return .iPhoneX
            default:
                return .other(model: model)
            }
        }

        static func ==(lhs: UIDeviceModelType, rhs: UIDeviceModelType) -> Bool {
            switch (lhs, rhs) {
            case (.iPhoneX, .iPhoneX):
                return true
            case (.other(let modelOne), .other(let modelTwo)):
                return modelOne == modelTwo
            default:
                return false
            }
        }
    }

    var simulatorModel: String? {
        guard TARGET_OS_SIMULATOR != 0 else {
            return nil
        }

        return ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"]
    }

    var hardwareModel: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let model = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }

        return model
    }

    var modelType: UIDeviceModelType {
        let model = self.simulatorModel ?? self.hardwareModel
        return UIDeviceModelType.type(from: model)
    }

    var isIPhoneX: Bool {
        return modelType == .iPhoneX
    }
}
```

Title: Detect if the device is iPhone X

Body:
My iOS app uses a custom height for the UINavigationBar which leads to some problems on the new iPhone X.

Does someone already know how to reliable detect programmatically (in Objective-C) if an app is running on iPhone X?

EDIT:

Of course checking the size of the screen is possible, however, I wonder if there is some "build in" method like TARGET_OS_IPHONE to detect iOS...

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    if (screenSize.height == 812)
        NSLog(@"iPhone X");
}

EDIT 2:

I do not think, that my question is a duplicate of the linked question. Of course, there are methods to "measure" different properties of the current device and to use the results to decide which device is used. However, this was not the actual point of my question as I tried to emphasize in my first edit.

The actual question is: "Is it possible to directly detect if the current device is an iPhone X (e.g. by some SDK feature) or do I have to use indirect measurements"?

By the answers given so far, I assume that the answer is "No, there is no direct methods. Measurements are the way to go".


答:
```<code>//Sending Data to another activity
Intent intent= new Intent(ACTION_NAME);
intent.putString("nume", NUME_VAL);
intent.putString("prenume", PRENUME_VAL);
startActivity(pod);
</code>```

<p>//Retrieving Data</p>

```<code>Bundle data = getIntent().getExtras();
String nume = data.getStringExtra("nume");
String prenume = data.getStringExtra("prenume");
</code>```

Title: How can I pass some Data from another activity android

Body:
//Sending Data to another activity
Intent intent= new Intent(ACTION_NAME);
intent.putString("nume", NUME_VAL);
intent.putString("prenume", PRENUME_VAL);
startActivity(pod);

//Retrieving Data

Bundle data = getIntent().getExtras();
String nume = data.getStringExtra("nume");
String prenume = data.getStringExtra("prenume");


问:
Using React Component Library in an Angular 4 application
I have an Angular 4 application, implemented using the redux architecture with this library https://github.com/ngrx/platform. I want to use some custom React components in my app. My guess is that I would have to rewrite my large Angular components into React components, as it would not be possible to embed a custom React library into already existing Angular components. Also, considering that I have not used the framework agnostic redux library, I would need to rewrite that part of my app as well, basically amounting to a whole rewrite. Am I correct in my assessment?    </p>

答:
You can use ReactDOM.render() to render react components inside of your angular components, or alongside them. As for the ngrx issue you can probably implement some middleware or an Angular service that can provide data to your react components. You could even make an Angular component to wrap your react components and pass them props from the ngrx store. You could also use portals in your react components to accomplish a similar goal.

This may not be the most performant solution (rewriting will almost always work better) but if you just want the functionality and the performance cost isn't too bad it should be fairly simple to implement.


问:
I am using pactnet and want to post the contract to pack broker
I am having a pact file generated by using pactNet(I am a C# programmer), now how do I post the pact file to pact-broker.
I have done a lot of reading using Curl, ruby and java (with Gradle) for this purpose but did not see anything equivalent for C#.
Is there anyone achieve this before and any guidance is appreciated.. </p>

答:
Check PactNet documentation:

```<code>var pactPublisher = new PactPublisher("http://test.pact.dius.com.au", new PactUriOptions("username", "password"));
pactPublisher.PublishToBroker(
    "..\\..\\..\\Samples\\EventApi\\Consumer.Tests\\pacts\\event_api_consumer-event_api.json",
    "1.0.2", new [] { "master" });
</code>```

I think you should consider publishing pacts as a CI task of Consumer's build.

Body:
Check PactNet documentation:

var pactPublisher = new PactPublisher("http://test.pact.dius.com.au", new PactUriOptions("username", "password"));
pactPublisher.PublishToBroker(
    "..\\..\\..\\Samples\\EventApi\\Consumer.Tests\\pacts\\event_api_consumer-event_api.json",
    "1.0.2", new [] { "master" });

I think you should consider publishing pacts as a CI task of Consumer's build.


问:
PHP session lost after redirect
How do I resolve the problem of losing a session after a redirect in PHP?

Recently, I encountered a very common problem of losing session after redirect. And after searching through this website I can still find no solution (although this came the closest).

Update

I have found the answer and I thought I'd post it here to help anyone experiencing the same problem.

答:
First of all, make sure you are calling session_start() before using $_SESSION variable.

If you have disabled error reporting, try to turn in on and see the result.

```<code>ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
</code>```

The most common reasons that aren't mentioned in @dayuloli's answer:

Disk space problem. Make sure your disk space is not full, you need some space to store session files.

Session directory may not be writable. You can check it with is_writable(session_save_path())

Title: PHP session lost after redirect

Body:
First of all, make sure you are calling session_start() before using $_SESSION variable.

If you have disabled error reporting, try to turn in on and see the result.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

The most common reasons that aren't mentioned in @dayuloli's answer:

Disk space problem. Make sure your disk space is not full, you need some space to store session files.

Session directory may not be writable. You can check it with is_writable(session_save_path())


问:
column headers in SAS datasets
My supervisor sent me a SAS dataset. I opened it in SAS and found that the headers shown are long variable labels instead of variable names. How can I change the headers from variable labels to variable names? I  know how to get variable names by 'proc contents' procedure, but I do not know how to let SAS display a dataset with variable names whenever I open the dataset in SAS.</p>

答: The fast and dirty way is to submit "options nolabel;", meaning that SAS will generally ignore labels. You can always switch back by submitting "options label;"</p>

Title: column headers in SAS datasets


问:
localStorage item not updating in axios headers
I am using a JWT Token auth system, and when I login I get the token like this:

```<code>axios.post('/login', data)
    .then(response => {
        localStorage.setItem('token', response.data.token);
   });
</code>```

This works well and the token is saved in localStorage. However, the token is not included in the later requests. The Authorization header is Bearer null.

This is how I set up my global axios object.

```<code>window.axios = axios.create({
    baseURL: '/api/',
    timeout: 10000,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
        'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
});
</code>```

If I refresh the site, the token is set, and is used properly.

Edit:

I got it to work by removing the Authorization header from the create() method and instead using window.axios.defaults.headers.common['Authorization']. But now the same problem appears with Laravel Echo. I create the instance like this:

```<code>window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'xxx',
    cluster: 'eu',
    encrypted: true,
    namespace: 'xxx',
    auth: {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
    }
});
</code>```

And I update the header like this:

```<code>window.setAuthToken = (token) => {
    window.axios.defaults.headers.Authorization = 'Bearer ' + token;
    window.Echo.options.auth.headers.Authorization = 'Bearer ' + token;
    localStorage.setItem('token', token);
}
</code>```

The axios header is successfully updated, but not Echo.

答:
The problem is that your are using localStorage.getItem('token') at page load. When  you are setting it in localStorage, you have to update it in axios header.

```<code>window.axios = axios.create({
    baseURL: '/api/',
    timeout: 10000,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
        'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
});

axios.post('/login', data)
    .then(response => {
        localStorage.setItem('token', response.data.token);
        window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token');
    });
</code>```

Body:
I am using a JWT Token auth system, and when I login I get the token like this:

axios.post('/login', data)
    .then(response => {
        localStorage.setItem('token', response.data.token);
   });

This works well and the token is saved in localStorage. However, the token is not included in the later requests. The Authorization header is Bearer null.

This is how I set up my global axios object.

window.axios = axios.create({
    baseURL: '/api/',
    timeout: 10000,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
        'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
});

If I refresh the site, the token is set, and is used properly.

Edit:

I got it to work by removing the Authorization header from the create() method and instead using window.axios.defaults.headers.common['Authorization']. But now the same problem appears with Laravel Echo. I create the instance like this:

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'xxx',
    cluster: 'eu',
    encrypted: true,
    namespace: 'xxx',
    auth: {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
    }
});

And I update the header like this:

window.setAuthToken = (token) => {
    window.axios.defaults.headers.Authorization = 'Bearer ' + token;
    window.Echo.options.auth.headers.Authorization = 'Bearer ' + token;
    localStorage.setItem('token', token);
}

The axios header is successfully updated, but not Echo.

Body:
The problem is that your are using localStorage.getItem('token') at page load. When  you are setting it in localStorage, you have to update it in axios header.

window.axios = axios.create({
    baseURL: '/api/',
    timeout: 10000,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
        'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
});

axios.post('/login', data)
    .then(response => {
        localStorage.setItem('token', response.data.token);
        window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token');
    });


问:
How do I pass arguments to bash?
So I am writing a bash script which will decrypt a file so I what the syntax of the the command to be decrypt [file.jpg]
 So far this is my script :

```<code>openssl enc -d -aes-256-cbc -in file.jpg > file
 echo "Please make sure you add the correct extension to
the file."
</code>```

Spent a lot time trying to achieve my goal but it doest work so I would like some help. Like suppose the file name is movie.mov I should be able to decrypt it using decrypt movie.mov or any other file.

EDIT: Thanks for all your answer but I found the answer which I approved to be simple and sorry I can't approve multiple answer all the answer give some new information!

答:
You can access parameters inside a bash script using the variables $1, $2, $3. $1 is the first argument, $2 the second ...

If you run

```<code>decrypt file.jpg
</code>```

You can access file.jpg in your bash script with following code:

```<code>openssl enc -d -aes-256-cbc -in $1 > file
echo "Please make sure you add the correct extension to the file."
</code>```

Title: How do I pass arguments to bash?

Body:
So I am writing a bash script which will decrypt a file so I what the syntax of the the command to be decrypt [file.jpg]
 So far this is my script :

openssl enc -d -aes-256-cbc -in file.jpg > file
 echo "Please make sure you add the correct extension to
the file."

Spent a lot time trying to achieve my goal but it doest work so I would like some help. Like suppose the file name is movie.mov I should be able to decrypt it using decrypt movie.mov or any other file.

EDIT: Thanks for all your answer but I found the answer which I approved to be simple and sorry I can't approve multiple answer all the answer give some new information!

Body:
You can access parameters inside a bash script using the variables $1, $2, $3. $1 is the first argument, $2 the second ...

If you run

decrypt file.jpg

You can access file.jpg in your bash script with following code:

openssl enc -d -aes-256-cbc -in $1 > file
echo "Please make sure you add the correct extension to the file."


问:
Serialize and Deserialize Date to Bean in Java
I've to projects: an API Rest named Usuario and a JEE Application named store. Store gets the information to work from the Usuario API.

All the information is sent and received using MediaType.APPLICATION_JSON_TYPE.

In the API there's the Evento entity, which has the next attribute: Date fecha.
In the JEE Application there's the Evento bean, which has the next attribute: Date fecha.

When the API sends any object of the Evento class, it sends the Date with the format yyyy-MM-dd HH:mm: {"Date":"2017-12-06 23:02"}.

The JEE Application uses Client and WebTarget to use de API and get the information.

The problem here is that fecha (of type Date) in the evento object is null. It's not well-deserialized.

I can not use Spring on the JEE Application.I'm using JAX-RS in the store application.

Could you help me, please?

答:
Let's clarify some facts, first. (I'm not 100% sure, though.)

There is no standard rule for representing dates or instants in JSON.

Some uses millisecons while others some formatted strings such as ISOZ.

There is no standard rule for serializing/deserializing in Java EE.

It only works as underlying message provider for application/json.

Note that JSON-B may not available in the spec yet.

Let's say we have this entity.

```<code>// I really want to know what Evento/fatcha means.
// Are they Italian words?
@XmlRootElement
@Entity
public class Evento implements Serializable {

    public Date getFetcha() {
        return ofNullable(fetcha)
                .map(v -> new Date(v.getTime()))
                .orElse(null);
    }

    public void setFetcha(final Date fetcha) {
        this.fetcha = ofNullable(fetcha)
                .map(v -> new Date(v.getTime()))
                .orElse(null);
    }

    @XmlElement
    @Temporal(TIMESTAMP)
    private Date fetcha;
}
</code>```

Now we can't help but depends on the underlying MessageReader or MessageWriter for serializing/deserializing in application/json.

Jackson will work in some way while MOXy will work in its way.

The only way to push client is that, they should use the format exactly as the same format when they GET the resource.

One way that I use is using another property for unified formatting/parsing.

```<code>@XmlRootElement
@Entity
public class Evento implements Serializable {

    // ...

    @JsonProperty
    @JsonbProperty
    @XmlElement
    public String getFetchaIsoz() {
        return ofNullable(getFetcha())
                .map(Date::toInstant)
                .map(DateTimeFormatter.ISO_INSTANT:format)
                .orElse(null);
    }

    public void setFetchaIsoz(final String fetchaIsoz) {
        setFetcha(ofNullable(fetchaIsoz)
                .map(DateTimeFormatter.ISO_INSTANT:parse)
                .map(Instant::from)
                .map(Date::from)
                orElse(null));
    }

    @JsonIgnore // just in case, e.g. Spring?
    @JsonbTransient
    @XmlTransient
    @Temporal(TIMESTAMP)
    private Date fetcha;
}
</code>```

Not we have an alternative property which guarantees to work in specific format.

Body:
Let's clarify some facts, first. (I'm not 100% sure, though.)

There is no standard rule for representing dates or instants in JSON.

Some uses millisecons while others some formatted strings such as ISOZ.

There is no standard rule for serializing/deserializing in Java EE.

It only works as underlying message provider for application/json.

Note that JSON-B may not available in the spec yet.

Let's say we have this entity.

// I really want to know what Evento/fatcha means.
// Are they Italian words?
@XmlRootElement
@Entity
public class Evento implements Serializable {

    public Date getFetcha() {
        return ofNullable(fetcha)
                .map(v -> new Date(v.getTime()))
                .orElse(null);
    }

    public void setFetcha(final Date fetcha) {
        this.fetcha = ofNullable(fetcha)
                .map(v -> new Date(v.getTime()))
                .orElse(null);
    }

    @XmlElement
    @Temporal(TIMESTAMP)
    private Date fetcha;
}

Now we can't help but depends on the underlying MessageReader or MessageWriter for serializing/deserializing in application/json.

Jackson will work in some way while MOXy will work in its way.

The only way to push client is that, they should use the format exactly as the same format when they GET the resource.

One way that I use is using another property for unified formatting/parsing.

@XmlRootElement
@Entity
public class Evento implements Serializable {

    // ...

    @JsonProperty
    @JsonbProperty
    @XmlElement
    public String getFetchaIsoz() {
        return ofNullable(getFetcha())
                .map(Date::toInstant)
                .map(DateTimeFormatter.ISO_INSTANT:format)
                .orElse(null);
    }

    public void setFetchaIsoz(final String fetchaIsoz) {
        setFetcha(ofNullable(fetchaIsoz)
                .map(DateTimeFormatter.ISO_INSTANT:parse)
                .map(Instant::from)
                .map(Date::from)
                orElse(null));
    }

    @JsonIgnore // just in case, e.g. Spring?
    @JsonbTransient
    @XmlTransient
    @Temporal(TIMESTAMP)
    private Date fetcha;
}

Not we have an alternative property which guarantees to work in specific format.


问:
H2O Import files via REST API from local server fails
I am trying to use h2o REST API to import CSV files that I have on my local server.

Command:

curl -v -X GET
  'http://127.0.0.1:54321/3/ImportFiles?path=http://127.0.0.1:8083/datasets/tables/csv/RDsTWgcvAjHeWJFnbhCKTCE5rn6aLCjJ.csv'

Result in following log:

Trying 127.0.0.1... Connected to 127.0.0.1 (127.0.0.1) port 54321 (#0)
  GET
  /3/ImportFiles?path=http://127.0.0.1:8083/datasets/tables/csv/RDsTWgcvAjHeWJFnbhCKTCE5rn6aLCjJ.csv HTTP/1.1 Host: 127.0.0.1:54321 User-Agent: curl/7.47.0 Accept: /

  HTTP/1.1 200 OK X-h2o-build-project-version: 3.16.0.2
  X-h2o-rest-api-version-max: 3 X-h2o-cluster-id: 1512722051559
  X-h2o-cluster-good: true X-h2o-context-path: / Content-Type:
  application/json Content-Length: 349 Server: Jetty(8.y.z-SNAPSHOT)

  Connection #0 to host 127.0.0.1 left intact
  {"__meta":{"schema_version":3,"schema_name":"ImportFilesV3","schema_type":"ImportFiles"},"_exclude_fields":"","path":"http://127.0.0.1:8083/datasets/tables/csv/RDsTWgcvAjHeWJFnbhCKTCE5rn6aLCjJ.csv","pattern":null,"files":[],"destination_frames":[],"fails":["http://127.0.0.1:8083/datasets/tables/csv/RDsTWgcvAjHeWJFnbhCKTCE5rn6aLCjJ.csv"],"dels":[]}

H2O log on TRACE level shows only:

12-08 15:41:59.951 10.8.128.101:54321    36013  #4756-331 INFO: GET
  /3/ImportFiles, parms:
  {path=http://127.0.0.1:8083/datasets/tables/csv/RDsTWgcvAjHeWJFnbhCKTCE5rn6aLCjJ.csv}

Is there any way to debug while importing fails? h2o does not asking local server at all.

Commands from other servers work well:

curl -v -X GET "http://127.0.0.1:54321/3/ImportFiles?path=http://s3.amazonaws.com/h2o-public-test-data/smalldata/flow_examples/arrhythmia.csv.gz"
  curl -v -X GET "https://raw.github.com/h2oai/h2o/master/smalldata/logreg/prostate.csv"

答:
In general, trying to interact directly with the H2O REST API isn't easy.  The vast majority of people use a pre-made API client like Python or R.

But if you really want to do this, I would debug it by comparing with something that's working.  Like the R client for H2O.

Write an R program that does this:

```<code>h2o.init()
h2o.startLogging()
h2o.importFile("/path/to/data.csv")
</code>```

The startLogging() call will produce a detailed log file with all the REST API requests and responses.  Look at that and try to mimic it.

You can also refer to the autogenerated REST API documentation (http://docs.h2o.ai/h2o/latest-stable/h2o-docs/rest-api-reference.html), but I would caution that if you tried to write a working client just based on the docs it would be hard.

Looking at a logged conversation from an already working client is by far your best bet.

Body:
In general, trying to interact directly with the H2O REST API isn't easy.  The vast majority of people use a pre-made API client like Python or R.

But if you really want to do this, I would debug it by comparing with something that's working.  Like the R client for H2O.

Write an R program that does this:

h2o.init()
h2o.startLogging()
h2o.importFile("/path/to/data.csv")

The startLogging() call will produce a detailed log file with all the REST API requests and responses.  Look at that and try to mimic it.

You can also refer to the autogenerated REST API documentation (http://docs.h2o.ai/h2o/latest-stable/h2o-docs/rest-api-reference.html), but I would caution that if you tried to write a working client just based on the docs it would be hard.

Looking at a logged conversation from an already working client is by far your best bet.


问:
Visual Studio Online Continuous integration, Turn on/off customErrors Azure in different environments
Three environments, where I want different settings:

Production (Azure Web App) CustomErrors ON

QA (Azure Web App) CustomErrors OFF

Development (Visual Studio, run debug mode) CustomErrors OFF

In web.config.release, I can configure a transformation, that is used when Visual Studio Online deploys/releases to an environment.

But how do I make a different setting for customerrors in one environment?

I think it either has to be solved in the visual studio release definitionfor each environment, or as an application setting in the azure web app.

How can I do this?

答:
The easiest way is to use Azure App Service Deploy task and enable the option XML Variable Substitution. This allows you to specify the variable values in your Release Definition and configure different values for each environment. On deployment, the task will then search and replace the values in your web.config with your specified values.

For more information see Managing Configuration and App Settings for Multiple Environments in Your CD Pipeline


答:
Arguments on bash script are received with $1 for first arg, $2 for second etc...

So your script should looks like

```<code>openssl enc -d -aes-256-cbc -in $1 > file
</code>```

See here

Title: How do I pass arguments to bash?

Body:
Arguments on bash script are received with $1 for first arg, $2 for second etc...

So your script should looks like

openssl enc -d -aes-256-cbc -in $1 > file

See here


问:
Access Strucuture Sensor via OpenNI 2 from UWP App targeting Windows 10
I'd like to access the Structure Sensor (https://structure.io) via OpenNI 2 (https://github.com/occipital/openni2) from an UWP App running on a Windows 10 Desktop.

The Setup

For this very reason I created a Windows Runtime Component (Universal Windows) in C++ besides my actual UWP App. This component exports several functions basically miming the initialization behavior of one of the samples in above OpenNI Github repo.

I extended the code to also iterate through all available devices:

```<code>// Initialize OpenNI
Status rc = OpenNI::initialize();
if (rc != STATUS_OK)
{
    logError("Initialize failed + " + std::string(OpenNI::getExtendedError()));
    return false;
}

// Get all attached sensors supported by OpenNI
Array<DeviceInfo> deviceList;
OpenNI::enumerateDevices(&deviceList);

for (int i = 0; i < deviceList.getSize(); i++) {
    logInfo(deviceList[i].getName());
    logInfo(deviceList[i].getUri());
}

// Actual open device
Device device;
rc = device.open(deviceList[0].getUri());
if (rc != STATUS_OK)
{
    logError("Error = " + to_string(rc));
    logError("Couldn't open device " + std::string(OpenNI::getExtendedError()));
    return false;
}
</code>```

The Problem

Calling above code from my UWP app through the Windows Runtime Component is successful when initializing OpenNI and enumerating over all available devices:

```<code>[INFO] PS1080
[INFO] \\?\usb#vid_1d27&pid_0600#13261#{c3b5f022-5a42-1980-1909-ea72095601b1}
</code>```

Actually Opening the device via device.open is the actual problem (Error 1 = STATUS_ERROR)

```<code>[ERROR] Error = 1
[ERROR] Couldn't open device    Could not open "\\?\usb#vid_1d27&pid_0600#13261#{c3b5f022-5a42-1980-1909-ea72095601b1}": USB device not found!
</code>```

I'm also under the impression that above error message is a bit misleading, as the actual message when having no device attached is:

```<code>[ERROR] Error = 1
[ERROR] Couldn't open device    DeviceOpen using default: no devices found
</code>```

I already tried to add a USB device capability to the package mainifest without any success.

```<code><DeviceCapability Name="usb">
  <Device Id="vidpid:1D27 0600">
    <!--<Function Type="classId:ff * *" />-->
    <Function Type="name:vendorSpecific"/>
  </Device>
</DeviceCapability>
</code>```

I also verified that above code is working when directly building a classic C++ program without targeting UWP at all.

I would be very happy for any direction/hint you can provide me with

答:
The Solution

Microsoft's UWP policy simply doesn't allow access to USB devices. But you can workaround that by grant the UWP AppContainer Process access to the Structure IO sensor.

Some manual work is required though:

Open the registry editor and go to the USB entry of the Structure IO sensor HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Enum\USB\VID_1D27&PID_0600

Uncollapse this node and right click on the node below this one and copy the whole key in to clipboard. The last digit is very important here and differs from machine to machine (e.g. HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Enum\USB\VID_1D27&PID_0600\13261)

Copy this key into following registry file where the brackets are. The following registry modification basically allows every UWP app access to the structure I/O sensor.

```<code>Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Enum\USB\VID_1D27&PID_0600\13261]
"Security"=hex:1,0,4,90,0,0,0,0,0,0,0,0,0,0,0,0,14,0,0,0,2,0,60,0,4,0,0,0,0,0,14,0,0,0,0,10,1,1,0,0,0,0,0,5,12,0,0,0,0,0,18,0,0,0,0,10,1,2,0,0,0,0,0,5,20,0,0,0,20,2,0,0,0,0,14,0,0,0,0,10,1,1,0,0,0,0,0,5,B,0,0,0,0,0,18,0,0,0,0,10,1,2,0,0,0,0,0,F,2,0,0,0,1,0,0,0
</code>```

Modify the following batch script to point to the full path(!) of above registry file. This script is needed to modify the registry with the security string. This is only allowed by Window's SYSTEM account. That's why we need to create a task for that.

```<code>call schtasks /create /RU SYSTEM /SC ONCE /TN DeviceAC /TR "reg import c:\full\path\to\registry\file.reg" /ST 00:00
call schtasks /run /tn DeviceAC
call schtasks /delete /tn DeviceAC /f
</code>```

Run the above batch script with Administrator privileges

After successfully executing the script, make sure there's a new entry called "Security" below you node from 2.

If the sensor is already connected to your PC you'll need to reconnect it.

Now the code from my Question above should work :)

You'll find a detailed read on how to solve this problem here:
https://developer.microsoft.com/en-us/windows/iot/Samples/CustomDeviceAccessor

Body:
I'd like to access the Structure Sensor (https://structure.io) via OpenNI 2 (https://github.com/occipital/openni2) from an UWP App running on a Windows 10 Desktop.

The Setup

For this very reason I created a Windows Runtime Component (Universal Windows) in C++ besides my actual UWP App. This component exports several functions basically miming the initialization behavior of one of the samples in above OpenNI Github repo.

I extended the code to also iterate through all available devices:

// Initialize OpenNI
Status rc = OpenNI::initialize();
if (rc != STATUS_OK)
{
    logError("Initialize failed + " + std::string(OpenNI::getExtendedError()));
    return false;
}

// Get all attached sensors supported by OpenNI
Array<DeviceInfo> deviceList;
OpenNI::enumerateDevices(&deviceList);

for (int i = 0; i < deviceList.getSize(); i++) {
    logInfo(deviceList[i].getName());
    logInfo(deviceList[i].getUri());
}

// Actual open device
Device device;
rc = device.open(deviceList[0].getUri());
if (rc != STATUS_OK)
{
    logError("Error = " + to_string(rc));
    logError("Couldn't open device " + std::string(OpenNI::getExtendedError()));
    return false;
}

The Problem

Calling above code from my UWP app through the Windows Runtime Component is successful when initializing OpenNI and enumerating over all available devices:

[INFO] PS1080
[INFO] \\?\usb#vid_1d27&pid_0600#13261#{c3b5f022-5a42-1980-1909-ea72095601b1}

Actually Opening the device via device.open is the actual problem (Error 1 = STATUS_ERROR)

[ERROR] Error = 1
[ERROR] Couldn't open device    Could not open "\\?\usb#vid_1d27&pid_0600#13261#{c3b5f022-5a42-1980-1909-ea72095601b1}": USB device not found!

I'm also under the impression that above error message is a bit misleading, as the actual message when having no device attached is:

[ERROR] Error = 1
[ERROR] Couldn't open device    DeviceOpen using default: no devices found

I already tried to add a USB device capability to the package mainifest without any success.

<DeviceCapability Name="usb">
  <Device Id="vidpid:1D27 0600">

    <Function Type="name:vendorSpecific"/>
  </Device>
</DeviceCapability>

I also verified that above code is working when directly building a classic C++ program without targeting UWP at all.

I would be very happy for any direction/hint you can provide me with

Body:
The Solution

Microsoft's UWP policy simply doesn't allow access to USB devices. But you can workaround that by grant the UWP AppContainer Process access to the Structure IO sensor.

Some manual work is required though:

Open the registry editor and go to the USB entry of the Structure IO sensor HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Enum\USB\VID_1D27&PID_0600

Uncollapse this node and right click on the node below this one and copy the whole key in to clipboard. The last digit is very important here and differs from machine to machine (e.g. HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Enum\USB\VID_1D27&PID_0600\13261)

Copy this key into following registry file where the brackets are. The following registry modification basically allows every UWP app access to the structure I/O sensor.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Enum\USB\VID_1D27&PID_0600\13261]
"Security"=hex:1,0,4,90,0,0,0,0,0,0,0,0,0,0,0,0,14,0,0,0,2,0,60,0,4,0,0,0,0,0,14,0,0,0,0,10,1,1,0,0,0,0,0,5,12,0,0,0,0,0,18,0,0,0,0,10,1,2,0,0,0,0,0,5,20,0,0,0,20,2,0,0,0,0,14,0,0,0,0,10,1,1,0,0,0,0,0,5,B,0,0,0,0,0,18,0,0,0,0,10,1,2,0,0,0,0,0,F,2,0,0,0,1,0,0,0

Modify the following batch script to point to the full path(!) of above registry file. This script is needed to modify the registry with the security string. This is only allowed by Window's SYSTEM account. That's why we need to create a task for that.

call schtasks /create /RU SYSTEM /SC ONCE /TN DeviceAC /TR "reg import c:\full\path\to\registry\file.reg" /ST 00:00
call schtasks /run /tn DeviceAC
call schtasks /delete /tn DeviceAC /f

Run the above batch script with Administrator privileges

After successfully executing the script, make sure there's a new entry called "Security" below you node from 2.

If the sensor is already connected to your PC you'll need to reconnect it.

Now the code from my Question above should work :)

You'll find a detailed read on how to solve this problem here:
https://developer.microsoft.com/en-us/windows/iot/Samples/CustomDeviceAccessor


问:
Where do I put startup code in Play Framework?
I want to run some code on startup to pre-cache some stuff, and would also like to start a Timer to re-cache some things outside the critical path of a web request.  Is this possible with Play Framework, and where so I put this code?</p>

答:
In Play 2.4.+ you should use dependency injection with an (optional) lifecycle hook. Play will automatically use any class called Module that is in the root package.

For example:

app/ApplicationStart.scala:

```<code>import scala.concurrent.Future
import javax.inject._
import play.api.inject.ApplicationLifecycle

// This creates an `ApplicationStart` object once at start-up and registers hook for shut-down.
@Singleton
class ApplicationStart @Inject() (lifecycle: ApplicationLifecycle) {
  // Shut-down hook
  lifecycle.addStopHook { () =>
    Future.successful(())
  }
  //...
}
</code>```

app/Module.scala:

```<code>import com.google.inject.AbstractModule

class Module extends AbstractModule {
  override def configure() = {
    bind(classOf[ApplicationStart]).asEagerSingleton()
  }
}
</code>```

More documentation of this pattern in Playframework docs.

Here's an example in an application.

Body:
In Play 2.4.+ you should use dependency injection with an (optional) lifecycle hook. Play will automatically use any class called Module that is in the root package.

For example:

app/ApplicationStart.scala:

import scala.concurrent.Future
import javax.inject._
import play.api.inject.ApplicationLifecycle

// This creates an `ApplicationStart` object once at start-up and registers hook for shut-down.
@Singleton
class ApplicationStart @Inject() (lifecycle: ApplicationLifecycle) {
  // Shut-down hook
  lifecycle.addStopHook { () =>
    Future.successful(())
  }
  //...
}

app/Module.scala:

import com.google.inject.AbstractModule

class Module extends AbstractModule {
  override def configure() = {
    bind(classOf[ApplicationStart]).asEagerSingleton()
  }
}

More documentation of this pattern in Playframework docs.

Here's an example in an application.


问:
How to Render Two Components Conditionally?

How can I render these two components conditionally?

import React, { Component } from 'react';
import { Container, Header, Content, Card, CardItem, Text, Body } from 'native-base';
export default class CardHeaderFooterExample extends Component {
  render() {

    return (
      <Card>
        <CardItem header>
          <Text>NativeBase</Text>
        </CardItem>
        <CardItem>

            <Text>
              //Your text here
            </Text>

        </CardItem>
        <CardItem footer>
          <Text>GeekyAnts</Text>
        </CardItem>
      </Card>
```

<p>lets say:  </p>

<pre class="lang-js prettyprint-override"><code>if logedin={true}
  return
    <Card>
      <CardItem header>
        <Text>NativeBase</Text>
      </CardItem>
      <CardItem>
        <Body>
          <Text>
            //Your text here
          </Text>
        </Body>
      </CardItem>
      <CardItem footer>
        <Text>GeekyAnts</Text>
      </CardItem>
    </Card>

else return

  <Text> signup to access this content </Text>
</code>```

How can be this conditional rendering be done for this situation? Those components should be rendered based on boolean logedin.

答:
You can achieve that by referring below:</p>

```<code>render() {
  var1 =
    <Card>
      <CardItem header>
        <Text>NativeBase</Text>
      </CardItem>
      <CardItem>
        <Body>
          <Text>
            //Your text here
          </Text>
        </Body>
      </CardItem>
      <CardItem footer>
        <Text>GeekyAnts</Text>
      </CardItem>
    </Card>

var2 = <Text> signup to access this content </Text>

return(
  <View>
  {logedin == true
     ? var1
     : var2
  }
  </View>
);
}
</code>```

Body:
How can I render these two components conditionally?

import React, { Component } from 'react';
import { Container, Header, Content, Card, CardItem, Text, Body } from 'native-base';
export default class CardHeaderFooterExample extends Component {
  render() {

    return (
      <Card>
        <CardItem header>
          <Text>NativeBase</Text>
        </CardItem>
        <CardItem>

            <Text>
              //Your text here
            </Text>

        </CardItem>
        <CardItem footer>
          <Text>GeekyAnts</Text>
        </CardItem>
      </Card>

lets say:

if logedin={true}
  return
    <Card>
      <CardItem header>
        <Text>NativeBase</Text>
      </CardItem>
      <CardItem>

          <Text>
            //Your text here
          </Text>

      </CardItem>
      <CardItem footer>
        <Text>GeekyAnts</Text>
      </CardItem>
    </Card>

else return

  <Text> signup to access this content </Text>

How can be this conditional rendering be done for this situation? Those components should be rendered based on boolean logedin.

Body:
You can achieve that by referring below:

render() {
  var1 =
    <Card>
      <CardItem header>
        <Text>NativeBase</Text>
      </CardItem>
      <CardItem>
        <Body>
          <Text>
            //Your text here
          </Text>
        </Body>
      </CardItem>
      <CardItem footer>
        <Text>GeekyAnts</Text>
      </CardItem>
    </Card>

var2 = <Text> signup to access this content </Text>

return(
  <View>
  {logedin == true
     ? var1
     : var2
  }
  </View>
);
}


问:
Get GIT HEAD remote
I'm kinda new to Git and I have to compare the HEAD from a lokal branch with a remote branch.

On the lokal branch I get the HEAD with the following command:

```<code>git rev-parse --short HEAD

root@debian:xxxx# git rev-parse --short HEAD
469xxx
</code>```

But how can I get the short HEAD of a remote branch?
For Example:

```<code>https://github.com/openssl/openssl
</code>```

The lastest short HEAD is there "cded951"

In my case, getting the HEAD and comparing it does it.

```<code>If local HEAD != remote HEAD do xyz
</code>```

For this check I need the remote HEAD of my github branch.

best regards :)

Solution:

```<code>git remote update
if ! git diff --quiet origin/master; then
    echo "the branch is different!"
else
    echo "the branch is equal!"
fi
</code>```

答:
Run rev-parse on the local copy of the remote branch

```<code>git fetch
git rev-parse --short origin/master
</code>```

Title: Get GIT HEAD remote

Body:
I'm kinda new to Git and I have to compare the HEAD from a lokal branch with a remote branch.

On the lokal branch I get the HEAD with the following command:

git rev-parse --short HEAD

root@debian:xxxx# git rev-parse --short HEAD
469xxx

But how can I get the short HEAD of a remote branch?
For Example:

https://github.com/openssl/openssl

The lastest short HEAD is there "cded951"

In my case, getting the HEAD and comparing it does it.

If local HEAD != remote HEAD do xyz

For this check I need the remote HEAD of my github branch.

best regards :)

Solution:

git remote update
if ! git diff --quiet origin/master; then
    echo "the branch is different!"
else
    echo "the branch is equal!"
fi

Body:
Run rev-parse on the local copy of the remote branch

git fetch
git rev-parse --short origin/master


问:
Go http reuse seem doesn't work in upload file
When I use my go(1.8) http lib to do normal GET/POST method, it works fine, If I try to upload file to server with the http lib, the client will create a lot of sockets. In my test, files are cut in pieces to upload in 5 goroutines, the client remain 250 sockets. I already add defer resp.Body.Close()，here the key codes:

```<code>const (
    MaxIdleConns        int = 40
    MaxIdleConnsPerHost int = 40
)
transport := &http.Transport{
        MaxIdleConns:          MaxIdleConns,
        MaxIdleConnsPerHost:   MaxIdleConnsPerHost,
        IdleConnTimeout:       15 * time.Second,
        ResponseHeaderTimeout: Time.Hour,
    }
client := &http.Client{
        Transport: transport,
        Timeout:   time.Second * 30,
}
</code>```

those 250 sockets only recycle after client exit。

答:
It just a silly question，the lib doesn't reuse http client, thanks for help.here my new transport define:

```<code>const (
  MaxIdleConnsPerHost = 10
  MaxIdleConns        = 100
)
transport := &http.Transport{
    DialContext: (&net.Dialer{
      Timeout:   30 * time.Second,
      KeepAlive: 30 * time.Second,
      DualStack: true,
    }).DialContext,
    MaxIdleConns:          MaxIdleConns,
    MaxIdleConnsPerHost:   MaxIdleConnsPerHost,
    IdleConnTimeout:       90 * time.Second,
    TLSHandshakeTimeout:   10 * time.Second,
    ExpectContinueTimeout: 5 * time.Second,
}
</code>```

and i cache the http client instead of new http.Client for every http request.
go doc recommand reuse the client

// The Client's Transport typically has internal state (cached TCP
    // connections), so Clients should be reused instead of created as
    // needed. Clients are safe for concurrent use by multiple goroutines.
  https://golang.org/src/net/http/client.go

Body:
When I use my go(1.8) http lib to do normal GET/POST method, it works fine, If I try to upload file to server with the http lib, the client will create a lot of sockets. In my test, files are cut in pieces to upload in 5 goroutines, the client remain 250 sockets. I already add defer resp.Body.Close()，here the key codes:

const (
    MaxIdleConns        int = 40
    MaxIdleConnsPerHost int = 40
)
transport := &http.Transport{
        MaxIdleConns:          MaxIdleConns,
        MaxIdleConnsPerHost:   MaxIdleConnsPerHost,
        IdleConnTimeout:       15 * time.Second,
        ResponseHeaderTimeout: Time.Hour,
    }
client := &http.Client{
        Transport: transport,
        Timeout:   time.Second * 30,
}

those 250 sockets only recycle after client exit。

Body:
It just a silly question，the lib doesn't reuse http client, thanks for help.here my new transport define:

const (
  MaxIdleConnsPerHost = 10
  MaxIdleConns        = 100
)
transport := &http.Transport{
    DialContext: (&net.Dialer{
      Timeout:   30 * time.Second,
      KeepAlive: 30 * time.Second,
      DualStack: true,
    }).DialContext,
    MaxIdleConns:          MaxIdleConns,
    MaxIdleConnsPerHost:   MaxIdleConnsPerHost,
    IdleConnTimeout:       90 * time.Second,
    TLSHandshakeTimeout:   10 * time.Second,
    ExpectContinueTimeout: 5 * time.Second,
}

and i cache the http client instead of new http.Client for every http request.
go doc recommand reuse the client

// The Client's Transport typically has internal state (cached TCP
    // connections), so Clients should be reused instead of created as
    // needed. Clients are safe for concurrent use by multiple goroutines.
  https://golang.org/src/net/http/client.go


问:
HTML Unordered List not working
So I've been creating a webpage and tried to use an unordered list but it doesn't work and just appears with a grey background as a single string.

<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="project file 1.css">
  <link rel="stylesheet" href="style.css">
  <title>My Project
  </title>

            Home Page

            Project Page

            CV page

            Contact Me

         Home
              Page

        Hobbies

These are just a few of hobbies but these are the ones that take up the most time

Football

Rugby

Cycling

Gaming

        Photo Of Me

Please don't be mean

I know what a beautiful man ;)

        Table Of My Current/ Previous Jobs

          company

          Job Title

          length of time there

          Network Research

          Telemarketer

          2 Months

          David MacBeth Moir

          Kitchen Associate

          3 months

          Justice Mill

          Kitchen Associate

          1 year to present

        Why I Stay at Spoons

Cause its good patter and the people there as a good laugh but he job its self is pretty rubbish

        Questions?

Please feel free to ask any questions if you need help understanding anything for example:

Information given didnt make sense

Further questions on the information on the page

The layout was confusing

ect...

      <form>
        <fieldset>
          <legend>Please leave a comment...
          </legend>
          Name:

          <input type="text" name="name" value="" />
          Email

          <input type="text" name="email" value="" />
          Comments

          <textarea name="comments" cols="45" rows="5">
              </textarea>
          <input type="submit" value="submit" />
        </fieldset>
      </form>

```
</div>
</div>
</p>

<p>I have tried to create unordered lists in boxes 1 and 4 but they don't display correctly, main CSS spreadsheet is as follows:</p>

```h1 {
    color:black;
        }
     h2 {
        text-align:center;
    }
     p {
        margin-top:10px;
    }

    *{
    margin:0;
    padding:0;
    }
    body {
    background-color: white;
    }
    form {
    padding-top:120px;
    }
    img {
    margin-left:10px;
    margin-top:6px;
    border: 3px solid grey;
     }
    h3 {
    margin-left:30px;
    margin-right:30px;
    margin-top:10px;
    }
    h4 {
    margin-right:30px;
    margin-top:40px;
     }
     iframe {
    margin-left:150px;
    margin-top:40px;
    }
     #wrapper{
     width:1000px;
    height:1350px;
    margin:auto;
    background:#white;
    }
    #nav{
    width:1000px;
    height:50px;
    background:grey;
    }
    .box{
    width:400px;
    height:400px;
    float:left;
    background:#ff0;
    margin: 65px 0 0 65px ;
    border:5px solid grey;
    }
    .box2 {
    width: 400px;
    height:900px;
    float:left;
    background:#ff0;
    margin:65px 0 0 65px;
    border:5px solid grey;
    }
    .box3 {
    width:400px;
    height:400px;
    float:right;
    background:#ff0;
    margin-right:65px;
    margin-top:65px;
    border:5px solid grey;
    }
    .box4 {
    width:865px;
    height:400px;
    background:#ff0;
    margin-left:65px;
    margin-top:540px;
    border:5px solid grey;
    }
    .box5 {
    width:auto;
    height:150px;
    background:white;
    }
    .box6 {
    width:auto;
    height:60px;
    background:#3c3c3c;
    }
    .box7 {
    width:auto;
    height:1100px;
    background:white;
    }
    .one p{
    color:red;
    }
    .two p{
    color:purple;
    }
    .three p{
    color:green;
    }
    .four p{
    color:red;
    }
```

I cannot understand why the unordered list isn't working and I've checked it with a couple friends who have coded HTML before and they can't offer me any help. I thought that it could perhaps have been the div that goes around the list but I can't see anything that would mess with the actual list. any help would be greatly appreciated.

答:
You used:

```<code>li {
    float: left;
}
</code>```

Basically you can't float li items if you want them to work properly. Target your li items which you want to float through classes, id-s, or html tags, but not directly.

Title: HTML Unordered List not working

Body:
So I've been creating a webpage and tried to use an unordered list but it doesn't work and just appears with a grey background as a single string.

<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="project file 1.css">
  <link rel="stylesheet" href="style.css">
  <title>My Project
  </title>

            Home Page

            Project Page

            CV page

            Contact Me

         Home
              Page

        Hobbies

These are just a few of hobbies but these are the ones that take up the most time

Football

Rugby

Cycling

Gaming

        Photo Of Me

Please don't be mean

I know what a beautiful man ;)

        Table Of My Current/ Previous Jobs

          company

          Job Title

          length of time there

          Network Research

          Telemarketer

          2 Months

          David MacBeth Moir

          Kitchen Associate

          3 months

          Justice Mill

          Kitchen Associate

          1 year to present

        Why I Stay at Spoons

Cause its good patter and the people there as a good laugh but he job its self is pretty rubbish

        Questions?

Please feel free to ask any questions if you need help understanding anything for example:

Information given didnt make sense

Further questions on the information on the page

The layout was confusing

ect...

      <form>
        <fieldset>
          <legend>Please leave a comment...
          </legend>
          Name:

          <input type="text" name="name" value="" />
          Email

          <input type="text" name="email" value="" />
          Comments

          <textarea name="comments" cols="45" rows="5">
              </textarea>
          <input type="submit" value="submit" />
        </fieldset>
      </form>

I have tried to create unordered lists in boxes 1 and 4 but they don't display correctly, main CSS spreadsheet is as follows:

h1 {
    color:black;
        }
     h2 {
        text-align:center;
    }
     p {
        margin-top:10px;
    }

    *{
    margin:0;
    padding:0;
    }
    body {
    background-color: white;
    }
    form {
    padding-top:120px;
    }
    img {
    margin-left:10px;
    margin-top:6px;
    border: 3px solid grey;
     }
    h3 {
    margin-left:30px;
    margin-right:30px;
    margin-top:10px;
    }
    h4 {
    margin-right:30px;
    margin-top:40px;
     }
     iframe {
    margin-left:150px;
    margin-top:40px;
    }
     #wrapper{
     width:1000px;
    height:1350px;
    margin:auto;
    background:#white;
    }
    #nav{
    width:1000px;
    height:50px;
    background:grey;
    }
    .box{
    width:400px;
    height:400px;
    float:left;
    background:#ff0;
    margin: 65px 0 0 65px ;
    border:5px solid grey;
    }
    .box2 {
    width: 400px;
    height:900px;
    float:left;
    background:#ff0;
    margin:65px 0 0 65px;
    border:5px solid grey;
    }
    .box3 {
    width:400px;
    height:400px;
    float:right;
    background:#ff0;
    margin-right:65px;
    margin-top:65px;
    border:5px solid grey;
    }
    .box4 {
    width:865px;
    height:400px;
    background:#ff0;
    margin-left:65px;
    margin-top:540px;
    border:5px solid grey;
    }
    .box5 {
    width:auto;
    height:150px;
    background:white;
    }
    .box6 {
    width:auto;
    height:60px;
    background:#3c3c3c;
    }
    .box7 {
    width:auto;
    height:1100px;
    background:white;
    }
    .one p{
    color:red;
    }
    .two p{
    color:purple;
    }
    .three p{
    color:green;
    }
    .four p{
    color:red;
    }

I cannot understand why the unordered list isn't working and I've checked it with a couple friends who have coded HTML before and they can't offer me any help. I thought that it could perhaps have been the div that goes around the list but I can't see anything that would mess with the actual list. any help would be greatly appreciated.

Body:
You used:

li {
    float: left;
}

Basically you can't float li items if you want them to work properly. Target your li items which you want to float through classes, id-s, or html tags, but not directly.


问:
Get week of year in JavaScript like in PHP
How do I get the current weeknumber of the year, like PHP's date('W')?

It should be the ISO-8601 week number of year, weeks starting on Monday.

答:
I tried a lot to get the shortest code to get the weeknumber ISO-conform.

```<code>Date.prototype.getWeek=function(){
    var date=new Date(this);
    date.setHours(0,0,0,0);
    return Math.round(((date.setDate(this.getDate()+2-(this.getDay()||7))-date.setMonth(0,4))/8.64e7+3+(date.getDay()||7))/7)+"/"+date.getFullYear();}
</code>```

The variable date is necessary to avoid to alter the original this. I used the return values of setDate() and setMonth() to dispense with getTime() to save code length and I used an expontial number for milliseconds of a day instead of a multiplication of single elements or a number with five zeros. this is Date or Number of milliseconds, return value is String e.g. "49/2017".

Body:
I tried a lot to get the shortest code to get the weeknumber ISO-conform.

Date.prototype.getWeek=function(){
    var date=new Date(this);
    date.setHours(0,0,0,0);
    return Math.round(((date.setDate(this.getDate()+2-(this.getDay()||7))-date.setMonth(0,4))/8.64e7+3+(date.getDay()||7))/7)+"/"+date.getFullYear();}

The variable date is necessary to avoid to alter the original this. I used the return values of setDate() and setMonth() to dispense with getTime() to save code length and I used an expontial number for milliseconds of a day instead of a multiplication of single elements or a number with five zeros. this is Date or Number of milliseconds, return value is String e.g. "49/2017".


问:
All viewmodels inherit from 'BaseViewModel', can I set this up in OnActionExecuting?
If all my actions have a model that inherits from BaseViewModel, is it possible to initialize this model from the OnActionExecuting method?

Currently in all my actions I do this:

var model = new SomeModel();

model.User = Users.Get(...);

Now I am loading the user object in OnActionExecuting, so I was hoping I could setup my model from there somehow.

答:
You can't do it in OnActionExecuting, since at that point you don't know which subclass of BaseViewModel to use. However, you can update the model in OnActionExecuted, which runs after the action method but before the view is rendered.

Most likely you are populating these properties to use in the view only, but if you do need access to them in the action method you can put them into ViewBag or a controller property in OnActionExecuting and add them to the model in OnActionExecuted


问:
Select values that exists in array, but do not exits in database?
I have got DB with IDs: 1 2 3 4 5. I need to return elements that exists in my array (simple list of data that usually specifying in IN ( ... ) ), but DO NOT exits in DB.
For example checking values: 1, 2, 3, 4, 5, 6, 7.

So query should return 6, 7. How can I do it's with PostgreSQL?

答:
If you want a query that excludes all elements in a list you can use the NOT IN statement.

```<code>SELECT * FROM someTable WHERE id NOT IN (1, 2, 3, 4, 5);
</code>```

In your case you can create the query from your array.

Body:
If you want a query that excludes all elements in a list you can use the NOT IN statement.

SELECT * FROM someTable WHERE id NOT IN (1, 2, 3, 4, 5);

In your case you can create the query from your array.


问:
Browser not sending cookie in subsequent request
Working with a project, where using cookie for user identification.

When user arrives, it calls the service (which is running in localhost) and the service sending cookie with the response header looks like below:

```<code>curl 'http://127.0.0.1:8000/api/v1.0/tracking' -X OPTIONS -H 'Access-Control-Request-Method: POST' -H 'Origin: http://local.com:8080' -H 'Access-Control-Request-Headers: content-type,x-forwarded-for' --compressed
</code>```

The response header looks like below:

```<code>HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 60
Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, x-forwarded-for
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, PATCH, GET
Content-Length: 0
Content-Type: text/plain; charset=utf-8
Set-Cookie: id=random_id_123_123; expires=Wed, 06-Dec-2017 10:57:36 GMT; Domain=.local.com; Path=/
</code>```

And then after a specific user action, the app is sending following API request:

```<code>curl 'http://127.0.0.1:8000/api/v1.0/tracking?event=video_added&user_id=123123123' -H 'Origin: http://local.com:8080' -H 'Accept: */*' -H 'Referer: http://local.com:8080/' -H 'Connection: keep-alive' --compressed
</code>```

The request header for the above request looks like below:

```<code>GET api/v1.0/tracking?event=video_added&user_id=123123123 HTTP/1.1
Host: 127.0.0.1:8000
Connection: keep-alive
Accept: */*
Origin: http://local.com:8080
User-Agent: My user agent
Referer: http://local.com:8080/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
</code>```

I was expecting the cookie (random_id_123_123) to be received with the first request as response header would be the request header for the second request.

The website is running on: http://local.com:8080 (which actually running on local machine and my vhost config pointing 127.0.0.1 local.com) and its being served by python SimpleHTTPServer.

The backend service which is setting the cookie is running on port 8000 in localhost also.
Seems I have missed something during the implementation. Whats that?

Edit: Here is the code.

答:
Your issue is that cookies are only sent based on the domain. Your code has

```<code>var settings = {
  "crossDomain": true,
  "url": "http://127.0.0.1:8000/api/v1.0/tracking?event=video_added&tracking_id=123123123",
  "method": "GET",

}
</code>```

The url is 127.0.0.1:8000 and it should be local.com:8000 if you want the cookies to be passed.

Body:
Working with a project, where using cookie for user identification.

When user arrives, it calls the service (which is running in localhost) and the service sending cookie with the response header looks like below:

curl 'http://127.0.0.1:8000/api/v1.0/tracking' -X OPTIONS -H 'Access-Control-Request-Method: POST' -H 'Origin: http://local.com:8080' -H 'Access-Control-Request-Headers: content-type,x-forwarded-for' --compressed

The response header looks like below:

HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 60
Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, x-forwarded-for
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, PATCH, GET
Content-Length: 0
Content-Type: text/plain; charset=utf-8
Set-Cookie: id=random_id_123_123; expires=Wed, 06-Dec-2017 10:57:36 GMT; Domain=.local.com; Path=/

And then after a specific user action, the app is sending following API request:

curl 'http://127.0.0.1:8000/api/v1.0/tracking?event=video_added&user_id=123123123' -H 'Origin: http://local.com:8080' -H 'Accept: */*' -H 'Referer: http://local.com:8080/' -H 'Connection: keep-alive' --compressed

The request header for the above request looks like below:

GET api/v1.0/tracking?event=video_added&user_id=123123123 HTTP/1.1
Host: 127.0.0.1:8000
Connection: keep-alive
Accept: */*
Origin: http://local.com:8080
User-Agent: My user agent
Referer: http://local.com:8080/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

I was expecting the cookie (random_id_123_123) to be received with the first request as response header would be the request header for the second request.

The website is running on: http://local.com:8080 (which actually running on local machine and my vhost config pointing 127.0.0.1 local.com) and its being served by python SimpleHTTPServer.

The backend service which is setting the cookie is running on port 8000 in localhost also.
Seems I have missed something during the implementation. Whats that?

Edit: Here is the code.

Body:
Your issue is that cookies are only sent based on the domain. Your code has

var settings = {
  "crossDomain": true,
  "url": "http://127.0.0.1:8000/api/v1.0/tracking?event=video_added&tracking_id=123123123",
  "method": "GET",

}

The url is 127.0.0.1:8000 and it should be local.com:8000 if you want the cookies to be passed.


问:
tensorboard: command not found
I installed TensorFlow on my MacBook Pro 10.12.5 from source code by steps described here.
https://www.tensorflow.org/install/install_sources

TensorFlow itself works well but I cannot run TensorBoard.
It seems tensorboard is not installed properly.

When I try running tensorboard --logdir=... it says -bash: tensorboard: command not found. And locate tensorboard  returns empty.

Do I need any additional step to install tensorboard?

答:
If no other methods work then try this one. It may help you.

1. check the location of Tensorflow

```<code>pip show tensorflow
</code>```

It will show output something like this.

...

Name: tensorflow

Version: 1.4.0

Location: /home/abc/xy/.local/lib/python2.7/site-packages

...

2. Go to that location you get from the above output.

```<code>cd /home/abc/xy/.local/lib/python2.7/site-packages
</code>```

There you can see a directory named tensorboard.

```<code>cd tensorboard
</code>```

3. There must be a file named 'main.py'.

4. Execute the following command to launch the tensorboard.

```<code>python main.py --logdir=/path/to/log_file/
</code>```

Title: tensorboard: command not found

Body:
If no other methods work then try this one. It may help you.

1. check the location of Tensorflow

pip show tensorflow

It will show output something like this.

...

Name: tensorflow

Version: 1.4.0

Location: /home/abc/xy/.local/lib/python2.7/site-packages

...

2. Go to that location you get from the above output.

cd /home/abc/xy/.local/lib/python2.7/site-packages

There you can see a directory named tensorboard.

cd tensorboard

3. There must be a file named 'main.py'.

4. Execute the following command to launch the tensorboard.

python main.py --logdir=/path/to/log_file/

ContentLicense: CC BY-SA 4.0