问:
Laravel - Import excel keep looping
Dears,

i have an excel file with 5K rows and i'm importing it to my table in the DB successfully.

But the error, when the system finish all the rows, it keeps looping and the page doesn't stop running and not redirecting to my view.

My controller:

if($request->hasFile('import_file')){
       $path = $request->file('import_file')->getRealPath();
       $data = \Excel::load($path)->get();
       foreach ($data as $key => $row) {
       $res = policies::where('phone', '=', $row['phone'])
                      ->where('draft_no', '=', $row['draftno'])
                      ->where('due_date', '=', $duedate)
                      ->select('id')->get()->toArray();
                  if(empty($res)) {
                      $polic = new policies();
                      $polic->cust_id = $row['custno'];
                      $polic->policy = '';
                      $polic->bord_date = $borddate;
                      $polic->client_id = $row['clientid'];
                      $polic->client_no = $row['clientno'];
                      $polic->client_name = $row['clientname'];
                      $polic->draft_no = $row['draftno'];
                      if ($row['status'] == '') {
                          $polic->status = '';
                      } else {
                          $polic->status = $row['status'];
                      }

                      $polic->due_date = $duedate;
                      if ($row['curno'] == 'USD') {
                          $polic->currency = 1;
                      } else {
                          $polic->currency = 0;
                      }
                      $polic->amount = $row['amnt'];
                      $polic->zone = $row['zone'];
                      $polic->broker_id = $row['brokercode'];
                      $polic->broker_name = $row['brokername'];
                      $polic->remarks = $row['remarks'];
                      $polic->phone = $row['phone'];
                      $polic->insured_name = $row['insname'];
                      // $polic->cust_id = $row['valuedate'];
                      $polic->address = ''; //address
                      if (trim($row['status']) == 'P') {
                          $polic->paid_at = date('Y-m-d');
                      }
                      $polic->new = 1; //address
                      $polic->save();
       }
       else {
       //am updating the imported date in the DB
       }

```

what is very strange that in my localhost is working fine, but in digitaloceans cloud, keep looping without redirecting.

Thanks for your help.

答:
I can be because you have 5000 rows to insert and 5000 insert operation consumes lots of memory. What you can try is batch insert operation.

In your policies.php make all fields fillable

protected $fillable=['cust_id ','policy','bord_date','client_id','client_no','client_name ','draft_no','bord_date','status','due_date','currency','amount','zone','broker_id','broker_name','remarks','phone','insured_name','address','paid_at','new'];

And on your excel file import use exists rather than getting collections.

```<code>if($request->hasFile('import_file')){
       $path = $request->file('import_file')->getRealPath();
       $data = \Excel::load($path)->get();
$data=[];
$i=0;
 foreach ($data as $key => $row) {
       $res = policies::where('phone', '=', $row['phone'])
                      ->where('draft_no', '=', $row['draftno'])
                      ->where('due_date', '=', $duedate)
                      ->exists();
                  if(!$res) {
                    $i++;
                    $data[$i]['cust_id ']=$row['custno'];

                      $data['policy'] = '';
                      $data['bord_date'] = $borddate;
                      $data[$i]['client_id'] = $row['clientid'];
                      $data[$i]['client_no'] = $row['clientno'];
                      $data[$i]['client_name'] = $row['clientname'];
                      $data[$i]['draft_no'] = $row['draftno'];
                      if ($row['status'] == '') {
                          $data[$i]['status'] = '';
                      } else {
                          $data[$i]['status'] = $row['status'];
                      }

                      $data[$i]['due_date'] = $duedate;
                      if ($row['curno'] == 'USD') {
                          $data[$i]['currency'] = 1;
                      } else {
                          $data[$i]['currency'] = 0;
                      }
                      $data[$i]['amount'] = $row['amnt'];
                      $data[$i]['zone'] = $row['zone'];
                      $data[$i]['broker_id'] = $row['brokercode'];
                      $data[$i]['broker_name'] = $row['brokername'];
                      $data[$i]['remarks'] = $row['remarks'];
                      $data[$i]['phone'] = $row['phone'];
                      $data[$i]['insured_name'] = $row['insname'];
                      // $data[$i]['cust_id'] = $row['valuedate'];
                      $data[$i]['address'] = ''; //address
                      if (trim($row['status']) == 'P') {
                          $data[$i]['paid_at'] = date('Y-m-d');
                      }
                      $data[$i]['new'] = 1; //address

       }
       else {
       //am updating the imported date in the DB
       }
}
policies::insert($data);
</code>```

Title: Laravel - Import excel keep looping

Body:
Dears,

i have an excel file with 5K rows and i'm importing it to my table in the DB successfully.

But the error, when the system finish all the rows, it keeps looping and the page doesn't stop running and not redirecting to my view.

My controller:

if($request->hasFile('import_file')){
       $path = $request->file('import_file')->getRealPath();
       $data = \Excel::load($path)->get();
       foreach ($data as $key => $row) {
       $res = policies::where('phone', '=', $row['phone'])
                      ->where('draft_no', '=', $row['draftno'])
                      ->where('due_date', '=', $duedate)
                      ->select('id')->get()->toArray();
                  if(empty($res)) {
                      $polic = new policies();
                      $polic->cust_id = $row['custno'];
                      $polic->policy = '';
                      $polic->bord_date = $borddate;
                      $polic->client_id = $row['clientid'];
                      $polic->client_no = $row['clientno'];
                      $polic->client_name = $row['clientname'];
                      $polic->draft_no = $row['draftno'];
                      if ($row['status'] == '') {
                          $polic->status = '';
                      } else {
                          $polic->status = $row['status'];
                      }

                      $polic->due_date = $duedate;
                      if ($row['curno'] == 'USD') {
                          $polic->currency = 1;
                      } else {
                          $polic->currency = 0;
                      }
                      $polic->amount = $row['amnt'];
                      $polic->zone = $row['zone'];
                      $polic->broker_id = $row['brokercode'];
                      $polic->broker_name = $row['brokername'];
                      $polic->remarks = $row['remarks'];
                      $polic->phone = $row['phone'];
                      $polic->insured_name = $row['insname'];
                      // $polic->cust_id = $row['valuedate'];
                      $polic->address = ''; //address
                      if (trim($row['status']) == 'P') {
                          $polic->paid_at = date('Y-m-d');
                      }
                      $polic->new = 1; //address
                      $polic->save();
       }
       else {
       //am updating the imported date in the DB
       }

what is very strange that in my localhost is working fine, but in digitaloceans cloud, keep looping without redirecting.

Thanks for your help.

Body:
I can be because you have 5000 rows to insert and 5000 insert operation consumes lots of memory. What you can try is batch insert operation.

In your policies.php make all fields fillable

protected $fillable=['cust_id ','policy','bord_date','client_id','client_no','client_name ','draft_no','bord_date','status','due_date','currency','amount','zone','broker_id','broker_name','remarks','phone','insured_name','address','paid_at','new'];

And on your excel file import use exists rather than getting collections.

if($request->hasFile('import_file')){
       $path = $request->file('import_file')->getRealPath();
       $data = \Excel::load($path)->get();
$data=[];
$i=0;
 foreach ($data as $key => $row) {
       $res = policies::where('phone', '=', $row['phone'])
                      ->where('draft_no', '=', $row['draftno'])
                      ->where('due_date', '=', $duedate)
                      ->exists();
                  if(!$res) {
                    $i++;
                    $data[$i]['cust_id ']=$row['custno'];

                      $data['policy'] = '';
                      $data['bord_date'] = $borddate;
                      $data[$i]['client_id'] = $row['clientid'];
                      $data[$i]['client_no'] = $row['clientno'];
                      $data[$i]['client_name'] = $row['clientname'];
                      $data[$i]['draft_no'] = $row['draftno'];
                      if ($row['status'] == '') {
                          $data[$i]['status'] = '';
                      } else {
                          $data[$i]['status'] = $row['status'];
                      }

                      $data[$i]['due_date'] = $duedate;
                      if ($row['curno'] == 'USD') {
                          $data[$i]['currency'] = 1;
                      } else {
                          $data[$i]['currency'] = 0;
                      }
                      $data[$i]['amount'] = $row['amnt'];
                      $data[$i]['zone'] = $row['zone'];
                      $data[$i]['broker_id'] = $row['brokercode'];
                      $data[$i]['broker_name'] = $row['brokername'];
                      $data[$i]['remarks'] = $row['remarks'];
                      $data[$i]['phone'] = $row['phone'];
                      $data[$i]['insured_name'] = $row['insname'];
                      // $data[$i]['cust_id'] = $row['valuedate'];
                      $data[$i]['address'] = ''; //address
                      if (trim($row['status']) == 'P') {
                          $data[$i]['paid_at'] = date('Y-m-d');
                      }
                      $data[$i]['new'] = 1; //address

       }
       else {
       //am updating the imported date in the DB
       }
}
policies::insert($data);


来源: stackexchange

问:
I'm having trouble with HTTPS redirect in Apache
I'm having trouble using this code to redirect my users to HTTPS while including the subfolder/file after the domain.

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^tix\.kiwi [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}
</code>```

If I manually enter http://tix.kiwi/atd in my address bar, the browser redirects to https://tix.kiwiatd instead of https://tix.kiwi/atd/ and if I go to https://tix.kiwi/atd directly then it loads fine.

This same code works fine on my other websites; why is it not working here?

Notes: I'm using DigitalOcean, Ubuntu 14.04 x64

答: Your rewrites look correct, your issue lies in additional redirect code on another virtual host.  Resolving the conflict at that level allowed this rewrite to work as intented.  As discussed in the comments</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm having trouble using this code to redirect my users to HTTPS while including the subfolder/file after the domain.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^tix\.kiwi [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}

If I manually enter http://tix.kiwi/atd in my address bar, the browser redirects to https://tix.kiwiatd instead of https://tix.kiwi/atd/ and if I go to https://tix.kiwi/atd directly then it loads fine.

This same code works fine on my other websites; why is it not working here?

Notes: I'm using DigitalOcean, Ubuntu 14.04 x64

ContentLicense: CC BY-SA 4.0


问:
Pandas-style transform of grouped data on PySpark DataFrame
If we have a Pandas data frame consisting of a column of categories and a column of values, we can remove the mean in each category by doing the following:

```<code>df["DemeanedValues"] = df.groupby("Category")["Values"].transform(lambda g: g - numpy.mean(g))
</code>```

As far as I understand, Spark dataframes do not directly offer this group-by/transform operation (I am using PySpark on Spark 1.5.0). So, what is the best way to implement this computation?

I have tried using a group-by/join as follows:

```<code>df2 = df.groupBy("Category").mean("Values")
df3 = df2.join(df)
</code>```

But it is very slow since, as I understand, each category requires a full scan of the DataFrame.

I think (but have not verified) that I can speed this up a great deal if I collect the result of the group-by/mean into a dictionary, and then use that dictionary in a UDF as follows:

```<code>nameToMean = {...}
f = lambda category, value: value - nameToMean[category]
categoryDemeaned = pyspark.sql.functions.udf(f, pyspark.sql.types.DoubleType())
df = df.withColumn("DemeanedValue", categoryDemeaned(df.Category, df.Value))
</code>```

Is there an idiomatic way to express this type of operation without sacrificing performance?

答:
You can use Window to do this

i.e.

```<code>import pyspark.sql.functions as F
from pyspark.sql.window import Window

window_var = Window().partitionBy('Categroy')
df = df.withColumn('DemeanedValues', F.col('Values') - F.mean('Values').over(window_var))
</code>```

Body:
If we have a Pandas data frame consisting of a column of categories and a column of values, we can remove the mean in each category by doing the following:

df["DemeanedValues"] = df.groupby("Category")["Values"].transform(lambda g: g - numpy.mean(g))

As far as I understand, Spark dataframes do not directly offer this group-by/transform operation (I am using PySpark on Spark 1.5.0). So, what is the best way to implement this computation?

I have tried using a group-by/join as follows:

df2 = df.groupBy("Category").mean("Values")
df3 = df2.join(df)

But it is very slow since, as I understand, each category requires a full scan of the DataFrame.

I think (but have not verified) that I can speed this up a great deal if I collect the result of the group-by/mean into a dictionary, and then use that dictionary in a UDF as follows:

nameToMean = {...}
f = lambda category, value: value - nameToMean[category]
categoryDemeaned = pyspark.sql.functions.udf(f, pyspark.sql.types.DoubleType())
df = df.withColumn("DemeanedValue", categoryDemeaned(df.Category, df.Value))

Is there an idiomatic way to express this type of operation without sacrificing performance?

Body:
You can use Window to do this

i.e.

import pyspark.sql.functions as F
from pyspark.sql.window import Window

window_var = Window().partitionBy('Categroy')
df = df.withColumn('DemeanedValues', F.col('Values') - F.mean('Values').over(window_var))


问:
How can I prefix a value in a python dictionary used for an Ansible dynamic inventory?
I'm working on a custom Ansible dynamic inventory python script. I have created groups from k=v pairs, but for certain groups, I want the key prefixed to the values, otherwise the group names are meaningless (1,2,3, etc.)

I've tried sticking the key name in various places, but without a proper understanding of what I'm doing. In the example below, I am trying to get the "bucket" group to have every value look something like bucket_3 (which would then be the Ansible group name).

result = {
  'all': {
    'hosts': [],
    'vars': {},
   },
  '_meta': {
    'hostvars': {}
   }
}
server = ''
for raw_line in output.split('\n'):
    line = raw_line.strip()
    if len(line) > 0 and not line.startswith(comment_char):
        if line.endswith(server_char):
            server = line[:-1]
            result['all']['hosts'].append(server)
            result['_meta']['hostvars'][server] = {}
        else:
            raw_key, raw_value = line.split('=', 1)
            key = raw_key.strip()
            value = raw_value.strip()
            result['_meta']['hostvars'][server][key] = value
            if key == 'ansible_groups':
                for group in value.split(","):
                    if group not in result.keys():
                        result[group] = {'hosts': [], 'vars': {}}
                    result[group]['hosts'].append(server)
            if key == 'bucket':
                for group in value:
                    if group not in result.keys():
                        result[group] = 'bucket_' + {'hosts': [], 'vars': {}}
                    result[group]['hosts'].append(server)
```

I expect to get groups such as bucket_1, bucket_2, etc. (The source has 'bucket = 1', 'bucket = 2', etc.).

Getting error "'bucket_' + {'hosts': [], 'vars': {}} TypeError: cannot concatenate 'str' and
'dict' objects"

granted, this is just my latest attempt, so errors have been varied as I try to find the correct way to modify the group name.

答:
nevermind...just not thinking.

if key == 'bucket':
    for group in value:
        group = 'bucket_' + group
        if group not in result.keys():
```

still a bit slower than I would like, but it is functional

Body:
I'm working on a custom Ansible dynamic inventory python script. I have created groups from k=v pairs, but for certain groups, I want the key prefixed to the values, otherwise the group names are meaningless (1,2,3, etc.)

I've tried sticking the key name in various places, but without a proper understanding of what I'm doing. In the example below, I am trying to get the "bucket" group to have every value look something like bucket_3 (which would then be the Ansible group name).

result = {
  'all': {
    'hosts': [],
    'vars': {},
   },
  '_meta': {
    'hostvars': {}
   }
}
server = ''
for raw_line in output.split('\n'):
    line = raw_line.strip()
    if len(line) > 0 and not line.startswith(comment_char):
        if line.endswith(server_char):
            server = line[:-1]
            result['all']['hosts'].append(server)
            result['_meta']['hostvars'][server] = {}
        else:
            raw_key, raw_value = line.split('=', 1)
            key = raw_key.strip()
            value = raw_value.strip()
            result['_meta']['hostvars'][server][key] = value
            if key == 'ansible_groups':
                for group in value.split(","):
                    if group not in result.keys():
                        result[group] = {'hosts': [], 'vars': {}}
                    result[group]['hosts'].append(server)
            if key == 'bucket':
                for group in value:
                    if group not in result.keys():
                        result[group] = 'bucket_' + {'hosts': [], 'vars': {}}
                    result[group]['hosts'].append(server)

I expect to get groups such as bucket_1, bucket_2, etc. (The source has 'bucket = 1', 'bucket = 2', etc.).

Getting error "'bucket_' + {'hosts': [], 'vars': {}} TypeError: cannot concatenate 'str' and
'dict' objects"

granted, this is just my latest attempt, so errors have been varied as I try to find the correct way to modify the group name.

Body:
nevermind...just not thinking.

if key == 'bucket':
    for group in value:
        group = 'bucket_' + group
        if group not in result.keys():

still a bit slower than I would like, but it is functional


问:
Prevent retriggering mouseenter on parent div when child hidden
I have a parent div where a user's mouse enters, then they click a child input to hide it (mousedown).

Is it possible to prevent triggering another mousenter on the parent div when the child is hidden?

For example, the sequence currently becomes:

```<code>onMouseEnter Blue Container
input mouseEnter
input hidden
onMouseEnter Blue Container
</code>```

I want to prevent the last "onMouseEnter Blue Container" from being triggered (i.e., parent mouseEnter should not trigger again).

Stackblitz is here:  https://stackblitz.com/edit/angular-mouseenter-dquf3y

Below is my component:

```<code><div [ngClass]="class" #target
    (mouseenter)="onMouseEnter($event)"
    (mouseleave)="onMouseLeave($event)">
    <input (mouseenter)="this.log('input mouseEnter')"
           type="checkbox" (click)="doHide()" *ngIf="!hide"/>
</div>
</code>```

Below is my TS:

```<code>onMouseEnter($event) {
    this.log('onMouseEnter Blue Container');
    this.isHovering = true;
  }

  onMouseLeave($event) {
    this.log('onMouseLeave');
    this.isHovering = false;
  }

  hide = false;
  doHide() {
    this.hide = !this.hide;
    if (this.hide === true) {
      this.log('input hidden')
    }
  }
</code>```

答:
Instead of removing the input element with:

```<code>*ngIf="!hide"
</code>```

you can hide it with:

```<code>[hidden]="hide"
</code>```

That appears to avoid the triggering of the mouseenter event on the parent.

See this stackblitz for a demo.

Body:
I have a parent div where a user's mouse enters, then they click a child input to hide it (mousedown).

Is it possible to prevent triggering another mousenter on the parent div when the child is hidden?

For example, the sequence currently becomes:

onMouseEnter Blue Container
input mouseEnter
input hidden
onMouseEnter Blue Container

I want to prevent the last "onMouseEnter Blue Container" from being triggered (i.e., parent mouseEnter should not trigger again).

Stackblitz is here:  https://stackblitz.com/edit/angular-mouseenter-dquf3y

Below is my component:

    <input (mouseenter)="this.log('input mouseEnter')"
           type="checkbox" (click)="doHide()" *ngIf="!hide"/>

Below is my TS:

onMouseEnter($event) {
    this.log('onMouseEnter Blue Container');
    this.isHovering = true;
  }

  onMouseLeave($event) {
    this.log('onMouseLeave');
    this.isHovering = false;
  }

  hide = false;
  doHide() {
    this.hide = !this.hide;
    if (this.hide === true) {
      this.log('input hidden')
    }
  }

Body:
Instead of removing the input element with:

*ngIf="!hide"

you can hide it with:

[hidden]="hide"

That appears to avoid the triggering of the mouseenter event on the parent.

See this stackblitz for a demo.


问:
Redirect to a certain page then perform an event or action
I have a button with an onlick event that when triggered, has to redirect to a certain page, and add a class to a certain element.

Using the code:

window.location.href = "http://localhost:8000/dashboard";

$('p').addClass('active');,

I've successfully managed to redirect it but the event was not performed.  Is this even possible because it refreshes the DOM after redirecting. Thanks.

答:
The normal flow of JavaScript execution is broken when executing a full page navigation.  That means that JavaScript on the first page won't be able to modify the DOM on the second since the first page is no longer being executed by the browser after navigation.

There are some ways around this in practice, although I'm not sure if they are beyond the scope of what you might want to consider.  The old way of doing this would be to use an IFRAME tag to load your content in to, and execute all your scripts from the outer context.  If the pages are all on the same domain, the outer page can reach into the frame and cause them to navigate or even modify their DOM.

A more modern approach is to pick a "single page app" technology like Angular or React.  In those languages page navigation doesn't have to redirect the page in the traditional sense so execution flow isn't interrupted in the same way.  This is a fairly heavy handed approach though and since you mentioned PHP, you may not find those as appealing.

Since you are using PHP you could pass parameters to the second page to indicate a change needed to be made and handle it in PHP, such as http://example.com/secondPage.php?useOtherCSS=true.  Just a thought, even though it wouldn't use JavaScript it would play toward your goal.


问:
Java basics: a static function without a name, or return type
```<code>public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...
</code>```

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?

答: It a initialization block and called at the time of class loading.

Body:
public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?


问:
Neo4j bad performance with OR operator
I am using neo4j-3.5 community version .And have built a huge graph using neo4j containing ~20 million nodes on movie data. I have also inserted genres & keywords and constructed the graph.
The following query takes > 5 seconds

```<code>MATCH
    (p:`Program`),
    (p:Program)-[genre:of_genre]->(g:Genre),
    (p:Program)-[key_rel:associated_keyword]->(k:Keyword)
  WHERE
    ((g.id IN [1010]) OR (k.id IN ['keyword_121'])) AND
    ((p.show_type IN ['movie'])) AND
    (p.imdb_score > 0)
  RETURN distinct p.id, p.imdb_score
  ORDER BY p.imdb_score desc
  LIMIT 50
</code>```

whereas if i replace OR with AND, it takes < 100 ms.

```<code>MATCH
    (p:`Program`),
    (p:Program)-[genre:of_genre]->(g:Genre),
    (p:Program)-[key_rel:associated_keyword]->(k:Keyword)
  WHERE
    ((g.id IN [1010]) AND (k.id IN ['keyword_121'])) AND
    ((p.show_type IN ['movie'])) AND
    (p.imdb_score > 0)
  RETURN distinct p.id, p.imdb_score
  ORDER BY p.imdb_score desc
  LIMIT 50
</code>```

Indexes are there on genre id and keyword id.

The PROFILE response for 'OR' :

THE PROFILE response for 'AND' :

Any better way to write the query with OR operator?

答:
This may work better for you:

```<code>OPTIONAL MATCH (g:Genre) WHERE g.id IN [1010]
OPTIONAL MATCH (k:Keyword) WHERE k.id IN ['keyword_121']
WITH g, k
MATCH (p:`Program`)
WHERE
  p.show_type IN ['movie'] AND
  p.imdb_score > 0 AND
  ((p)-[:of_genre]->(g) OR (p)-[:associated_keyword]->(k))
RETURN distinct p.id, p.imdb_score
ORDER BY p.imdb_score desc
LIMIT 50
</code>```

This query might use both of your indexes (or at least you may be able to give hints to use them). Also, you may want to create an index on :Program(show_type) if movies are not very common in your DB.

The WHERE clause also just tests for the existence of a single desired :of_genre or :associated_keyword relationship -- it does not try to actually scan for and hold in memory all of them.

Title: Neo4j bad performance with OR operator

Body:
I am using neo4j-3.5 community version .And have built a huge graph using neo4j containing ~20 million nodes on movie data. I have also inserted genres & keywords and constructed the graph.
The following query takes > 5 seconds

MATCH
    (p:`Program`),
    (p:Program)-[genre:of_genre]->(g:Genre),
    (p:Program)-[key_rel:associated_keyword]->(k:Keyword)
  WHERE
    ((g.id IN [1010]) OR (k.id IN ['keyword_121'])) AND
    ((p.show_type IN ['movie'])) AND
    (p.imdb_score > 0)
  RETURN distinct p.id, p.imdb_score
  ORDER BY p.imdb_score desc
  LIMIT 50

whereas if i replace OR with AND, it takes < 100 ms.

MATCH
    (p:`Program`),
    (p:Program)-[genre:of_genre]->(g:Genre),
    (p:Program)-[key_rel:associated_keyword]->(k:Keyword)
  WHERE
    ((g.id IN [1010]) AND (k.id IN ['keyword_121'])) AND
    ((p.show_type IN ['movie'])) AND
    (p.imdb_score > 0)
  RETURN distinct p.id, p.imdb_score
  ORDER BY p.imdb_score desc
  LIMIT 50

Indexes are there on genre id and keyword id.

The PROFILE response for 'OR' :

THE PROFILE response for 'AND' :

Any better way to write the query with OR operator?

Body:
This may work better for you:

OPTIONAL MATCH (g:Genre) WHERE g.id IN [1010]
OPTIONAL MATCH (k:Keyword) WHERE k.id IN ['keyword_121']
WITH g, k
MATCH (p:`Program`)
WHERE
  p.show_type IN ['movie'] AND
  p.imdb_score > 0 AND
  ((p)-[:of_genre]->(g) OR (p)-[:associated_keyword]->(k))
RETURN distinct p.id, p.imdb_score
ORDER BY p.imdb_score desc
LIMIT 50

This query might use both of your indexes (or at least you may be able to give hints to use them). Also, you may want to create an index on :Program(show_type) if movies are not very common in your DB.

The WHERE clause also just tests for the existence of a single desired :of_genre or :associated_keyword relationship -- it does not try to actually scan for and hold in memory all of them.


问:
How to use JDK 11 from host system in containerized Jenkins to build Spring Boot 2
I have jenkinsci/blueocean:latest used in my docker-compose.yml it does not support however JDK 11 is installed at the host system of docker.

Now this dockerized Jenkins is based on JDK 8, but I want to use 11 for my project builds using Spring Boot 2.

How can one use the JDK 11 installed at the host system while building jobs on dockerized jenkins?

答:
The java for linux depends on glibc, the docker image jenkinsci/blueocean:latest uses alpine and alpine uses MUSL as a standard C library.

To use java in alpine images, have some tricks, but is not easy. Do you have some alternatives do prepare docker image. See this link fro more info.

To work, do you have to use another imagem from jenkins what don't use alpine.
See examples bellow

```<code>version: '3'

services:
  blueocean:
    image: jenkinsci/blueocean:latest
    ports:
      - 8080:8080
    volumes:
      - ./jdk-11.0.2:/opt/jdk11-glibc # doens't work
      - ./jdk-13-ea-musl:/opt/jdk13-musl # work

  jenkins:
    image: jenkins/jenkins:latest
    ports:
      - 8081:8080
    volumes:
      - ./jdk-11.0.2:/opt/jdk11-glibc # work
      - ./jdk-13-ea-musl:/opt/jdk13-musl # doens't work

  jenkins-alpine:
    image: jenkins/jenkins:alpine
    ports:
      - 8082:8080
    volumes:
      - ./jdk-11.0.2:/opt/jdk11-glibc # doens't work
      - ./jdk-13-ea-musl:/opt/jdk13-musl # work

  # alternatively, you can use the jenkins version with jdk11 and install blueocean
  jenkins-jdk11:
    image: jenkins/jenkins:jdk11
    ports:
      - 8083:8080
</code>```

You want to keep the settings when updating the jenkins, do you have to externalise volume /var/jenkins_home.

Body:
The java for linux depends on glibc, the docker image jenkinsci/blueocean:latest uses alpine and alpine uses MUSL as a standard C library.

To use java in alpine images, have some tricks, but is not easy. Do you have some alternatives do prepare docker image. See this link fro more info.

To work, do you have to use another imagem from jenkins what don't use alpine.
See examples bellow

version: '3'

services:
  blueocean:
    image: jenkinsci/blueocean:latest
    ports:
      - 8080:8080
    volumes:
      - ./jdk-11.0.2:/opt/jdk11-glibc # doens't work
      - ./jdk-13-ea-musl:/opt/jdk13-musl # work

  jenkins:
    image: jenkins/jenkins:latest
    ports:
      - 8081:8080
    volumes:
      - ./jdk-11.0.2:/opt/jdk11-glibc # work
      - ./jdk-13-ea-musl:/opt/jdk13-musl # doens't work

  jenkins-alpine:
    image: jenkins/jenkins:alpine
    ports:
      - 8082:8080
    volumes:
      - ./jdk-11.0.2:/opt/jdk11-glibc # doens't work
      - ./jdk-13-ea-musl:/opt/jdk13-musl # work

  # alternatively, you can use the jenkins version with jdk11 and install blueocean
  jenkins-jdk11:
    image: jenkins/jenkins:jdk11
    ports:
      - 8083:8080

You want to keep the settings when updating the jenkins, do you have to externalise volume /var/jenkins_home.


问:
how to generate report between two date which are linked to cells that are linked to ranges of cells in multiple sheets
Im trying to create a "Report Generator" in excel using command button(VBA) to generate the report after entering the range of date i want in two cell,
sheet1 has at B2 and D2, which only contains dates (FROM & TO), which are from 1/1/2019 to 31/12/2019

i tried linking the two dates, to other 12 sheets (each month)
in each sheet, each day contains 50 rows and 40 columns
Starting with the date of the day in cell B2,B52,B102,B152...ETC.

im successful in doing the following (easy part)
using command button(VBA) in the months' sheet to only show the 50 rows of the day i want, i was able to hide unneeded rows after choosing date in cell A1 (with date drop down list) and clicking on command button next to it in cell A2, using number of dates (43466 = 1/1/2019, 43467 = 2/1/2019...etc.)
sample of VBA code below (it goes over 1000 lines, with each sheet containing 100 or so lines, with command button to "refresh" and show only the day i want)

im unsuccessful in doing the following (hard part)
trying different formulas and vba to link the two dates in sheet1 (B2 and D2) to specific cell in specific sheet to use as FROM & TO in generating report, and linking the cell to a range below it using OFFSET, and use COUNTIF to count the specific data in each column

```<code>Private Sub CommandButton1_Click()

    Dim TriggerCell As Range
    Set TriggerCell = Range("C1")

    If TriggerCell.Value = "Show Entire Month" Then
        Rows("2:1644").Hidden = False
    ElseIf TriggerCell.Value = 43466 Then
        Rows("2:1644").Hidden = True
        Rows("2:54").Hidden = False
    ElseIf TriggerCell.Value = 43467 Then
        Rows("2:1644").Hidden = True
        Rows("55:107").Hidden = False
    End If

End Sub
</code>```

i expect the output in cells under the main sheet (sheet1)
to calculate the ranges between the specified dates and count the specific data which were entered and produce it, then generate charts based on those results, and creating a fully automatic report generator if possible

答:
This is my first/quick approach.

Read this information first as there are some disadvantages depending on how much data you're dealing with: http://www.mcgimpsey.com/excel/threedsumif.html

You could use the last suggestion given in the link and create the 3D formula using countifs

Steps I made to create the example:

1- Add sheets names in G3:G5

2- Added formula to cell D3:

```<code>=SUMPRODUCT(COUNTIFS(INDIRECT(""&G3:G5&"!$C:$C");">="&$B$3;INDIRECT(""&G3:G5&"!$C:$C");"<="&$C$3;INDIRECT(""&G3:G5&"!$D:$D");D$2))
</code>```

This was based on this set up in each sheet:

The key here is to use the countifs function that allows you to filter dates using >= or <= and include other criteria (inclusive - and).

Note: As stated in several forums, Sumproduct is volatile and it tends to slow the workbooks if it is used in ranges that include lots of cells.

I'd need to know how you're updating the report's data and with how much data you're dealing with to come up with other approaches.

If this helps, remember to mark the answer so it can help others too

Body:
Im trying to create a "Report Generator" in excel using command button(VBA) to generate the report after entering the range of date i want in two cell,
sheet1 has at B2 and D2, which only contains dates (FROM & TO), which are from 1/1/2019 to 31/12/2019

i tried linking the two dates, to other 12 sheets (each month)
in each sheet, each day contains 50 rows and 40 columns
Starting with the date of the day in cell B2,B52,B102,B152...ETC.

im successful in doing the following (easy part)
using command button(VBA) in the months' sheet to only show the 50 rows of the day i want, i was able to hide unneeded rows after choosing date in cell A1 (with date drop down list) and clicking on command button next to it in cell A2, using number of dates (43466 = 1/1/2019, 43467 = 2/1/2019...etc.)
sample of VBA code below (it goes over 1000 lines, with each sheet containing 100 or so lines, with command button to "refresh" and show only the day i want)

im unsuccessful in doing the following (hard part)
trying different formulas and vba to link the two dates in sheet1 (B2 and D2) to specific cell in specific sheet to use as FROM & TO in generating report, and linking the cell to a range below it using OFFSET, and use COUNTIF to count the specific data in each column

Private Sub CommandButton1_Click()

    Dim TriggerCell As Range
    Set TriggerCell = Range("C1")

    If TriggerCell.Value = "Show Entire Month" Then
        Rows("2:1644").Hidden = False
    ElseIf TriggerCell.Value = 43466 Then
        Rows("2:1644").Hidden = True
        Rows("2:54").Hidden = False
    ElseIf TriggerCell.Value = 43467 Then
        Rows("2:1644").Hidden = True
        Rows("55:107").Hidden = False
    End If

End Sub

i expect the output in cells under the main sheet (sheet1)
to calculate the ranges between the specified dates and count the specific data which were entered and produce it, then generate charts based on those results, and creating a fully automatic report generator if possible

Body:
This is my first/quick approach.

Read this information first as there are some disadvantages depending on how much data you're dealing with: http://www.mcgimpsey.com/excel/threedsumif.html

You could use the last suggestion given in the link and create the 3D formula using countifs

Steps I made to create the example:

1- Add sheets names in G3:G5

2- Added formula to cell D3:

=SUMPRODUCT(COUNTIFS(INDIRECT(""&G3:G5&"!$C:$C");">="&$B$3;INDIRECT(""&G3:G5&"!$C:$C");"<="&$C$3;INDIRECT(""&G3:G5&"!$D:$D");D$2))

This was based on this set up in each sheet:

The key here is to use the countifs function that allows you to filter dates using >= or <= and include other criteria (inclusive - and).

Note: As stated in several forums, Sumproduct is volatile and it tends to slow the workbooks if it is used in ranges that include lots of cells.

I'd need to know how you're updating the report's data and with how much data you're dealing with to come up with other approaches.

If this helps, remember to mark the answer so it can help others too


问:
Excel VBA loop and show interactively changes
I have a VBA Application which loops through a range and does some changes.
However, I don't care much about the running time but I want to show the User that changes were made in run time.

I was thinking about something like this.

```<code>Private Sub ProcessALBODY(ByRef Fullpath, ByRef MasterWB)
...

    For Each Row In rng.rows
    ... 'Do Something

    DoEvents
    ActiveWindow.ScrollRow = 1 'for each row scrolldown and proceed to next row
    Next

...
End Sub
</code>```

Unfortunately my application freezes until it has finished..

答:
What select or hide not work?

```<code>rng.EntireRow.Hidden = True
    For Each row In rng.Rows

        row.EntireRow.Hidden = False
        'do something.
        rng.EntireRow.Hidden = True

    Next

rng.EntireRow.Hidden = False
</code>```

or

```<code>For Each row In rng.Rows

    row.Select
    'do something.

Next
</code>```

Body:
I have a VBA Application which loops through a range and does some changes.
However, I don't care much about the running time but I want to show the User that changes were made in run time.

I was thinking about something like this.

Private Sub ProcessALBODY(ByRef Fullpath, ByRef MasterWB)
...

    For Each Row In rng.rows
    ... 'Do Something

    DoEvents
    ActiveWindow.ScrollRow = 1 'for each row scrolldown and proceed to next row
    Next

...
End Sub

Unfortunately my application freezes until it has finished..

Body:
What select or hide not work?

rng.EntireRow.Hidden = True
    For Each row In rng.Rows

        row.EntireRow.Hidden = False
        'do something.
        rng.EntireRow.Hidden = True

    Next

rng.EntireRow.Hidden = False

or

For Each row In rng.Rows

    row.Select
    'do something.

Next


问:
react-navigation header has a faint line
This turned into a massive adventure and subsequently, a very large and messy post, so to spare you from having to read through the mess that I keyboard-farted out below, here's a summary:

Main goal: To find a way to selectively show the navigation bar in my app without also selectively removing the Safe area padding to prevent my content being clipped by the iPhone X notch.

Why I did it the way I did: I wanted to try and use the Navigation Bar's built-in safe area padding instead of react-native's <SafeAreaView> because the <SafeAreaView> would interfere with the built in padding and cause the headers to be unnecessarily tall.

Side effect of not doing it the standard way: There was a faint line between the header (shown in picture with height: 0) and content that was plainly visible when both header and content were the same color

What I tried:

Using <SafeAreaView>

Not using <SafeAreaView> and trying to header: null instead (aka "the recommended way of doing it")

Playing with header options to make the header disappear without causing clipped content. As a side affect (quoted from extended post below)

i also found that header: null is functionally the same in result as
  headerTransparent: 'true' which I later discovered, is also
  functionally the same result as display: 'none'. All seem to be
  valid ways of making the entire header, Safe area padding and all,
  disappear.

Playing with the borderColor and borderWidth to determine if it was a border (in hindsight i should have done this more thoroughly)

Playing with 'opacity'

Shifting both the header and content around with position: 'relative', top: 6

Re-creating the issue in Xcode to see if it was an iOS issue (hindsight: i did this wrong)

This leads pretty cleanly into the answer so i'll cut it off here and continue it in my answer.

The long, confusing, original version

I'm using react-navigation in my react-native project (created with CRNA) and I think I have found a way to style the headers of a StackNavigator so that iOS takes care of the safe areas for you and negates the need to use <SafeAreaView> (which was interfering with the header on other screens).

My app is arranged such that the first screen is sort of like a home screen with a grid of buttons which will eventually each have their own page in the StackNavigator. On this home screen I want to disable the header bar since there is nothing to navigate to and it just moves the content down, however, on the other screens, I want to have the header bar visible to display the back button. While using <SafeAreaView> I  could only get one of the two mentioned above, either the home screen was clipped by the notch on the iPhone X, or the <SafeAreaView> moved the navigation/header bar on the other screens down and takes up space.

However, I found that by ditching the <SafeAreaView> entirely, i was able to re-create what I wanted using header styling from react-navigation:

App.js

```<code>const Navigation = createStackNavigator({
    Home: HomeScreen,
    Test: PageScreen,
},
{
  headerMode: 'screen',
  navigationOptions: {
    headerStyle: { backgroundColor: colors.background},
    headerTintColor: colors.headerTint,
    headerTitleStyle: {
      fontWeight: 'bold',
    },
  }
});
</code>```

HomeScreen.js

```<code> static navigationOptions = {
    headerStyle: {
        height: 0,
        backgroundColor: colors.background //had to re-color it here too because otherwise the header would be white???
      },
 };
</code>```

This works well because it effectively removes the header from the home screen but still keeps the safe area padding that the header creates. However, there is a thin line now separating the header from the Home Screen content and i'm not sure how to make it go away. It is the only thing that gives away my header trickery and detracts from the user experience.

Here is what I'm talking about:

This does not affect the other screens in which i want the header visible: Apparently it actually does, the colors were just masking it...

This line also appears on my iPhone 8 while testing the app using expo, although it is not as far down due to the smaller status bar on that device.

I have already tried changing the headerTintColor in the navigationOptions because I thought there may be some kind of background color behind the one I set but apparently that controls the color of the text and back button. The internet also doesnt seem to have much on this from what I can immediately tell as searches for header line react-navigation come up with results about hiding the header, being unable to hide the header, and how to customize the header. Does anyone know what this line is and how I remove it? or failing that, how to make <SafeAreaView> play nice with a StackNavigator's navigation header?

EDIT: I have also already tried the header: null, solution, however, by removing the header on the homepage of the app and not others causes a weird side effect with the <SafeAreaView> where the <SafeAreaView>'s safe area adds onto the one already built into the iOS header, causing the header to be a lot larger than it should, which is why I opted to go for height: 0 instead, since it renders the header effectively invisible, yet still keeps it's safe area.

EDIT 2: after playing with the borderColor and borderWidth of the header, I have determined that this line is not a border...

```<code>headerStyle: {
        height: 400,
        backgroundColor: 'green',
        borderColor: 'red',
        borderWidth: 150,
      },
</code>```

EDIT 3: more findings. After playing with the CSS I have found that setting the opacity: 0 reveals a white layer behind the navigation bar... maybe this is slightly bigger than the navbar itself?

also, it seems like header: null is functionally the same in result as headerTransparent: 'true' which I later discovered, is also functionally the same result as display: 'none'. All seem to be valid ways of making the entire header, Safe area padding and all, disappear.

shifting it with position: 'relative', top: 6 seems to not solve the issue either

EDIT 4:
Since I have determined that this line was in fact not just appearing on the screen where i'd set the header height to 0 and instead was appearing on all screens, I think this is something that is intentionally built into iOS in order to differentiate the header from the page content.

EDIT 4a: to confirm this theory I created a native-only xcode project and tried to recreate this by setting the nav bar and the view to black and, in contrary to my expectations, the issue did not re-create itself. So this is indeed something created by react-native and not built-into iOS i stand corrected again... How to remove navigation bar border/shadow?

答:
will fix this issue with below steps,

import {SafeAreaView} from 'react-native'

render() {
return(

<View style .....>

)
}

const styles = StyleSheet.create ({
safeArea : {
flex: 1,
backgroundColor: 'white'
})

Body:
This turned into a massive adventure and subsequently, a very large and messy post, so to spare you from having to read through the mess that I keyboard-farted out below, here's a summary:

Main goal: To find a way to selectively show the navigation bar in my app without also selectively removing the Safe area padding to prevent my content being clipped by the iPhone X notch.

Why I did it the way I did: I wanted to try and use the Navigation Bar's built-in safe area padding instead of react-native's <SafeAreaView> because the <SafeAreaView> would interfere with the built in padding and cause the headers to be unnecessarily tall.

Side effect of not doing it the standard way: There was a faint line between the header (shown in picture with height: 0) and content that was plainly visible when both header and content were the same color

What I tried:

Using <SafeAreaView>

Not using <SafeAreaView> and trying to header: null instead (aka "the recommended way of doing it")

Playing with header options to make the header disappear without causing clipped content. As a side affect (quoted from extended post below)

i also found that header: null is functionally the same in result as
  headerTransparent: 'true' which I later discovered, is also
  functionally the same result as display: 'none'. All seem to be
  valid ways of making the entire header, Safe area padding and all,
  disappear.

Playing with the borderColor and borderWidth to determine if it was a border (in hindsight i should have done this more thoroughly)

Playing with 'opacity'

Shifting both the header and content around with position: 'relative', top: 6

Re-creating the issue in Xcode to see if it was an iOS issue (hindsight: i did this wrong)

This leads pretty cleanly into the answer so i'll cut it off here and continue it in my answer.

The long, confusing, original version

I'm using react-navigation in my react-native project (created with CRNA) and I think I have found a way to style the headers of a StackNavigator so that iOS takes care of the safe areas for you and negates the need to use <SafeAreaView> (which was interfering with the header on other screens).

My app is arranged such that the first screen is sort of like a home screen with a grid of buttons which will eventually each have their own page in the StackNavigator. On this home screen I want to disable the header bar since there is nothing to navigate to and it just moves the content down, however, on the other screens, I want to have the header bar visible to display the back button. While using <SafeAreaView> I  could only get one of the two mentioned above, either the home screen was clipped by the notch on the iPhone X, or the <SafeAreaView> moved the navigation/header bar on the other screens down and takes up space.

However, I found that by ditching the <SafeAreaView> entirely, i was able to re-create what I wanted using header styling from react-navigation:

App.js

const Navigation = createStackNavigator({
    Home: HomeScreen,
    Test: PageScreen,
},
{
  headerMode: 'screen',
  navigationOptions: {
    headerStyle: { backgroundColor: colors.background},
    headerTintColor: colors.headerTint,
    headerTitleStyle: {
      fontWeight: 'bold',
    },
  }
});

HomeScreen.js

 static navigationOptions = {
    headerStyle: {
        height: 0,
        backgroundColor: colors.background //had to re-color it here too because otherwise the header would be white???
      },
 };

This works well because it effectively removes the header from the home screen but still keeps the safe area padding that the header creates. However, there is a thin line now separating the header from the Home Screen content and i'm not sure how to make it go away. It is the only thing that gives away my header trickery and detracts from the user experience.

Here is what I'm talking about:

This does not affect the other screens in which i want the header visible: Apparently it actually does, the colors were just masking it...

This line also appears on my iPhone 8 while testing the app using expo, although it is not as far down due to the smaller status bar on that device.

I have already tried changing the headerTintColor in the navigationOptions because I thought there may be some kind of background color behind the one I set but apparently that controls the color of the text and back button. The internet also doesnt seem to have much on this from what I can immediately tell as searches for header line react-navigation come up with results about hiding the header, being unable to hide the header, and how to customize the header. Does anyone know what this line is and how I remove it? or failing that, how to make <SafeAreaView> play nice with a StackNavigator's navigation header?

EDIT: I have also already tried the header: null, solution, however, by removing the header on the homepage of the app and not others causes a weird side effect with the <SafeAreaView> where the <SafeAreaView>'s safe area adds onto the one already built into the iOS header, causing the header to be a lot larger than it should, which is why I opted to go for height: 0 instead, since it renders the header effectively invisible, yet still keeps it's safe area.

EDIT 2: after playing with the borderColor and borderWidth of the header, I have determined that this line is not a border...

headerStyle: {
        height: 400,
        backgroundColor: 'green',
        borderColor: 'red',
        borderWidth: 150,
      },

EDIT 3: more findings. After playing with the CSS I have found that setting the opacity: 0 reveals a white layer behind the navigation bar... maybe this is slightly bigger than the navbar itself?

also, it seems like header: null is functionally the same in result as headerTransparent: 'true' which I later discovered, is also functionally the same result as display: 'none'. All seem to be valid ways of making the entire header, Safe area padding and all, disappear.

shifting it with position: 'relative', top: 6 seems to not solve the issue either

EDIT 4:
Since I have determined that this line was in fact not just appearing on the screen where i'd set the header height to 0 and instead was appearing on all screens, I think this is something that is intentionally built into iOS in order to differentiate the header from the page content.

EDIT 4a: to confirm this theory I created a native-only xcode project and tried to recreate this by setting the nav bar and the view to black and, in contrary to my expectations, the issue did not re-create itself. So this is indeed something created by react-native and not built-into iOS i stand corrected again... How to remove navigation bar border/shadow?


问:
Check if image content is a valid image code
Is there any way to check if the image code inside it  is valid  because

some crackers(hackers) can change the extension and play with image info using some applications to trick the website that the type is image while it's not

so  is there any way to check if content is an image code ?

Or is there anyway to check against this type of attacks ?

答:
For Multiple Images

```<code>$validatedData = $request->validate([
    'images' => 'required',
    'images.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
</code>```

Single Image Validation

```<code>$validatedData = $request->validate([
    'image' => 'required',
    'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
</code>```

Body:
For Multiple Images

$validatedData = $request->validate([
    'images' => 'required',
    'images.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);

Single Image Validation

$validatedData = $request->validate([
    'image' => 'required',
    'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);


问:
NSURLConnection threading problem
i have a big problem and i need your help. Here's what i need to accomplish:

The user select a row from a
TableView

A new view controller is pushed in
the NavigationController, and
displays only a "Loading" message

Meanwhile some data is read from an
XML file (via http)

When the data has been read, an
NSUConnection is used to load an
image from an URL (this URL is part
of the data)

While the image is still loading,
the other data is displayed on the
screen

The image has been downloaded and is
shown, completing the appearance of
the view

The big problem is that i can't use detachNewThreadSelector and NSURLConnection together!

So how can i make a workaround for this? How would you do this?

Thank you VERY much!

答:
You can use following approach...(if you are using asynchronous request)

When your application comes in  - (void)connectionDidFinishLoading:(NSURLConnection *)connection ... add a NSInvocationOperation object in NSOperationQueue (which you can handle at application level, by synthesizing it in appDelegate) ..

create NSInvocationOperation as follows..(in connectionDidFinishLoading)

```<code>NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(parseIt) object:nil];

[appDelegate.operationQueue addOperation:operation];
[operation release];

-(void) parseIt
{
   //ask for parsing stuff....what you have earlier wrote directly in connectionDidFinishLoading
}
</code>```

Thanks,

Title: NSURLConnection threading problem

Body:
You can use following approach...(if you are using asynchronous request)

When your application comes in  - (void)connectionDidFinishLoading:(NSURLConnection *)connection ... add a NSInvocationOperation object in NSOperationQueue (which you can handle at application level, by synthesizing it in appDelegate) ..

create NSInvocationOperation as follows..(in connectionDidFinishLoading)

NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(parseIt) object:nil];

[appDelegate.operationQueue addOperation:operation];
[operation release];

-(void) parseIt
{
   //ask for parsing stuff....what you have earlier wrote directly in connectionDidFinishLoading
}

Thanks,


问:
Update Project version automatically in Maven 3.6.0
I am using Maven 3.6.0 in a project where the version of my project is set using a revision property as described in https://maven.apache.org/maven-ci-friendly.html and I want to automatically update the project's version in command line.

I tried to look on the side of maven release plugin (https://maven.apache.org/maven-release/maven-release-plugin/update-versions-mojo.html) using the release:update-versions command, which seems to work, but instead of updating the property revision it updates the version property.

Current setup :

    <version>${revision}</version>

    <properties>
        <revision>1.1-SNAPSHOT</revision>
    </properties>
```

<p>When running <code>mvn release:update-versions</code> :</p>

<pre class="lang-xml prettyprint-override"><code>    <version>1.2-SNAPSHOT</version>

    <properties>
        <revision>1.1-SNAPSHOT</revision>
    </properties>
</code>```

Expected:

    <version>${revision}</version>

    <properties>
        <revision>1.2-SNAPSHOT</revision>
    </properties>
```

答:
Following is the explanation why this is happening:

When mvn release:update-versions is executed then it will bump the version by first fetching value of revision property. This command does not care about updating property value as well.

In general, property value in maven can be updated using -D flag within command line as follows:

mvn release -Drevision=1.2-SNAPSHOT

Following links could also be helpful:

https://maven.apache.org/maven-release/maven-release-plugin/examples/non-interactive-release.html

https://maven.apache.org/maven-release/maven-release-plugin/update-versions-mojo.html

Body:
I am using Maven 3.6.0 in a project where the version of my project is set using a revision property as described in https://maven.apache.org/maven-ci-friendly.html and I want to automatically update the project's version in command line.

I tried to look on the side of maven release plugin (https://maven.apache.org/maven-release/maven-release-plugin/update-versions-mojo.html) using the release:update-versions command, which seems to work, but instead of updating the property revision it updates the version property.

Current setup :

    <version>${revision}</version>

    <properties>
        <revision>1.1-SNAPSHOT</revision>
    </properties>

When running mvn release:update-versions :

    <version>1.2-SNAPSHOT</version>

    <properties>
        <revision>1.1-SNAPSHOT</revision>
    </properties>

Expected:

    <version>${revision}</version>

    <properties>
        <revision>1.2-SNAPSHOT</revision>
    </properties>


问:
z-index reversed in iOS and Safari macOS
The z-index of these images is set so they should be staked blue, red, green but in iOS browsers and Safari on macOS the order is reversed so they display green, red, blue.

Here is a CodePen, the issue effects all iOS browsers and Safari on macOS.

https://codepen.io/W3-design/pen/pBOJyy

HTML:

```<code><div class="stacked-images">
  <img src="https://via.placeholder.com/320x180/0000FF">
  <img src="https://via.placeholder.com/320x180/FF0000">
  <img src="https://via.placeholder.com/320x180/00FF00">
</div>
</code>```

SCSS:

```<code>.stacked-images {
    min-height: 500px;
    position: relative;
    margin: 20px;

    img {
      position: absolute;
      opacity: 0.9;
      transition: transform .5s ease-in-out;
      transform: translateZ(-1000px) rotate3d(1,0,0,-55deg) rotate3d(0,0,1,-30deg);
      -webkit-transform: translateZ(-1000px) rotate3d(1,0,0,-55deg) rotate3d(0,0,1,-30deg);

      &:nth-of-type(1) {
        z-index: 100;
        top: 0;
      }

      &:nth-of-type(2) {
        z-index: 90;
        top: 80px;
      }

      &:nth-of-type(3) {
        z-index: 80;
        top: 160px;
      }

      &:hover {
          transform: rotate3d(0, 0, 0, 0) scale(1.1,1.1);
          -webkit-transform: rotate3d(0, 0, 0, 0) scale(1.1,1.1);
          opacity: 1;
          z-index: 101;
      }
   }
}
</code>```

I would like the z-index to be the same across all browsers.

答:
Here you are:

.stacked-images {
  min-height: 500px;
  position: relative;
  margin: 20px;
}

img {
  position: absolute;
  opacity: 0.9;
  transition: transform .5s ease-in-out;
  transform: translateZ(-1000px) rotate3d(1, 0, 0, 55deg) rotate3d(0, 0, 1, -30deg);
}

img:nth-of-type(1) {
  z-index: 100;
  top: 0;
}

img:nth-of-type(2) {
  z-index: 90;
  top: 80px;
}

img:nth-of-type(3) {
  z-index: 80;
  top: 160px;
}

img:hover {
  transform: rotate3d(0, 0, 0, 0) scale(1.1, 1.1);
  opacity: 1;
  z-index: 101;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="stacked-images">
  <img src="https://via.placeholder.com/320x180/0000FF">
  <img src="https://via.placeholder.com/320x180/FF0000">
  <img src="https://via.placeholder.com/320x180/00FF00">
</div></code>```

Body:
The z-index of these images is set so they should be staked blue, red, green but in iOS browsers and Safari on macOS the order is reversed so they display green, red, blue.

Here is a CodePen, the issue effects all iOS browsers and Safari on macOS.

https://codepen.io/W3-design/pen/pBOJyy

HTML:

SCSS:

.stacked-images {
    min-height: 500px;
    position: relative;
    margin: 20px;

    img {
      position: absolute;
      opacity: 0.9;
      transition: transform .5s ease-in-out;
      transform: translateZ(-1000px) rotate3d(1,0,0,-55deg) rotate3d(0,0,1,-30deg);
      -webkit-transform: translateZ(-1000px) rotate3d(1,0,0,-55deg) rotate3d(0,0,1,-30deg);

      &:nth-of-type(1) {
        z-index: 100;
        top: 0;
      }

      &:nth-of-type(2) {
        z-index: 90;
        top: 80px;
      }

      &:nth-of-type(3) {
        z-index: 80;
        top: 160px;
      }

      &:hover {
          transform: rotate3d(0, 0, 0, 0) scale(1.1,1.1);
          -webkit-transform: rotate3d(0, 0, 0, 0) scale(1.1,1.1);
          opacity: 1;
          z-index: 101;
      }
   }
}

I would like the z-index to be the same across all browsers.

Body:
Here you are:

.stacked-images {
  min-height: 500px;
  position: relative;
  margin: 20px;
}

img {
  position: absolute;
  opacity: 0.9;
  transition: transform .5s ease-in-out;
  transform: translateZ(-1000px) rotate3d(1, 0, 0, 55deg) rotate3d(0, 0, 1, -30deg);
}

img:nth-of-type(1) {
  z-index: 100;
  top: 0;
}

img:nth-of-type(2) {
  z-index: 90;
  top: 80px;
}

img:nth-of-type(3) {
  z-index: 80;
  top: 160px;
}

img:hover {
  transform: rotate3d(0, 0, 0, 0) scale(1.1, 1.1);
  opacity: 1;
  z-index: 101;
}

<div class="stacked-images">
  <img src="https://via.placeholder.com/320x180/0000FF">
  <img src="https://via.placeholder.com/320x180/FF0000">
  <img src="https://via.placeholder.com/320x180/00FF00">
</div>


问:
spring mvc: convert json property in DTO to Enum
I'd like to have a String sent from the client to be converted to its respective Enum value.

Given:

```<code>public enum TheEnum {
    One,
    Two
}
</code>```

when hitting bindsToParams?boolVal=false&stringVal=foobar&enumVal=one

```<code>@Controller
//..
public void bindsToParams(
    @RequestParam Boolean boolVal,
    @RequestParam String stringVal,
    @RequestParam TheEnum enumVal) {
        // this works. enumVal created correctly
}
</code>```

I'd like the same enum conversion to happen, when the enum is a property of a DTO, and the incoming payload is json. So, with the following DTO:

```<code>public BagOfProps {
    Boolean boolVal;
    String stringVal;
    TheEnum enumVal;
}
</code>```

When sending: {"boolVal":false,"stringVal":"foobar",enumVal: "One"}

```<code>@Controller
//..
public void bindsToObject(
    @RequestBody BagOfProps bag) {
        // unmarshalling of boolVal, stringVal works
        // but bag.enumVal is null
}
</code>```

What should I do?

Thank you.

答:
Found the issue.

Deserialising the nested enum actually works out of the box. Reason it didn't work for me was that in the json payload, the name of the enum property was different than the name of the variable in the DTO:

I was sending:

```<code>{"boolVal":false,"stringVal":"foobar",enumVal: "One"}
</code>```

While the DTO was in-fact:

```<code>public BagOfProps {
    Boolean boolVal;
    String stringVal;
    TheEnum notTheSameNameAsEnumVal;
}
</code>```

HTH

Body:
I'd like to have a String sent from the client to be converted to its respective Enum value.

Given:

public enum TheEnum {
    One,
    Two
}

when hitting bindsToParams?boolVal=false&stringVal=foobar&enumVal=one

@Controller
//..
public void bindsToParams(
    @RequestParam Boolean boolVal,
    @RequestParam String stringVal,
    @RequestParam TheEnum enumVal) {
        // this works. enumVal created correctly
}

I'd like the same enum conversion to happen, when the enum is a property of a DTO, and the incoming payload is json. So, with the following DTO:

public BagOfProps {
    Boolean boolVal;
    String stringVal;
    TheEnum enumVal;
}

When sending: {"boolVal":false,"stringVal":"foobar",enumVal: "One"}

@Controller
//..
public void bindsToObject(
    @RequestBody BagOfProps bag) {
        // unmarshalling of boolVal, stringVal works
        // but bag.enumVal is null
}

What should I do?

Thank you.

Body:
Found the issue.

Deserialising the nested enum actually works out of the box. Reason it didn't work for me was that in the json payload, the name of the enum property was different than the name of the variable in the DTO:

I was sending:

{"boolVal":false,"stringVal":"foobar",enumVal: "One"}

While the DTO was in-fact:

public BagOfProps {
    Boolean boolVal;
    String stringVal;
    TheEnum notTheSameNameAsEnumVal;
}

HTH


问:
In mac terminal, how to check which port mysql is running?
I've done some research and found several places where people suggest using netstat to check which port a particular process is using.
But here is what I got:

```<code>myMac:~/Documents$ netstat -ap tcp | grep -i "listen"

tcp4       0      0  localhost.mysql        *.*                    LISTEN
</code>```

What does localhost.mysql say about the port number?? I'm expecting a 4 digit number like 3306.
Any thoughts?

答:
You should use -n for netstat to show network addresses as numbers.

```<code>netstat -nap tcp | grep -i "listen"
</code>```

```<code>man netstat
-n Show network addresses as numbers (normally netstat interprets addresses and attempts to display them symbolically).  This option may be used with any of the display formats.
</code>```

Or use lsof:

```<code>lsof -n -P -i TCP -s TCP:LISTEN
</code>```

Or use mysql client to check mysql port:

```<code>mysql> SHOW GLOBAL VARIABLES LIKE 'PORT';
</code>```

Body:
I've done some research and found several places where people suggest using netstat to check which port a particular process is using.
But here is what I got:

myMac:~/Documents$ netstat -ap tcp | grep -i "listen"

tcp4       0      0  localhost.mysql        *.*                    LISTEN

What does localhost.mysql say about the port number?? I'm expecting a 4 digit number like 3306.
Any thoughts?

Body:
You should use -n for netstat to show network addresses as numbers.

netstat -nap tcp | grep -i "listen"

man netstat
-n Show network addresses as numbers (normally netstat interprets addresses and attempts to display them symbolically).  This option may be used with any of the display formats.

Or use lsof:

lsof -n -P -i TCP -s TCP:LISTEN

Or use mysql client to check mysql port:

mysql> SHOW GLOBAL VARIABLES LIKE 'PORT';


问:
Accessing css custom theme constant from code
I wonder whether it's possible to retrieve custom constant values set in the css file from the java code.

I went through the UIManager.themeConstants (as well as themeProps, you never know :)) but I could not find my custom constants in there.

I tried the following:

#Constants {
    --color0: #C4DFE6;
}
```

<pre class="lang-java prettyprint-override"><code>int color = UIManager.getInstance().getThemeConstant("--color0", 0);
                System.out.println("COLOR0=" + color);
                color = UIManager.getInstance().getThemeConstant("color0", 1);
                System.out.println("COLOR0=" + color);
                color = UIManager.getInstance().getThemeConstant("var(--color0)", 2);
                System.out.println("COLOR0=" + color);
                color = UIManager.getInstance().getThemeConstant("var(color0)", 3);
                System.out.println("COLOR0=" + color);
</code>```

I was hoping one of them to return my value: 0xC4DFE6.

答: The -- syntax is a special case for use within the CSS. Try using MyColor in the CSS with the same syntax in the Java side and it should work.

Body:
I wonder whether it's possible to retrieve custom constant values set in the css file from the java code.

I went through the UIManager.themeConstants (as well as themeProps, you never know :)) but I could not find my custom constants in there.

I tried the following:

#Constants {
    --color0: #C4DFE6;
}

int color = UIManager.getInstance().getThemeConstant("--color0", 0);
                System.out.println("COLOR0=" + color);
                color = UIManager.getInstance().getThemeConstant("color0", 1);
                System.out.println("COLOR0=" + color);
                color = UIManager.getInstance().getThemeConstant("var(--color0)", 2);
                System.out.println("COLOR0=" + color);
                color = UIManager.getInstance().getThemeConstant("var(color0)", 3);
                System.out.println("COLOR0=" + color);

I was hoping one of them to return my value: 0xC4DFE6.


问:
Plotly.js - Get 4 y values for each x in a stacked bar chart
I have plotted a stacked bar chart for 4 data values that I have for every U.S. state. The CSV file I have been working off of looks like this:

Here's the JS code I wrote for the stacked bar chart:

// Read the data from CSV
d3.csv('https://raw.githubusercontent.com/krithikaragha/ResPy/master/Flask%20App/static/data/tobacco_use_by_state.csv', function(data) {

    var chartData = []; // Array containing all the traces
    function makeTrace(d) {    // Function to make all 50 traces
        return {
            x: ["Smokes Everyday", "Smokes Somedays", "Former Smoker", "Never Smoked"],
            y: [d.smokesEveryday, d.smokesSomedays, d.formerSmoker, d.neverSmoked],
            name: d.state,
            type: 'bar'
        }
    }

    // Loop through all rows of the data
    for(var i = 0; i < data.length; i++) {

        // Call makeTrace to create a trace with index i
        chartData.push(makeTrace(data[i]));

        // Define a chart layout
        var layout = {
            barmode: 'stack',
            width: 1200,
            height: 800
        };

        // Plot the stacked bar chart
        Plotly.newPlot('bar', chartData, layout);
    }
});```

The resulting stacked bar chart ended up looking like this:

The result I want to achieve is: I want each U.S. state to have its own bar which is stacked with respective 4 values (smokesEveryday, smokesSomedays, formerSmoker and neverSmoked)

Is there any way I can achieve this? Thanks in advance.

答:
I figured it out myself.

Turns out, I had to make four separate traces for each of the 4 values I needed. So I looped through the data and created arrays for each column - smokedEveryday, smokesSomedays, formerSmoker and neverSmoked and a last array states to hold the state's abbreviations.

Then I created 4 individual traces with x-axis holding the states array and y-axis holding the respective smoking array.

Here's the modified code snippet:

// Read the data from CSV
d3.csv('https://raw.githubusercontent.com/krithikaragha/ResPy/master/Flask%20App/static/data/tobacco_use_by_state.csv', function(data) {

    var states = [];
    var smokesEveryday = [];
    var smokesSomedays = [];
    var formerSmoker = [];
    var neverSmoked = [];

    // Loop through all rows of the data
    for(var i = 0; i < data.length; i++) {

        states.push(data[i].abbr);
        smokesEveryday.push(data[i].smokesEveryday);
        smokesSomedays.push(data[i].smokesSomedays);
        formerSmoker.push(data[i].formerSmoker);
        neverSmoked.push(data[i].neverSmoked);
    }

    var smokesEverydayTrace = {
        x: states,
        y: smokesEveryday,
        name: 'Smokes Everyday',
        type: 'bar'
    };

    var smokesSomedaysTrace = {
        x: states,
        y: smokesSomedays,
        name: 'Smokes Somedays',
        type: 'bar'
    };

    var formerSmokerTrace = {
        x: states,
        y: formerSmoker,
        name: 'Former Smoker',
        type: 'bar'
    };

    var neverSmokedTrace = {
        x: states,
        y: neverSmoked,
        name: 'Never Smoked',
        type: 'bar'
    };

    var data = [neverSmokedTrace, formerSmokerTrace, smokesSomedaysTrace, smokesEverydayTrace];

    var layout = {
        barmode: 'stack',
        title: "Percentage of Tobacoo Use by State",
        xaxis: {
            title: {
                text: "Tobacco Use"
            },
            tickangle: 45
        },
        yaxis: {
            title: {
                text: "Percentage"
            }
        },
        bargap: 0.4,
        width: 1250,
        height: 800
    };

    Plotly.newPlot('bar', data, layout);

});```

Body:
I have plotted a stacked bar chart for 4 data values that I have for every U.S. state. The CSV file I have been working off of looks like this:

Here's the JS code I wrote for the stacked bar chart:

// Read the data from CSV
d3.csv('https://raw.githubusercontent.com/krithikaragha/ResPy/master/Flask%20App/static/data/tobacco_use_by_state.csv', function(data) {

    var chartData = []; // Array containing all the traces
    function makeTrace(d) {    // Function to make all 50 traces
        return {
            x: ["Smokes Everyday", "Smokes Somedays", "Former Smoker", "Never Smoked"],
            y: [d.smokesEveryday, d.smokesSomedays, d.formerSmoker, d.neverSmoked],
            name: d.state,
            type: 'bar'
        }
    }

    // Loop through all rows of the data
    for(var i = 0; i < data.length; i++) {

        // Call makeTrace to create a trace with index i
        chartData.push(makeTrace(data[i]));

        // Define a chart layout
        var layout = {
            barmode: 'stack',
            width: 1200,
            height: 800
        };

        // Plot the stacked bar chart
        Plotly.newPlot('bar', chartData, layout);
    }
});

The resulting stacked bar chart ended up looking like this:

The result I want to achieve is: I want each U.S. state to have its own bar which is stacked with respective 4 values (smokesEveryday, smokesSomedays, formerSmoker and neverSmoked)

Is there any way I can achieve this? Thanks in advance.


问:
Sed substitution on capture group
I would like to create a bash function which behaves in the following way:

If passed a string with no flags, add the second argument as flags

If passed any flag which is in the second argument, keep it in the flags.

If passed any flag with the letter c or d, we remove it.

If there is any other character in the flag, we want to keep those and append the second argument as flags.

For example:

my_func 'cmd pattern' 'ab' #=> cmd -ab pattern
my_func 'cmd -a pattern' 'ab' #=> cmd -ab pattern
my_func 'cmd -ac pattern' 'ab' #=> cmd -ab pattern
my_func 'cmd -aef pattern' 'ab' #=> cmd -efab pattern
my_func 'cmd -deaf pattern' 'ab' #=> cmd -efab pattern
```

<p>This is what I have tried:</p>

<pre class="lang-sh prettyprint-override"><code>function my_func() {
  echo $1 |
  # case with no flags
  sed "/^cmd [^-]/s/^cmd \(.*$\)/cmd -$2 \1/" |
  # case with flags in $2 or `a` or `b`
  sed "/^cmd -[$2ab]+ /s/^cmd -[$2ab] \(.*$\)/cmd -$2 \1/" |
  # case with other flags
  sed ...
}
</code>```

I'm struggling with the last one. I'm not sure if it's possible, but would love to know if it is.

It would somehow capture the flags (cmd -\([a-z]\)),

then remove abcd from the capture group (sed 's/[abcd]//g' on the group)

then take that value and append ab in the output.

It would also be cool to know if there is a nicer implementation using something other than sed

答:
As mentioned in the comments, sed probably isn't needed.

Here's a pure bash version:

```<code>my_func(){
    local cmd arg1 rest flags

    if [[ $2 =~ [^a-zA-Z0-9] ]]; then
        echo 1>&2 "bad character in arg2"
        exit 1
    fi

    read -r cmd arg1 rest <<< $1

    if [[ $arg1 =~ ^[^-] ]]; then
        # no flags
        echo "$cmd -$2 $arg1${rest:+ $rest}"
    else
        # have flags

        # strip unwanted/duplicates and append new
        eval 'flags=${arg1//[cd'$2']/}$2'

        # append new flags and return
        echo "$cmd $flags $rest"
    fi
}
</code>```

eval is dangerous if passed untrusted data (as is your sed using $2 unchecked) - always do a sanity check - I've assumed here that flags must be alphanumerics.

If you want to use sed, this should work (same caveat about sanity-checking $2:

```<code>my_func(){
    sed <<< $1 '
        /^\([^ ][^ ]*\) \([^-]\)/ { # no flags
            s//\1 -'$2' \2/;
            q;
         }
        /^[^ ][^ ]* -\([^ ]*\) .*/ { # has flags
            h;
            s//\1/;
            s/[cd'$2']//g;
            G;
            s/^\([^\n]*\)\n\([^ ][^ ]* -\)[^ ]*\( .*\)/\2\1'$2'\3/;
            q;
        }
        {
            s/.*/#ERROR: malformed input/;
            q;
        }
    '
}
</code>```

Title: Sed substitution on capture group

Body:
I would like to create a bash function which behaves in the following way:

If passed a string with no flags, add the second argument as flags

If passed any flag which is in the second argument, keep it in the flags.

If passed any flag with the letter c or d, we remove it.

If there is any other character in the flag, we want to keep those and append the second argument as flags.

For example:

my_func 'cmd pattern' 'ab' #=> cmd -ab pattern
my_func 'cmd -a pattern' 'ab' #=> cmd -ab pattern
my_func 'cmd -ac pattern' 'ab' #=> cmd -ab pattern
my_func 'cmd -aef pattern' 'ab' #=> cmd -efab pattern
my_func 'cmd -deaf pattern' 'ab' #=> cmd -efab pattern

This is what I have tried:

function my_func() {
  echo $1 |
  # case with no flags
  sed "/^cmd [^-]/s/^cmd \(.*$\)/cmd -$2 \1/" |
  # case with flags in $2 or `a` or `b`
  sed "/^cmd -[$2ab]+ /s/^cmd -[$2ab] \(.*$\)/cmd -$2 \1/" |
  # case with other flags
  sed ...
}

I'm struggling with the last one. I'm not sure if it's possible, but would love to know if it is.

It would somehow capture the flags (cmd -\([a-z]\)),

then remove abcd from the capture group (sed 's/[abcd]//g' on the group)

then take that value and append ab in the output.

It would also be cool to know if there is a nicer implementation using something other than sed

Body:
As mentioned in the comments, sed probably isn't needed.

Here's a pure bash version:

my_func(){
    local cmd arg1 rest flags

    if [[ $2 =~ [^a-zA-Z0-9] ]]; then
        echo 1>&2 "bad character in arg2"
        exit 1
    fi

    read -r cmd arg1 rest <<< $1

    if [[ $arg1 =~ ^[^-] ]]; then
        # no flags
        echo "$cmd -$2 $arg1${rest:+ $rest}"
    else
        # have flags

        # strip unwanted/duplicates and append new
        eval 'flags=${arg1//[cd'$2']/}$2'

        # append new flags and return
        echo "$cmd $flags $rest"
    fi
}

eval is dangerous if passed untrusted data (as is your sed using $2 unchecked) - always do a sanity check - I've assumed here that flags must be alphanumerics.

If you want to use sed, this should work (same caveat about sanity-checking $2:

my_func(){
    sed <<< $1 '
        /^\([^ ][^ ]*\) \([^-]\)/ { # no flags
            s//\1 -'$2' \2/;
            q;
         }
        /^[^ ][^ ]* -\([^ ]*\) .*/ { # has flags
            h;
            s//\1/;
            s/[cd'$2']//g;
            G;
            s/^\([^\n]*\)\n\([^ ][^ ]* -\)[^ ]*\( .*\)/\2\1'$2'\3/;
            q;
        }
        {
            s/.*/#ERROR: malformed input/;
            q;
        }
    '
}


问:
How do I get user entitlements to persist across conversations
I am trying to see if a user has purchased a product by checking conv.user.entitlements but except for immediately after purchase, this is empty.

This value seemed to be persisting between conversations previously, now it is always empty. I am able to see the entitlement using conv.user.entitlements immediately after purchase, but then it is gone.

```<code> if (arg.purchaseStatus === 'PURCHASE_STATUS_OK') {
 console.log('purchase2 ', conv.user.entitlements);
//this works as expected showing the entitlement
</code>```

In the logs I see:  purchase2  [ { entitlements: [ [Object] ],
    packageName: 'com.chad.myfirstapp' } ]

But when I try to log the same in the next conversation, I get:

purchase2 [ ]

答:
If you just want to see if a user has purchased an item in the past, use the conv.user.storage to store either a boolean whether the user has purchased something in the past:

conv.user.storage.hasPurchasedItem = true

Or perhaps you can make an array of purchases in conv.user.storage and check its length:

conv.user.storage.purchases = conv.user.storage.purchases || []
conv.user.storage.purchases.push({item: bananas, cost: 0.99})

Body:
I am trying to see if a user has purchased a product by checking conv.user.entitlements but except for immediately after purchase, this is empty.

This value seemed to be persisting between conversations previously, now it is always empty. I am able to see the entitlement using conv.user.entitlements immediately after purchase, but then it is gone.

 if (arg.purchaseStatus === 'PURCHASE_STATUS_OK') {
 console.log('purchase2 ', conv.user.entitlements);
//this works as expected showing the entitlement

In the logs I see:  purchase2  [ { entitlements: [ [Object] ],
    packageName: 'com.chad.myfirstapp' } ]

But when I try to log the same in the next conversation, I get:

purchase2 [ ]


问:
Tabulator - Header Formatter parameters
I am trying to programmatically modify header text/color/style using a custom formatter. I looked at the question Tabulator - Having Column Header Resize when Font Size Changes which was nearly perfect, but the example formatter given looks like a cell formatter not a header title formatter.

A cell formatter takes three parameters whereas a header title formatter takes none. (I believe - and the docs seem to agree: http://tabulator.info/docs/4.2/format#format-column)

My question is simply "Is there any way for a header title formatter to determine which column it is in?"

If I'm wrong about the parameters, then that should help, but I use the exact format as given in the other answer but modify the code to

```<code>var customFormatter = function(cell, formatterParams, onRendered){
  alert(cell == undefined)
}
</code>```

and the browser returns 'true'. So it is being run as I get the alert, but no parameters. Which agrees with the docs.

My alternative, as I'm creating the many tabulators programmatically in php, is to create a different function for every column in every table. But that seems like a terrible solution.

答:
I don't think I'm going to get a definitive answer from someone who knows this better than I do, but I'll stick with my initial position that the answer in the linked question was misleading.

A cell formatter has parameters:

var customFormatter = function(cell, formatterParams, onRendered){
  alert(cell == undefined) // false
}

...whereas a titleformatter does not:

var customFormatter = function(){
  // can really only do very generic stuff without parameters, only the return value matters
}

So the answer to my question is "No - you can't tell which column you're in when using a titleFormatter function", so you need one per column.

As I couldn't tell which column the formatter was for without creating a set of functions, I went a different way and instead created a fake but unique field name for each column and then once the table was set, ran through the header elements and mapped to them using the text in the header, and then modified the text to its proper value, and then could do what I liked with the header formatting.

If you're going a similar way, I only modified the text and background colours. Keep in mind the Tabulator doesn't know you've done this and might revert them, and my changes involved no resizing problems.

It meant I created an entire wrapper class for the Tabulator, but that has made it a lot more powerful anyway. Having said that, and having been through I think every free grid option out there, Tabulator is already strong enough as it is, in my opinion.

Title: Tabulator - Header Formatter parameters

Body:
I am trying to programmatically modify header text/color/style using a custom formatter. I looked at the question Tabulator - Having Column Header Resize when Font Size Changes which was nearly perfect, but the example formatter given looks like a cell formatter not a header title formatter.

A cell formatter takes three parameters whereas a header title formatter takes none. (I believe - and the docs seem to agree: http://tabulator.info/docs/4.2/format#format-column)

My question is simply "Is there any way for a header title formatter to determine which column it is in?"

If I'm wrong about the parameters, then that should help, but I use the exact format as given in the other answer but modify the code to

var customFormatter = function(cell, formatterParams, onRendered){
  alert(cell == undefined)
}

and the browser returns 'true'. So it is being run as I get the alert, but no parameters. Which agrees with the docs.

My alternative, as I'm creating the many tabulators programmatically in php, is to create a different function for every column in every table. But that seems like a terrible solution.


问:
How to Retrieve image from database?
In my Database, the images(jpeg,bmp format) are stored in bytea datatype, showing up in binary code in the database. Now I want to retrieve the images from the database. But i could not get the image in the web page. When i retrieve using this code given below, it shows the binary code value.(ie combination of numbers,characters,symbols). My code was

```<code>$dbconn = pg_connect("host=localhost user=xxxx password=xxxx dbname=xxxx")
 or die('Could not connect: ' .pg_last_error());

$rs = pg_query($dbconn, "select scan_image from image where cno='4' and imageno='1'");

$image = pg_escape_bytea(pg_fetch_result($rs, 0));

echo $image;
</code>```

Am i correct with this code? Please help me to find the solution.

答:
U can use Blob to retrieve image from database. And to store image u have convert image to byte using filestream.

This link may help you - http://www.itpian.com/Coding/6298-How-to-retrieve-the-image-to-database-coding.aspx

ContentLicense: CC BY-SA 2.5

Title: How to Retrieve image from database?

Body:
In my Database, the images(jpeg,bmp format) are stored in bytea datatype, showing up in binary code in the database. Now I want to retrieve the images from the database. But i could not get the image in the web page. When i retrieve using this code given below, it shows the binary code value.(ie combination of numbers,characters,symbols). My code was

$dbconn = pg_connect("host=localhost user=xxxx password=xxxx dbname=xxxx")
 or die('Could not connect: ' .pg_last_error());

$rs = pg_query($dbconn, "select scan_image from image where cno='4' and imageno='1'");

$image = pg_escape_bytea(pg_fetch_result($rs, 0));

echo $image;

Am i correct with this code? Please help me to find the solution.


问:
Is there a way to deploy an app onto the google play store but the ability to push out any updates without going through the google play store?
I need to find a way to push out updates to our app, but need it to happen instantly, instead of a 24 hour period or whatever it may take normally.

So at the moment we have an app that is just a WebView inside an app container, so we can update instantly because we only need to update the website and the app is automatically updated, but we want to transition to a native app which means we will need to redeploy every time we make an update. This will slow down our development and increase deployment times.

Is there an option which will give us the freedom to have a native app and create updates without having to redeploy through the google play store each time, or if we do have to use the store is there a way to have a faster turn around time?

答:
after doing some research it's possbile ,if you would like to check if you app has updates (without interacting with Google Play), you'd have to poll a server (providing your current version) and let the server check if there is a newer version available. If that is the case, let the server respond with a changelog and an url to the newer version.

Luckily, there are libraries to do this:

AppUpdater. Android Library that checks for updates on your own server (or Google Play, Github, etc). Great documentation. This library notifies your apps' updates by showing a Material dialog, Snackbar or notification.

AppUpdateChecker A simple non-Market way to keep your app updated. All it requires to set up is a URL pointing to a JSON document describing your app's changes.

Auto Updater This project allows to automatically update a running APK application using a private update server (see apk-updater) instead of Google Play updater. Also comes with a server script.

SmartUpdates. Older library, but instructions in English and also provides a server script.


问:
Can you implement autorenewing subscriptions in codenameone without a server side
I have followed the Auto renewing app subscriptions documentation. However the app i am building does not have a server side right now as it stands. I am failing to see if its possible to create the app without the need for the database at all

I have tried simply calling the Purchase.subscribe methods without any saving to a database

```<code>public void start() {

    Form hi = new Form("Hello World");
    //create receiptes store
    Purchase.getInAppPurchase().setReceiptStore(createReceieptsStore());
    //create a button to purchase the world
    Button buyWorld = new Button("Buy World");
    buyWorld.addActionListener(e -> {
        if (Purchase.getInAppPurchase().isSubscribed(SKU)) {
            Dialog.show("Cant Buy It", "You Own It", "OK", null);
        } else {
            Purchase.getInAppPurchase().subscribe(SKU);
        }
    });

    hi.addComponent(buyWorld);
    hi.show();
}
</code>```

I got an error pertaining to the receipt store fetch and submit methods needing to be implemented

答: It should be possible to implement subscription without a server but it would be very easy to hack this on any rooted Android device.</p>

Body:
I have followed the Auto renewing app subscriptions documentation. However the app i am building does not have a server side right now as it stands. I am failing to see if its possible to create the app without the need for the database at all

I have tried simply calling the Purchase.subscribe methods without any saving to a database

public void start() {

    Form hi = new Form("Hello World");
    //create receiptes store
    Purchase.getInAppPurchase().setReceiptStore(createReceieptsStore());
    //create a button to purchase the world
    Button buyWorld = new Button("Buy World");
    buyWorld.addActionListener(e -> {
        if (Purchase.getInAppPurchase().isSubscribed(SKU)) {
            Dialog.show("Cant Buy It", "You Own It", "OK", null);
        } else {
            Purchase.getInAppPurchase().subscribe(SKU);
        }
    });

    hi.addComponent(buyWorld);
    hi.show();
}

I got an error pertaining to the receipt store fetch and submit methods needing to be implemented


问:
Unable to access flask server hosted on azure VM
I have a flask server hosted on my azure vm.

```<code>if __name__ == '__main__':
    app.run(debug=True, host="127.0.0.1", port=4400)
</code>```

On vm, I can access the server via the address 127.0.0.1:4400
Now I want to be able to access this server from outside the vm i.e. my local computer.

I have already added the inbound security rule as below:

I have also added the same inbound rule on the VM's firewall on port 4400

Still I am unable to access the flask server via publicIP:4400 (publicIP is the public IP of my VM as displayed on the azure portal)

What could be the issue?

答:
For your issue, there are two possible reasons.

You must listen to the IP 0.0.0.0 so that it's possible to access from the Internet. The 127.0.0.1 is just a loopback IP for the test in the localhost. So 4c74356b41 is right in this way.

If you also cannot access the app from the Internet when you change the IP into 0.0.0.0. Then it must be the rules issue. You should check your VM networking if it's the same NSG for your subnet and NIC. If not, add the rule to allow the port 4400 in both NSGs. Then you also should check if the public IP is associated directly with your VM, or it's associated with the load balancer and your VM is just in the backend of the load balancer. If it's a load balancer, you still need to add the load balancer rule to allow the port 4400.

Take a check for the two possible reasons.

Body:
I have a flask server hosted on my azure vm.

if __name__ == '__main__':
    app.run(debug=True, host="127.0.0.1", port=4400)

On vm, I can access the server via the address 127.0.0.1:4400
Now I want to be able to access this server from outside the vm i.e. my local computer.

I have already added the inbound security rule as below:

I have also added the same inbound rule on the VM's firewall on port 4400

Still I am unable to access the flask server via publicIP:4400 (publicIP is the public IP of my VM as displayed on the azure portal)

What could be the issue?


问:
Using a subquery in 'FROM' in gorm
I would like to know how I can use a subquery in FROM clause using gorm. It would look like the following:

```<code>SELECT * FROM
(
  SELECT foo.*
  FROM foo
  WHERE bar = "baz"
) AS t1
WHERE t1.id = 1;
</code>```

I have built the subquery using golang:

```<code>db.Model(Foo{}).Where("bar = ?", "baz")
</code>```

But how can I use this as a subquery in FROM?

If there is a method that turns a gorm query into a SQL string, then I can simply plug that string into a raw SQL. But there does not seem to be such method. Any suggestions?

答:
also could be used in join </p>

```<code>subQuery:=db.Find(&subTable).QueryExpr()

db.
Table("table").
Select("*").
Join("join (?) as t1 on t1.id==table.id", //<---round brackets for multiple rows
subQuery).
Find(&Rows)

</code>```

Title: Using a subquery in 'FROM' in gorm

Body:
I would like to know how I can use a subquery in FROM clause using gorm. It would look like the following:

SELECT * FROM
(
  SELECT foo.*
  FROM foo
  WHERE bar = "baz"
) AS t1
WHERE t1.id = 1;

I have built the subquery using golang:

db.Model(Foo{}).Where("bar = ?", "baz")

But how can I use this as a subquery in FROM?

If there is a method that turns a gorm query into a SQL string, then I can simply plug that string into a raw SQL. But there does not seem to be such method. Any suggestions?

Body:
also could be used in join

subQuery:=db.Find(&subTable).QueryExpr()

db.
Table("table").
Select("*").
Join("join (?) as t1 on t1.id==table.id", //<---round brackets for multiple rows
subQuery).
Find(&Rows)