问:
ngx-charts render dynamic data
I'm new at ngx-charts I'm trying to render the dynamic bitcoin data by fetching the data from bitstamp service. The goal is to render visually the bitcoin data (price and timestamp) to the chart (value and date (convert to actual date from timestamp number)), and whenever bitcoin data updates, the data is pushed automatically to the chart. I tried to apply similar method from this plunker: https://plnkr.co/edit/JSTcS4FnJ5dshAldLWPL?p=preview.

However, I got tones of errors in the market-data component such as :

 attribute d: Expected number, "M0,NaNZ".
 attribute cy: Expected length, "NaN".

I don't know at which step I did wrong. Here is the relevant scripts:

bitstamp.service.ts:

```<code>import Pusher from 'pusher-js';
import { Injectable, Output, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs/Observable'
import { BehaviorSubject } from "rxjs/Rx";
import { List } from 'immutable';

@Injectable()
export class BitstampService {
  private pusher: any;

  private _messages: BehaviorSubject<any> = new BehaviorSubject(null);
  public messages: Observable<any> = this._messages.asObservable();

  constructor() {
    this.pusher = new Pusher('de504dc5763aeef9ff52');
    this.pusher.logToConsole = true;

    let channel = this.pusher.subscribe('live_trades');
    channel.bind('trade', (data) => {
      this._messages.next(data);
    });
  }
}
</code>```

market-data.component.ts:

```<code>import { Component, OnInit } from '@angular/core';
import { BitstampService } from '../../services/bitstamp.service';
import { Subject } from "rxjs/Subject";

@Component({
  selector: 'app-market-data',
  templateUrl: './market-data.component.html',
  styleUrls: ['./market-data.component.scss']
})
export class MarketDataComponent implements OnInit {

  private ngUnsubscribe: Subject<void> = new Subject<void>();

  bitcoinData: any = [
    {
      name: 'Bitcoin',
      series: [
        {
          "name": new Date,
          "value": Number
        }
      ]
    }
  ];

  view: any[] = [960, 500];

  // options
  showXAxis = true;
  showYAxis = true;
  gradient = false;
  showLegend = true;
  showXAxisLabel = true;
  xAxisLabel = 'Year';
  showYAxisLabel = true;
  yAxisLabel = 'USD';
  intervalId:any;

  colorScheme = {
    domain: ['#DC143C', '#A10A28', '#C7B42C', '#AAAAAA']
  };

  // line, area
  autoScale = true;

  constructor(private bitstamp: BitstampService) {
  }

  onSelect(event) {
    console.log(event);
  }

  ngOnInit() {
      this.bitstamp.messages.takeUntil(this.ngUnsubscribe).subscribe(data => {
        if (data != null) {
          this.bitcoinData[0].series.push({"name": new Date(parseInt(data.timestamp)*1000), "value": Math.floor(data.price)});
        }
        this.bitcoinData = [...this.bitcoinData];
      }, (err) => {
        console.log(err);
      });
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}
</code>```

market-data.component.html:

```<code><ngx-charts-line-chart
        [view]="view"
        [scheme]="colorScheme"
        [results]="bitcoinData"
        [gradient]="gradient"
        [xAxis]="showXAxis"
        [yAxis]="showYAxis"
        [legend]="showLegend"
        [showXAxisLabel]="showXAxisLabel"
        [showYAxisLabel]="showYAxisLabel"
        [xAxisLabel]="xAxisLabel"
        [yAxisLabel]="yAxisLabel"
        [autoScale]="autoScale"
        (select)="onSelect($event)">
      </ngx-charts-line-chart>
</code>```

Thank you in advance.

答:
I think you running into problems by pushing the timestamp in the bitcoinData-array in your market-data-component.ts.
With this line:

```<code>this.bitcoinData[0].series.push({"name": new Date(parseInt(data.timestamp)*1000), "value": Math.floor(data.price)});
</code>```

This should work:

```<code>this.bitcoinData[0].series.push({"name": String( new Date()), "value": Math.floor(data.price)});
</code>```

Title: ngx-charts render dynamic data

Body:
I'm new at ngx-charts I'm trying to render the dynamic bitcoin data by fetching the data from bitstamp service. The goal is to render visually the bitcoin data (price and timestamp) to the chart (value and date (convert to actual date from timestamp number)), and whenever bitcoin data updates, the data is pushed automatically to the chart. I tried to apply similar method from this plunker: https://plnkr.co/edit/JSTcS4FnJ5dshAldLWPL?p=preview.

However, I got tones of errors in the market-data component such as :

 attribute d: Expected number, "M0,NaNZ".
 attribute cy: Expected length, "NaN".

I don't know at which step I did wrong. Here is the relevant scripts:

bitstamp.service.ts:

import Pusher from 'pusher-js';
import { Injectable, Output, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs/Observable'
import { BehaviorSubject } from "rxjs/Rx";
import { List } from 'immutable';

@Injectable()
export class BitstampService {
  private pusher: any;

  private _messages: BehaviorSubject<any> = new BehaviorSubject(null);
  public messages: Observable<any> = this._messages.asObservable();

  constructor() {
    this.pusher = new Pusher('de504dc5763aeef9ff52');
    this.pusher.logToConsole = true;

    let channel = this.pusher.subscribe('live_trades');
    channel.bind('trade', (data) => {
      this._messages.next(data);
    });
  }
}

market-data.component.ts:

import { Component, OnInit } from '@angular/core';
import { BitstampService } from '../../services/bitstamp.service';
import { Subject } from "rxjs/Subject";

@Component({
  selector: 'app-market-data',
  templateUrl: './market-data.component.html',
  styleUrls: ['./market-data.component.scss']
})
export class MarketDataComponent implements OnInit {

  private ngUnsubscribe: Subject<void> = new Subject<void>();

  bitcoinData: any = [
    {
      name: 'Bitcoin',
      series: [
        {
          "name": new Date,
          "value": Number
        }
      ]
    }
  ];

  view: any[] = [960, 500];

  // options
  showXAxis = true;
  showYAxis = true;
  gradient = false;
  showLegend = true;
  showXAxisLabel = true;
  xAxisLabel = 'Year';
  showYAxisLabel = true;
  yAxisLabel = 'USD';
  intervalId:any;

  colorScheme = {
    domain: ['#DC143C', '#A10A28', '#C7B42C', '#AAAAAA']
  };

  // line, area
  autoScale = true;

  constructor(private bitstamp: BitstampService) {
  }

  onSelect(event) {
    console.log(event);
  }

  ngOnInit() {
      this.bitstamp.messages.takeUntil(this.ngUnsubscribe).subscribe(data => {
        if (data != null) {
          this.bitcoinData[0].series.push({"name": new Date(parseInt(data.timestamp)*1000), "value": Math.floor(data.price)});
        }
        this.bitcoinData = [...this.bitcoinData];
      }, (err) => {
        console.log(err);
      });
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}

market-data.component.html:

<ngx-charts-line-chart
        [view]="view"
        [scheme]="colorScheme"
        [results]="bitcoinData"
        [gradient]="gradient"
        [xAxis]="showXAxis"
        [yAxis]="showYAxis"
        [legend]="showLegend"
        [showXAxisLabel]="showXAxisLabel"
        [showYAxisLabel]="showYAxisLabel"
        [xAxisLabel]="xAxisLabel"
        [yAxisLabel]="yAxisLabel"
        [autoScale]="autoScale"
        (select)="onSelect($event)">
      </ngx-charts-line-chart>

Thank you in advance.

Body:
I think you running into problems by pushing the timestamp in the bitcoinData-array in your market-data-component.ts.
With this line:

this.bitcoinData[0].series.push({"name": new Date(parseInt(data.timestamp)*1000), "value": Math.floor(data.price)});

This should work:

this.bitcoinData[0].series.push({"name": String( new Date()), "value": Math.floor(data.price)});


来源: stackexchange

问:
Passing an async option value with Angular
This is the view:

```<code><select name="day" (change)="showHourRange(value)">
  <option selected="true" disabled="disabled">Choose one</option>
  <option *ngFor="let delivery of deliveries$ | async"
          [value]="delivery.day">{{delivery.day | date:'dd/MM/yy'}}
  </option>
</select>
</code>```

The value logs undefined when the method is called even if it is correctly shown inside the rendered options.

答:
Use [ngModel] and ngModelChange</p>

```<code><select name="day" [ngModel]="selectedDelovery" (ngModelChange)="showHourRange($event)">
  <option *ngFor="let delivery of deliveries$ | async"
          [value]="delivery.day">{{delivery.day | date:'dd/MM/yy'}}
  </option>
</select>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is the view:

<select name="day" (change)="showHourRange(value)">
  <option selected="true" disabled="disabled">Choose one</option>
  <option *ngFor="let delivery of deliveries$ | async"
          [value]="delivery.day">{{delivery.day | date:'dd/MM/yy'}}
  </option>
</select>

The value logs undefined when the method is called even if it is correctly shown inside the rendered options.

Body:
Use [ngModel] and ngModelChange

<select name="day" [ngModel]="selectedDelovery" (ngModelChange)="showHourRange($event)">
  <option *ngFor="let delivery of deliveries$ | async"
          [value]="delivery.day">{{delivery.day | date:'dd/MM/yy'}}
  </option>
</select>


问:
Cannot load a saved Spark model in pyspark: "java.lang.NoSuchMethodException"
When I run the following Python program

from pyspark.ml.classification import LinearSVC
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Sparkmodel").getOrCreate()
data = spark.read.format("libsvm").load("/usr/local/spark/data/mllib/sample_libsvm_data.txt")
model = LinearSVC().fit(data)
model.save("mymodel")
LinearSVC.load("mymodel")
```

<p>the <code>load</code> fails with a "java.lang.NoSuchMethodException".</p>

<pre class="lang-python prettyprint-override"><code>/anaconda3/envs/scratch/bin/python /Users/billmcn/src/toy/sparkmodel/sparkmodel/little.py
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/11/12 13:23:05 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/11/12 13:23:06 WARN Utils: Service 'SparkUI' could not bind on port 4040. Attempting port 4041.
17/11/12 13:23:06 WARN Utils: Service 'SparkUI' could not bind on port 4041. Attempting port 4042.
17/11/12 13:23:17 WARN BLAS: Failed to load implementation from: com.github.fommil.netlib.NativeSystemBLAS
17/11/12 13:23:17 WARN BLAS: Failed to load implementation from: com.github.fommil.netlib.NativeRefBLAS
Traceback (most recent call last):
  File "/Users/billmcn/src/toy/sparkmodel/sparkmodel/little.py", line 9, in <module>
    LinearSVC.load("mymodel")
  File "/anaconda3/envs/scratch/lib/python3.6/site-packages/pyspark/ml/util.py", line 257, in load
    return cls.read().load(path)
  File "/anaconda3/envs/scratch/lib/python3.6/site-packages/pyspark/ml/util.py", line 197, in load
    java_obj = self._jread.load(path)
  File "/anaconda3/envs/scratch/lib/python3.6/site-packages/py4j/java_gateway.py", line 1160, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "/anaconda3/envs/scratch/lib/python3.6/site-packages/pyspark/sql/utils.py", line 63, in deco
    return f(*a, **kw)
  File "/anaconda3/envs/scratch/lib/python3.6/site-packages/py4j/protocol.py", line 320, in get_return_value
    format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o64.load.
: java.lang.NoSuchMethodException: org.apache.spark.ml.classification.LinearSVCModel.<init>(java.lang.String)
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getConstructor(Class.java:1825)
    at org.apache.spark.ml.util.DefaultParamsReader.load(ReadWrite.scala:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)

Process finished with exit code 1
</code>```

The "mymodel" directory is created and its contents appear to be valid.

I am running Spark 2.2.0 and pyspark 2.2.0. I have the following mllib jars in my installation.

```<code>> ll /usr/local/spark.versions/spark-2.2.0-bin-hadoop2.7/jars/spark-mllib*
-rw-r--r--@ 1 billmcn  admin  6501535 Jun 30 18:09 /usr/local/spark.versions/spark-2.2.0-bin-hadoop2.7/jars/spark-mllib_2.11-2.2.0.jar
-rw-r--r--@ 1 billmcn  admin   182887 Jun 30 18:09 /usr/local/spark.versions/spark-2.2.0-bin-hadoop2.7/jars/spark-mllib-local_2.11-2.2.0.jar
</code>```

And the latter contains the class I want.

```<code>jar tf /usr/local/spark.versions/spark-2.2.0-bin-hadoop2.7/jars/spark-mllib_2.11-2.2.0.jar | grep LinearSVCModel
org/apache/spark/ml/classification/LinearSVCModel$LinearSVCWriter$Data.class
org/apache/spark/ml/classification/LinearSVCModel$.class
org/apache/spark/ml/classification/LinearSVCModel$LinearSVCWriter.class
org/apache/spark/ml/classification/LinearSVCModel$LinearSVCReader.class
org/apache/spark/ml/classification/LinearSVCModel$$anonfun$11.class
org/apache/spark/ml/classification/LinearSVCModel$LinearSVCWriter$$typecreator1$1.class
org/apache/spark/ml/classification/LinearSVCModel$LinearSVCWriter$Data$.class
org/apache/spark/ml/classification/LinearSVCModel.class
</code>```

The same problem happens on two different machines.

What am I doing wrong?

答:
I was using the wrong class to load the module. The following works

model = LinearSVCModel.load(model_path)
```

Body:
When I run the following Python program

from pyspark.ml.classification import LinearSVC
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Sparkmodel").getOrCreate()
data = spark.read.format("libsvm").load("/usr/local/spark/data/mllib/sample_libsvm_data.txt")
model = LinearSVC().fit(data)
model.save("mymodel")
LinearSVC.load("mymodel")

the load fails with a "java.lang.NoSuchMethodException".

/anaconda3/envs/scratch/bin/python /Users/billmcn/src/toy/sparkmodel/sparkmodel/little.py
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/11/12 13:23:05 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/11/12 13:23:06 WARN Utils: Service 'SparkUI' could not bind on port 4040. Attempting port 4041.
17/11/12 13:23:06 WARN Utils: Service 'SparkUI' could not bind on port 4041. Attempting port 4042.
17/11/12 13:23:17 WARN BLAS: Failed to load implementation from: com.github.fommil.netlib.NativeSystemBLAS
17/11/12 13:23:17 WARN BLAS: Failed to load implementation from: com.github.fommil.netlib.NativeRefBLAS
Traceback (most recent call last):
  File "/Users/billmcn/src/toy/sparkmodel/sparkmodel/little.py", line 9, in <module>
    LinearSVC.load("mymodel")
  File "/anaconda3/envs/scratch/lib/python3.6/site-packages/pyspark/ml/util.py", line 257, in load
    return cls.read().load(path)
  File "/anaconda3/envs/scratch/lib/python3.6/site-packages/pyspark/ml/util.py", line 197, in load
    java_obj = self._jread.load(path)
  File "/anaconda3/envs/scratch/lib/python3.6/site-packages/py4j/java_gateway.py", line 1160, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "/anaconda3/envs/scratch/lib/python3.6/site-packages/pyspark/sql/utils.py", line 63, in deco
    return f(*a, **kw)
  File "/anaconda3/envs/scratch/lib/python3.6/site-packages/py4j/protocol.py", line 320, in get_return_value
    format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o64.load.
: java.lang.NoSuchMethodException: org.apache.spark.ml.classification.LinearSVCModel.<init>(java.lang.String)
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getConstructor(Class.java:1825)
    at org.apache.spark.ml.util.DefaultParamsReader.load(ReadWrite.scala:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)

Process finished with exit code 1

The "mymodel" directory is created and its contents appear to be valid.

I am running Spark 2.2.0 and pyspark 2.2.0. I have the following mllib jars in my installation.

> ll /usr/local/spark.versions/spark-2.2.0-bin-hadoop2.7/jars/spark-mllib*
-rw-r--r--@ 1 billmcn  admin  6501535 Jun 30 18:09 /usr/local/spark.versions/spark-2.2.0-bin-hadoop2.7/jars/spark-mllib_2.11-2.2.0.jar
-rw-r--r--@ 1 billmcn  admin   182887 Jun 30 18:09 /usr/local/spark.versions/spark-2.2.0-bin-hadoop2.7/jars/spark-mllib-local_2.11-2.2.0.jar

And the latter contains the class I want.

jar tf /usr/local/spark.versions/spark-2.2.0-bin-hadoop2.7/jars/spark-mllib_2.11-2.2.0.jar | grep LinearSVCModel
org/apache/spark/ml/classification/LinearSVCModel$LinearSVCWriter$Data.class
org/apache/spark/ml/classification/LinearSVCModel$.class
org/apache/spark/ml/classification/LinearSVCModel$LinearSVCWriter.class
org/apache/spark/ml/classification/LinearSVCModel$LinearSVCReader.class
org/apache/spark/ml/classification/LinearSVCModel$$anonfun$11.class
org/apache/spark/ml/classification/LinearSVCModel$LinearSVCWriter$$typecreator1$1.class
org/apache/spark/ml/classification/LinearSVCModel$LinearSVCWriter$Data$.class
org/apache/spark/ml/classification/LinearSVCModel.class

The same problem happens on two different machines.

What am I doing wrong?


问:
Looping through csv file to create smaller file for action, loop not activating
The following code is meant to loop through a large csv file, take a block of 20 observations at a time, and load them into a smaller file, which will than be used for geocoding.  Loop does not seem to be running, and have run out of ideas why (nothing past the first row_count gets printed, except end)  </p>

```<code>SalesLoad = open('C:\Users\DillonSaxe\Real Estate\Chi address 2000-2015.csv')
Sales = csv.reader(SalesLoad)
Storage = []
row_count = sum(1 for row in Sales)
print row_count
for row in Sales:
    if Sales.line_num == 1:
        Header = row
        print header
    elif Sales.line_num%20 != 0 and Sales.line_num != row_count:
        Storage.append(row)
    else:
        Storage.append(row)
        print row
        TempLoad = open('C:\Users\DillonSaxe\Real Estate\Temp Geocode File.csv', 'wb')
        TempGeocode = csv.writer(TempLoad)
        TempGeocode.writerow(Header)
        for item in Storage:
            TempGeocode.writerow(item)
        TempLoad.close()
SalesLoad.close()
print 'Done'
</code>```

答: The line row_count = sum(1 for row in Sales) puts your reader at the bottom of the file. Add SalesLoad.seek(0) right after that line, or refactor your loop to not require the number of rows.

Body:
The following code is meant to loop through a large csv file, take a block of 20 observations at a time, and load them into a smaller file, which will than be used for geocoding.  Loop does not seem to be running, and have run out of ideas why (nothing past the first row_count gets printed, except end)

SalesLoad = open('C:\Users\DillonSaxe\Real Estate\Chi address 2000-2015.csv')
Sales = csv.reader(SalesLoad)
Storage = []
row_count = sum(1 for row in Sales)
print row_count
for row in Sales:
    if Sales.line_num == 1:
        Header = row
        print header
    elif Sales.line_num%20 != 0 and Sales.line_num != row_count:
        Storage.append(row)
    else:
        Storage.append(row)
        print row
        TempLoad = open('C:\Users\DillonSaxe\Real Estate\Temp Geocode File.csv', 'wb')
        TempGeocode = csv.writer(TempLoad)
        TempGeocode.writerow(Header)
        for item in Storage:
            TempGeocode.writerow(item)
        TempLoad.close()
SalesLoad.close()
print 'Done'


问:
How to get all rows from table that matches multiple parametres in Spring Data?
I'm using Java, Spring Boot and PostgreSQL

Right now I'm trying to send request form with multiple paramaters from website, to search the database for rows that match these parameters.

Like that

```<code>http://localhost:8080/search?vtitle=&vcompany=Epam&vcity=Kiev&vlanguage=Java
</code>```

I already figured out how to get such a solid query, but there is a problem.

```<code>List<JobSite> allJobs = jobRepository.findByTitleContainingAndCompanyAndCityAndLanguage(searchForm.getVtitle(),
            searchForm.getVcompany(),
            searchForm.getVcity(),
            searchForm.getVlanguage());

    allJobs.sort(Comparator.comparing(JobSite::getTime).reversed());
    model.addAttribute("jobs", allJobs);
    return "index";
</code>```

If i will not select one of the parameters it will not query this rows because of how findBy... method works.

If i will change code a little to

```<code>public String submit(@RequestParam MultiValueMap<String, String> params, Model model) {
</code>```

I will get some freedom. But even so I can't find a way to "automatically generate" queries like

```<code>SELECT * FROM table WHERE title = 1 AND company = 1 AND city = 1 AND language = 1
SELECT * FROM table WHERE company = 1 AND city = 1 AND language = 1
SELECT * FROM table WHERE city = 1 AND language = 1
SELECT * FROM table WHERE language = 1
SELECT * FROM table WHERE title = 1 AND city = 1 AND language = 1
</code>```

And so on.

If I will code it myself with Spring it will become a mess.

What is the best way to do such a search from site?

答:
In this case you can use Spring Data JPA Specifications. It's little bit tricky, refer these links you get an idea

1 . Spring Data JPA Specifications

advanced-spring-data-jpa-specifications

Body:
I'm using Java, Spring Boot and PostgreSQL

Right now I'm trying to send request form with multiple paramaters from website, to search the database for rows that match these parameters.

Like that

http://localhost:8080/search?vtitle=&vcompany=Epam&vcity=Kiev&vlanguage=Java

I already figured out how to get such a solid query, but there is a problem.

List<JobSite> allJobs = jobRepository.findByTitleContainingAndCompanyAndCityAndLanguage(searchForm.getVtitle(),
            searchForm.getVcompany(),
            searchForm.getVcity(),
            searchForm.getVlanguage());

    allJobs.sort(Comparator.comparing(JobSite::getTime).reversed());
    model.addAttribute("jobs", allJobs);
    return "index";

If i will not select one of the parameters it will not query this rows because of how findBy... method works.

If i will change code a little to

public String submit(@RequestParam MultiValueMap<String, String> params, Model model) {

I will get some freedom. But even so I can't find a way to "automatically generate" queries like

SELECT * FROM table WHERE title = 1 AND company = 1 AND city = 1 AND language = 1
SELECT * FROM table WHERE company = 1 AND city = 1 AND language = 1
SELECT * FROM table WHERE city = 1 AND language = 1
SELECT * FROM table WHERE language = 1
SELECT * FROM table WHERE title = 1 AND city = 1 AND language = 1

And so on.

If I will code it myself with Spring it will become a mess.

What is the best way to do such a search from site?


问:
Using proc datasets copy on files that fit a certain condition
As the title suggests I'd like to copy SAS tables from a Library to another but not all tables. I'd like to copy the tables which names start with 's' for example.
I know that I have to use proc  datasets copy but which option? How ?
(English isn't my first English so Im sorry if my question isnt clear))</p>

答:
It is probably easier to just use PROC COPY.  You can use : as a wildcard in the SELECT statement.

```<code>12220  proc copy inlib=work outlib=out;
12221    select c: / mtype=data ;
12222  run;

NOTE: Copying WORK.CHECK to OUT.CHECK (memtype=DATA).
NOTE: There were 3 observations read from the data set WORK.CHECK.
NOTE: The data set OUT.CHECK has 3 observations and 4 variables.
NOTE: Copying WORK.CLASS to OUT.CLASS (memtype=DATA).
NOTE: There were 19 observations read from the data set WORK.CLASS.
NOTE: The data set OUT.CLASS has 19 observations and 5 variables.
</code>```

Body:
It is probably easier to just use PROC COPY.  You can use : as a wildcard in the SELECT statement.

12220  proc copy inlib=work outlib=out;
12221    select c: / mtype=data ;
12222  run;

NOTE: Copying WORK.CHECK to OUT.CHECK (memtype=DATA).
NOTE: There were 3 observations read from the data set WORK.CHECK.
NOTE: The data set OUT.CHECK has 3 observations and 4 variables.
NOTE: Copying WORK.CLASS to OUT.CLASS (memtype=DATA).
NOTE: There were 19 observations read from the data set WORK.CLASS.
NOTE: The data set OUT.CLASS has 19 observations and 5 variables.


问:
How to override a Class from the Angular framework?
I am trying to find a way to override an Angular TS class, or at least be able to step through the code in debug mode.
So I would like for example to add : debugger;  or some console.log() to better understand its behavior.

In java I would just copy the source *.java Class in my projet and I would be sure that this class would be taken in priority,
but in TypeScript / Angular how can I achieve the same ?

答:
Find the function you want to debug in the node_modules/@angular folder in your project folder. You can edit angular's source files there.
When you want to reset the source to the original just delete the @angular folder, and do a npm install in the command line.


问:
Installation did not complete successfully. see the IDE log for details - Android studio
I am updating my android studio but show me bellow error :

My android studio is 2.3.1

答:
Download Intel XAMP by clicking on this link https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager-end-user-license-agreement

After downloading extract this file and install intelhaxm-android.exe file
Problem Solved....


问:
Why does Android Studio keep asking for a "Expression Expected"?
Here is my code:

```<code> @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnSighin = (Button) findViewById(R.id.btnSignIn);
    btnSignUp = (Button) findViewById(R.id.btnSignUp);

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent j = new Intent(MainActivity.this, SignUp.class);
            startActivity(SignUp);
        }
    });

    btnSighin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            Intent k = new Intent(MainActivity.this, SignIn.class);
            startActivity(SignIn);

        }
    });
}
</code>```

I am working on an app that allows customers to book appointments and in order to do so, they need to sign up or sign in. I have activities made for both of them and I can't run it without getting the "Expression Expected" and I'm new to Android Studio and have no idea what to do. Any help?

答:
You have to pass the intent object to the start activity method not the signup or signin class
So it should be startActivity(i) and startActivity(j)

Body:
Here is my code:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnSighin = (Button) findViewById(R.id.btnSignIn);
    btnSignUp = (Button) findViewById(R.id.btnSignUp);

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent j = new Intent(MainActivity.this, SignUp.class);
            startActivity(SignUp);
        }
    });

    btnSighin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            Intent k = new Intent(MainActivity.this, SignIn.class);
            startActivity(SignIn);

        }
    });
}

I am working on an app that allows customers to book appointments and in order to do so, they need to sign up or sign in. I have activities made for both of them and I can't run it without getting the "Expression Expected" and I'm new to Android Studio and have no idea what to do. Any help?


问:
PowerBI/DAX - Subtract min value per group
I want to take the value in a row and subtract the value in that group/category which is closest to 0. In other words, if I have a table

```<code>Col1     Col2
A          -4
A          -9
A           1
B          10
B          13
B          19
</code>```

Everything in the A category should be Col2 – 1 (because 1 is the closest to zero in the A group). Everything in the B category should be Col2 – 10 (because 10 is closest to zero in the B group).

Any suggestions on how to go about this?

答:
If your table is named Table1, then this should work:

```<code>=[Col2]-MINX(FILTER(Table1,[Col1]=EARLIER([Col1])),ABS([Col2]))
</code>```

Body:
I want to take the value in a row and subtract the value in that group/category which is closest to 0. In other words, if I have a table

Col1     Col2
A          -4
A          -9
A           1
B          10
B          13
B          19

Everything in the A category should be Col2 – 1 (because 1 is the closest to zero in the A group). Everything in the B category should be Col2 – 10 (because 10 is closest to zero in the B group).

Any suggestions on how to go about this?

Body:
If your table is named Table1, then this should work:

=[Col2]-MINX(FILTER(Table1,[Col1]=EARLIER([Col1])),ABS([Col2]))


问:
Java saving 2d tiles: for loop getting slower with each iteration up to 5 seconds for 10000 iterations
I'm currently developing a 2d game based on tiles. At the moment, I'm writing a process to save the whole world. In general, a world is 10000 x 10 = 1.100.000 blocks big. Obviously, it shouldn't be a problem for java, but it is.

Here's my loop:

```<code>Material[][] blocks = g.gameState.getLevel().tiles;
int y = 0;
int blocksHor = g.gameState.getLevel().getBlocksHor();

for(int x = 0; x < blocksHor; x++) {

    world += blocks[y][x] + " ";

    if(x >= blocksHor - 1) {
        x = 0;
        y++;
        System.out.println("LAYER " + y + " => " + (System.currentTimeMillis() - now) + " ms");
        now = System.currentTimeMillis();
    }
}
</code>```

The loop is a bit hard to understand, but I already tried to optimize wherever I could. Here's the console output:

```<code>LAYER 1 => 86 ms
LAYER 2 => 276 ms
LAYER 3 => 424 ms
LAYER 4 => 618 ms
LAYER 5 => 561 ms
LAYER 6 => 541 ms
LAYER 7 => 755 ms
LAYER 8 => 885 ms
LAYER 9 => 1036 ms
</code>```

These processes due up to 50 seconds and more at the end.

What's wrong with this loop? I honestly don't know how I should solve this problem.

Thank you :)
-phil

答:
If indeed the code you presented is representative of your problem, then the issue is very likely at

```<code>world += blocks[y][x] + " ";
</code>```

There are several performance issues with that.  In the first place, world must have type String, and Strings are immutable.  Therefore, whenever you concatenate them via the + operator, a new one must be created to hold the result.  You are doing that at least twice in each execution of that statement, producing overall in excess of 2M garbage objects that must eventually be collected.

Moreover, the intermediate values of world increase steadily in size, so the combined memory consumed by all those temporaries is proportional to the square of the total number of blocks.  Even if the string value of each block were only one character long, this would amount to a great deal of memory.  You're going to end up with serious garbage collection issues, and they will indeed get steadily worse as you proceed.

As a first attempt at improving this, you could consider accumulating the data into a StringBuilder instead of a String:

```<code>StringBuilder worldBuilder = new StringBuilder();

// ...

worldBuilder.append(blocks[y][x]).append(' ');
</code>```

That should significantly mitigate the GC issues by creating much less garbage, but you'll still end up requiring a pretty large object to hold the whole state.  Therefore, I'd also suggest accumulating the data into smaller chunks, outputting them as you go, instead of constructing the whole representation in memory before outputting anything.

You might also want to look at the implementation of Material.toString(), for if it, too, produces a lot of garbage by performing string concatenations then that will magnify the problem.

Body:
I'm currently developing a 2d game based on tiles. At the moment, I'm writing a process to save the whole world. In general, a world is 10000 x 10 = 1.100.000 blocks big. Obviously, it shouldn't be a problem for java, but it is.

Here's my loop:

Material[][] blocks = g.gameState.getLevel().tiles;
int y = 0;
int blocksHor = g.gameState.getLevel().getBlocksHor();

for(int x = 0; x < blocksHor; x++) {

    world += blocks[y][x] + " ";

    if(x >= blocksHor - 1) {
        x = 0;
        y++;
        System.out.println("LAYER " + y + " => " + (System.currentTimeMillis() - now) + " ms");
        now = System.currentTimeMillis();
    }
}

The loop is a bit hard to understand, but I already tried to optimize wherever I could. Here's the console output:

LAYER 1 => 86 ms
LAYER 2 => 276 ms
LAYER 3 => 424 ms
LAYER 4 => 618 ms
LAYER 5 => 561 ms
LAYER 6 => 541 ms
LAYER 7 => 755 ms
LAYER 8 => 885 ms
LAYER 9 => 1036 ms

These processes due up to 50 seconds and more at the end.

What's wrong with this loop? I honestly don't know how I should solve this problem.

Thank you :)
-phil

Body:
If indeed the code you presented is representative of your problem, then the issue is very likely at

world += blocks[y][x] + " ";

There are several performance issues with that.  In the first place, world must have type String, and Strings are immutable.  Therefore, whenever you concatenate them via the + operator, a new one must be created to hold the result.  You are doing that at least twice in each execution of that statement, producing overall in excess of 2M garbage objects that must eventually be collected.

Moreover, the intermediate values of world increase steadily in size, so the combined memory consumed by all those temporaries is proportional to the square of the total number of blocks.  Even if the string value of each block were only one character long, this would amount to a great deal of memory.  You're going to end up with serious garbage collection issues, and they will indeed get steadily worse as you proceed.

As a first attempt at improving this, you could consider accumulating the data into a StringBuilder instead of a String:

StringBuilder worldBuilder = new StringBuilder();

// ...

worldBuilder.append(blocks[y][x]).append(' ');

That should significantly mitigate the GC issues by creating much less garbage, but you'll still end up requiring a pretty large object to hold the whole state.  Therefore, I'd also suggest accumulating the data into smaller chunks, outputting them as you go, instead of constructing the whole representation in memory before outputting anything.

You might also want to look at the implementation of Material.toString(), for if it, too, produces a lot of garbage by performing string concatenations then that will magnify the problem.


问:
Dividing the page into columns using inline block not working
I want a solution by using inline-block not by using float:left.

    *{
     margin:0;
  padding:0;
 }
 body{
     margin:0;
  padding:0;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div style="width: 50%;background-color: #4caf50;display: inline-block;">
     Section 1
    </div>

 <div style="width: 50%;background-color: #ff5722;display: inline-block;">
     Section 2
    </div></code>```

Is there a solution ?

答:
you have spaces between the elements (a line break and a few tabs counts as a space, just to be clear). Minimized HTML will solve this problem

*{
    margin:0;
    padding:0;
}
body{
    margin:0;
    padding:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="width: 50%;background-color: #4caf50;display: inline-block;">Section 1</div><div style="width:50%;background-color: #ff5722;display: inline-block;">Section 2</div></code>```

Body:
I want a solution by using inline-block not by using float:left.

    *{
     margin:0;
  padding:0;
 }
 body{
     margin:0;
  padding:0;
 }

     Section 1

     Section 2

Is there a solution ?

Body:
you have spaces between the elements (a line break and a few tabs counts as a space, just to be clear). Minimized HTML will solve this problem

*{
    margin:0;
    padding:0;
}
body{
    margin:0;
    padding:0;
}

<div style="width: 50%;background-color: #4caf50;display: inline-block;">Section 1</div><div style="width:50%;background-color: #ff5722;display: inline-block;">Section 2</div>


问:
Ghost Blog posts sort order
Has anyone figured out a simple/quick way to use a custom post sort order with Ghost?

Specifically I would like to implement a theme that uses Ghost's tag-{slug}.hbs functionality to render tag specific pages that order posts oldest>newest instead of the default newest>oldest.

Any ideas vs. hacking at ghost core and making a big mess?

Thanks

答:
You can not make the blog engine return a different sort order. But what you can do is use template code to throw away the results provided by the engine and make it fetch new results with the #get helper.

```<code>    {{#has any="tag.feature_image"}}
        {{#get "posts" filter="tags.slug:{{tag.slug}}" limit=100 order="published_at asc"}}
            <!-- `posts` from the parent context is overwritten by get -->
            {> "loop"}}
        {{/get}}
    {{else}}
            <!-- default loop -->
            {{> "loop"}}
    {{/has}}
</code>```

I for example wanted to list posts in tag.hbs in chronological order if the Tag had a featured_image. So for such tags I use the #get helper to get the posts in chronological order (order="published_at asc"). If not the posts already provided by the blogging engine in reverse order are displayed.

Title: Ghost Blog posts sort order

Body:
You can not make the blog engine return a different sort order. But what you can do is use template code to throw away the results provided by the engine and make it fetch new results with the #get helper.

    {{#has any="tag.feature_image"}}
        {{#get "posts" filter="tags.slug:{{tag.slug}}" limit=100 order="published_at asc"}}
            <!-- `posts` from the parent context is overwritten by get -->
            {> "loop"}}
        {{/get}}
    {{else}}
            <!-- default loop -->
            {{> "loop"}}
    {{/has}}

I for example wanted to list posts in tag.hbs in chronological order if the Tag had a featured_image. So for such tags I use the #get helper to get the posts in chronological order (order="published_at asc"). If not the posts already provided by the blogging engine in reverse order are displayed.


问:
Selenium IE change event not fired
I have a select box which has an event listener on it:

```<code>$(document).ready(function () {
    $('#edit-era-code-select').change(function() {
      $.ajax({
        url: Drupal.settings.basePath+'era/js',
        type: 'POST',
        data: "era_code_select="+$(this).val(),
        context: document.body,
        success: function(){
        window.location.reload(true);
      }
    });
  });
});
</code>```

It will works fine when using it in ie/ff/...
When doing selenium tests using phpunit it I can see the selectbox being changed but it does not trigger the jquery event change. It only happens in IE. Here is the code that does the command:

```<code>AbstractSeleniumTestCaseIexplore::loginShib ( $user ['uid'] );
  $this->waitForElementPresent("//select[@id='edit-era-code-select']", 30000);
  $code = $this->getSelectedLabel("//select[@id='edit-era-code-select']");
  if ($code != 3333) {
    $this->select("edit-era-code-select", "label=3333");
    $this->waitForPageToLoad("30000");
  }
  ...
</code>```

Can anyone help?

答:
You can get it work without some hacks, like run script that fire change event.
Selenium generate javascript from your code and inject it in browser, than run it. But if you change selected option of any select via javascript it never work.

I've done small example in order to understand that(if you change selected option by hands 'change' event fire, but via javascript not. You can check workable example here):

```<code><select  id="someTxt">
    <option value="1">Option1</option>
    <option value="2">Option2</option>
    <option value="3">Option3</option>
</select>
<div id="button">Change selected option via javascript</div>

<script type="text/javascript">
    $(document).ready(function(){
     $('#someTxt').change(function() {
        alert($("#someTxt option:selected").text());
      });
    $("#button").bind("click", function(){
      $("#someTxt option[value='3']").attr('selected', 'selected');
    });
    });
 </script>
</code>```

So i think this is okay to fire event manually like:

```<code>$this->runScript("$('#edit-era-code-select').change()");
</code>```

ContentLicense: CC BY-SA 2.5

Title: Selenium IE change event not fired

Body:
I have a select box which has an event listener on it:

$(document).ready(function () {
    $('#edit-era-code-select').change(function() {
      $.ajax({
        url: Drupal.settings.basePath+'era/js',
        type: 'POST',
        data: "era_code_select="+$(this).val(),
        context: document.body,
        success: function(){
        window.location.reload(true);
      }
    });
  });
});

It will works fine when using it in ie/ff/...
When doing selenium tests using phpunit it I can see the selectbox being changed but it does not trigger the jquery event change. It only happens in IE. Here is the code that does the command:

AbstractSeleniumTestCaseIexplore::loginShib ( $user ['uid'] );
  $this->waitForElementPresent("//select[@id='edit-era-code-select']", 30000);
  $code = $this->getSelectedLabel("//select[@id='edit-era-code-select']");
  if ($code != 3333) {
    $this->select("edit-era-code-select", "label=3333");
    $this->waitForPageToLoad("30000");
  }
  ...

Can anyone help?

Body:
You can get it work without some hacks, like run script that fire change event.
Selenium generate javascript from your code and inject it in browser, than run it. But if you change selected option of any select via javascript it never work.

I've done small example in order to understand that(if you change selected option by hands 'change' event fire, but via javascript not. You can check workable example here):

<select  id="someTxt">
    <option value="1">Option1</option>
    <option value="2">Option2</option>
    <option value="3">Option3</option>
</select>
<div id="button">Change selected option via javascript</div>

<script type="text/javascript">
    $(document).ready(function(){
     $('#someTxt').change(function() {
        alert($("#someTxt option:selected").text());
      });
    $("#button").bind("click", function(){
      $("#someTxt option[value='3']").attr('selected', 'selected');
    });
    });
 </script>

So i think this is okay to fire event manually like:

$this->runScript("$('#edit-era-code-select').change()");


问:
Symfony Form Validation Choices Case Insensitive
On the form level validation in Symfony 3.3, I'm trying to figure out how to make it so that it is case insensitive. It is comparing against an array of choices.

```<code>public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', CollectionType::class, [
            'entry_type' => ChoiceType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'entry_options'  => array(
                'choices'  => array(
                                "Sample Option",
                                "Sample Option 2",
                                "Sample Option 3",
                                "Sample Option 4"
                            )
            ),
            'error_bubbling' => false
        ]);
</code>```

Under entry_options in choices is the array that it is using for form validation.

What I'm looking to do is be able to pass a case insensitive value like "sample option" or "sample Option" and have that pass the form level validation.

Thanks in advance for any help on this.

Update - As Kevin mentioned, I'm interested in figuring out how/where this should be updated in the framework.

答:
There's another approach that's worth considering, aside from DataTransformers. Form Events. Specifically FormEvents::PRE_SUBMIT.

From the Symfony Docs:

The FormEvents::PRE_SUBMIT event is dispatched at the beginning of the Form::submit() method.

It can be used to:

Change data from the request, before submitting the data to the form;

Add or remove form fields, before submitting the data to the form.

This would effectively precede any form-level validation.

Body:
On the form level validation in Symfony 3.3, I'm trying to figure out how to make it so that it is case insensitive. It is comparing against an array of choices.

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', CollectionType::class, [
            'entry_type' => ChoiceType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'entry_options'  => array(
                'choices'  => array(
                                "Sample Option",
                                "Sample Option 2",
                                "Sample Option 3",
                                "Sample Option 4"
                            )
            ),
            'error_bubbling' => false
        ]);

Under entry_options in choices is the array that it is using for form validation.

What I'm looking to do is be able to pass a case insensitive value like "sample option" or "sample Option" and have that pass the form level validation.

Thanks in advance for any help on this.

Update - As Kevin mentioned, I'm interested in figuring out how/where this should be updated in the framework.


问:
Angular js ng-click not working
I am trying to add form validation using JavaScript. When I add

```<code> document.getElementById("one").setAttribute("ng-click", "insertData()");
</code>```

to validateForm function, it does not work after I press the button.

When I move that line out of validateForm function it works, but does not perform form validation.

Here is my code:

```<code><!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

</head>
<body>

<div class="container">
   <div ng-app="myapp" ng-controller = "controller">
        <div class="row">
            <div id="divID"> </div>
                <div class="col-sm-12 col-md-10  col-md-offset-1 ">
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                            <input class="form-control" id = "k" placeholder="Name" ng-model = "username" name="user_name" type="text" autofocus>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                                <i class="glyphicon glyphicon-user"></i></span>
                            <input class="form-control" placeholder="NIC" ng-model = "nic" name="NIC" type="text" value="">
                        </div>
                    </div>

             <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"> @</span>
                            <input class="form-control" placeholder="Email" ng-model = "Email" name="email" type="email" value="">
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                                <i class="glyphicon glyphicon-lock"></i></span>
                            <input class="form-control" placeholder="Password" ng-model = "password" name="Password" type="password" value="">
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                                <i class="glyphicon glyphicon-lock"></i></span>
                            <input class="form-control" placeholder="Confierm Password" ng-model = "Conf_password" name="Conf_password" type="password" value="">
                        </div>
                    </div>

                    <div class="form-group">
                        <input type="submit" id = 'one' onclick="validateForm()"  class="btn btn-lg btn-primary btn-block" value="Sign Up">
                    </div>
                </div>
            </div>
       </div>
   </div>
  </body>
</html>
  <Script>
     function validateForm()
       {
       var x = document.getElementById("k").value;
       if (x == "")
         {
         document.getElementById("k").setAttribute("placeholder", "Insert Name");
         }
         else
         {
           //document.getElementById("one").removeAttribute("onclick");
           document.getElementById("one").setAttribute("ng-click", "insertData()");
          }
       }
      // when add this part here code working fine ---- document.getElementById("one").setAttribute("ng-click", "insertData()");

     var app = angular.module("myapp", []);
     app.controller("controller",function($scope,$http){
     $scope.insertData = function()
        {
         $http.post(
        "Signup.php",
        {'username':$scope.username,'nic':$scope.nic,'email':$scope.Email,'password':$scope.password,'Conf_password':$scope.Conf_password }

    ).then(function(data){

     var result = angular.toJson(data.data);
     var myEl = angular.element( document.querySelector( '#divID' ) );
     if(result.replace(/^"|"$/g, '') == 1)
       {
       myEl.replaceWith("<div class='alert alert-success alert-dismissable fade in'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Success!</strong>You have sucessfully registerd. Please login</div>");
       }
     else
        {
         myEl.replaceWith(result.replace(/^"|"$/g, ''));
         }
      $scope.username = null;
    });
  }
});

</script>
</code>```

答:
Ok, what you are trying to do is not how angularjs works; i suggest you to read angularjs form documentation, especially the Binding to form and control state chapter.
Your code seems a clash between jquery and angularjs, i suggest to you to re read angularjs phonecat tutorial or, even better, to try the new version of angular

Title: Angular js ng-click not working

Body:
I am trying to add form validation using JavaScript. When I add

 document.getElementById("one").setAttribute("ng-click", "insertData()");

to validateForm function, it does not work after I press the button.

When I move that line out of validateForm function it works, but does not perform form validation.

Here is my code:

<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                            <input class="form-control" id = "k" placeholder="Name" ng-model = "username" name="user_name" type="text" autofocus>

                            <input class="form-control" placeholder="NIC" ng-model = "nic" name="NIC" type="text" value="">

                             @
                            <input class="form-control" placeholder="Email" ng-model = "Email" name="email" type="email" value="">

                            <input class="form-control" placeholder="Password" ng-model = "password" name="Password" type="password" value="">

                            <input class="form-control" placeholder="Confierm Password" ng-model = "Conf_password" name="Conf_password" type="password" value="">

                        <input type="submit" id = 'one' onclick="validateForm()"  class="btn btn-lg btn-primary btn-block" value="Sign Up">


问:
Convert int 20171116101856 to yyyymmddhhmmss format to be used in datediff function
So I have this table that has date columns in int type.

```<code>last_run_date | last_run_time
   20171116   | 100234
</code>```

Im trying to convert this two values into a datetime to be used in datediff statement.

this is my statement

```<code>SELECT 1
FROM V_Jobs_All_Servers vjas
WHERE JobName='DailyReports_xxxx' and Step_Name='xxxx'
and DATEDIFF(hour, Convert(varchar,STUFF(STUFF(STUFF(STUFF(STUFF(cast(
Convert(varchar(100),vjas.last_run_date) +  Convert(varchar(100),vjas.last_run_time) as varchar)
,5,0,'-'),8,0,'-'),11,0,' '),14,0,':'),17,0,':')), Getdate()) <3
</code>```

This works but only when the last_run_time value is in two digits hour format
101216, but whenever its one digit hour 91316 it fails with the following error,

```<code>The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
</code>```

I am on SQL Server 2005

Body:
So I have this table that has date columns in int type.

last_run_date | last_run_time
   20171116   | 100234

Im trying to convert this two values into a datetime to be used in datediff statement.

this is my statement

SELECT 1
FROM V_Jobs_All_Servers vjas
WHERE JobName='DailyReports_xxxx' and Step_Name='xxxx'
and DATEDIFF(hour, Convert(varchar,STUFF(STUFF(STUFF(STUFF(STUFF(cast(
Convert(varchar(100),vjas.last_run_date) +  Convert(varchar(100),vjas.last_run_time) as varchar)
,5,0,'-'),8,0,'-'),11,0,' '),14,0,':'),17,0,':')), Getdate()) <3

This works but only when the last_run_time value is in two digits hour format
101216, but whenever its one digit hour 91316 it fails with the following error,

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

I am on SQL Server 2005

Body:
You are massively over complicating this, just pad your time value with a leading 0 and convert from there:

declare @t table(last_run_date int, last_run_time int);
insert into @t values(20171116,90234),(20171116,100234);

select last_run_date
      ,last_run_time
      ,convert(datetime,cast(last_run_date as nvarchar(8))
                + ' '
                + stuff(stuff(right('0' + cast(last_run_time as nvarchar(6))
                                   ,6)
                             ,5,0,':')
                       ,3,0,':')
             ,112) as DateTimeData
from @t

Output:

+---------------+---------------+-------------------------+
| last_run_date | last_run_time |      DateTimeData       |
+---------------+---------------+-------------------------+
|      20171116 |        100234 | 2017-11-16 09:02:34.000 |
|      20171116 |        100234 | 2017-11-16 10:02:34.000 |
+---------------+---------------+-------------------------+


问:
Print string values in object list
Im currently trying to make an addressbook application that holds some person data in an object which is then added to a list. Im currently making a method to try and list the data when prompted but the information isnt showing, does anyone know how I can go about fixing this?

```<code>namespace AddressBook
{
    class Student : Person
    {
    public String StudentID { get; set; }
    public String grade { get; set; }

    public List<Student> studentList = new List<Student>();

 public void addStudent(string firstName, string lastName, string address, string city, string country, string postcode, string StudentID, string grade )
    {
        Student student = new Student();
        student.firstName = firstName;
        student.lastName = lastName;
        student.address = address;
        student.city = city;
        student.country = country;
        student.postcode = postcode;
        student.StudentID = StudentID;
        student.grade = grade;
        studentList.Add(student);
    }

 public void listStudentData()
    {
        String fname ="", lname="", add="", city="", country="", post="", id="", grd = "";
        String[,] index = { { "First name: ", "Last Name: ", "Address: ", "City: ", "Country: ", "Postcode: ", "StudentID: ", "Grade: " }, { fname, lname, add, city, country, post, id, grd }, };
        for (int i = 0; i < studentList.Count; i++)
        {
            fname = (studentList[i].firstName.ToString());
            lname = (studentList[i].lastName.ToString());
            add = (studentList[i].address.ToString());
            city = (studentList[i].city.ToString());
            country = (studentList[i].country.ToString());
            post = (studentList[i].postcode.ToString());
            id = (studentList[i].StudentID.ToString());
            grd = (studentList[i].grade.ToString());
            Console.WriteLine(index[0, i] + index[1,i]);
        }
        Console.WriteLine("");
    }

}
</code>```

}

The format I want to print out is
"First Name: John"
"Last Name: Smith" etc

however the current format is:
"First Name: "

Any advice would be much appreciated

答:
Posting my solution too, you might find it useful.

I see in the original sample that the base Person class is missing, providing it here:

```<code>public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string PostCode { get; set; }

    public override string ToString()
    {
        return $"First name: {FirstName}, Last name: {LastName}, Address: {Address}, City: {City}, Country: {Country}, Post code: {PostCode}";
    }
}
</code>```

You can see that we are overriding the ToString() method to return the intended literal representation. As others have pointed out it is always better to use PascalCase notation for public properties in C# (common convention). Next comes the derived Student class:

```<code>public class Student : Person
{
    public String StudentID { get; set; }
    public String Grade { get; set; }

    public override string ToString()
    {
        return $"{base.ToString()}, Student ID: {StudentID}, Grade: {Grade}";
    }
}
</code>```

Here we are adding the StudentID and Grade properties and again overriding the ToString() method of the Object class. The override makes use of the ToString() method of our base class which we wrote previously.

Finally, an example of printing out a list of Student objects:

```<code>static void Main(string[] args)
{
    var students = new List<Student>();
    students.Add(
        new Student
        {
            FirstName = "John",
            LastName = "Doe",
            Address = "43 North West",
            City = "Capetown",
            Country = "South Africa",
            PostCode = "12345",
            Grade = "A+",
            StudentID = Guid.NewGuid().ToString("N")
        });

    foreach (Student student in students)
    {
        Console.WriteLine(student);
    }
}
</code>```

And the output is:

```<code>First name: John, Last name: Doe, Address: 43 North West, City: Capetown, Country: South Africa, Post code: 12345, Student ID: 975d7bf2e80f4406b14119f8fbc3018e, Grade: A+
</code>```

Title: Print string values in object list

Body:
Im currently trying to make an addressbook application that holds some person data in an object which is then added to a list. Im currently making a method to try and list the data when prompted but the information isnt showing, does anyone know how I can go about fixing this?

namespace AddressBook
{
    class Student : Person
    {
    public String StudentID { get; set; }
    public String grade { get; set; }

    public List<Student> studentList = new List<Student>();

 public void addStudent(string firstName, string lastName, string address, string city, string country, string postcode, string StudentID, string grade )
    {
        Student student = new Student();
        student.firstName = firstName;
        student.lastName = lastName;
        student.address = address;
        student.city = city;
        student.country = country;
        student.postcode = postcode;
        student.StudentID = StudentID;
        student.grade = grade;
        studentList.Add(student);
    }

 public void listStudentData()
    {
        String fname ="", lname="", add="", city="", country="", post="", id="", grd = "";
        String[,] index = { { "First name: ", "Last Name: ", "Address: ", "City: ", "Country: ", "Postcode: ", "StudentID: ", "Grade: " }, { fname, lname, add, city, country, post, id, grd }, };
        for (int i = 0; i < studentList.Count; i++)
        {
            fname = (studentList[i].firstName.ToString());
            lname = (studentList[i].lastName.ToString());
            add = (studentList[i].address.ToString());
            city = (studentList[i].city.ToString());
            country = (studentList[i].country.ToString());
            post = (studentList[i].postcode.ToString());
            id = (studentList[i].StudentID.ToString());
            grd = (studentList[i].grade.ToString());
            Console.WriteLine(index[0, i] + index[1,i]);
        }
        Console.WriteLine("");
    }

}

}

The format I want to print out is
"First Name: John"
"Last Name: Smith" etc

however the current format is:
"First Name: "

Any advice would be much appreciated

Body:
Posting my solution too, you might find it useful.

I see in the original sample that the base Person class is missing, providing it here:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string PostCode { get; set; }

    public override string ToString()
    {
        return $"First name: {FirstName}, Last name: {LastName}, Address: {Address}, City: {City}, Country: {Country}, Post code: {PostCode}";
    }
}

You can see that we are overriding the ToString() method to return the intended literal representation. As others have pointed out it is always better to use PascalCase notation for public properties in C# (common convention). Next comes the derived Student class:

public class Student : Person
{
    public String StudentID { get; set; }
    public String Grade { get; set; }

    public override string ToString()
    {
        return $"{base.ToString()}, Student ID: {StudentID}, Grade: {Grade}";
    }
}

Here we are adding the StudentID and Grade properties and again overriding the ToString() method of the Object class. The override makes use of the ToString() method of our base class which we wrote previously.

Finally, an example of printing out a list of Student objects:

static void Main(string[] args)
{
    var students = new List<Student>();
    students.Add(
        new Student
        {
            FirstName = "John",
            LastName = "Doe",
            Address = "43 North West",
            City = "Capetown",
            Country = "South Africa",
            PostCode = "12345",
            Grade = "A+",
            StudentID = Guid.NewGuid().ToString("N")
        });

    foreach (Student student in students)
    {
        Console.WriteLine(student);
    }
}

And the output is:

First name: John, Last name: Doe, Address: 43 North West, City: Capetown, Country: South Africa, Post code: 12345, Student ID: 975d7bf2e80f4406b14119f8fbc3018e, Grade: A+


问:
MySQL Query with multiple AND statements seems to be ignoring one
I'm trying to run a query on a MySQL database, but I found that it seems to be ignoring the 'status' item.

```<code>SELECT * FROM  `posts`
WHERE
      `tags` LIKE '%gda%'
   OR `tags` LIKE '%contests%'
   OR `tags` LIKE '%merch%'
  AND `newsID` != '2134'
  AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5
</code>```

In that example, it's still pulling items even if 'status' is set to 0. What am I doing wrong?

答:
Maybe you should use some brackets I don't know what combinations you want but try this:</p>

```<code>  SELECT * FROM  `posts`
    WHERE
         ( `tags` LIKE '%gda%'
       OR `tags` LIKE '%contests%'
       OR `tags` LIKE '%merch%'
      )
      AND `newsID` != '2134'
      AND `status` > '1'
    ORDER BY  `postDate` DESC  LIMIT 5
</code>```

Body:
I'm trying to run a query on a MySQL database, but I found that it seems to be ignoring the 'status' item.

SELECT * FROM  `posts`
WHERE
      `tags` LIKE '%gda%'
   OR `tags` LIKE '%contests%'
   OR `tags` LIKE '%merch%'
  AND `newsID` != '2134'
  AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5

In that example, it's still pulling items even if 'status' is set to 0. What am I doing wrong?

Body:
Maybe you should use some brackets I don't know what combinations you want but try this:

  SELECT * FROM  `posts`
    WHERE
         ( `tags` LIKE '%gda%'
       OR `tags` LIKE '%contests%'
       OR `tags` LIKE '%merch%'
      )
      AND `newsID` != '2134'
      AND `status` > '1'
    ORDER BY  `postDate` DESC  LIMIT 5


问:
Returning data after sorting through multiple arrays
I have nested arrays within an object, and I need to extract these values, and sort them into alphabetical order which will then be displayed in a table.

I am using the localeCompare method but it is returning:

```<code>Cannot read property 'localeCompare' of null
</code>```

To be honest, I am not sure I am approaching this correctly. Using sort you can compare a to b to sort them into alphabetical order. I am getting confused how to compare the values from the arrays within a and b. I am using the first sort on tableData to access the array, and the using a second sort to compare the values that I pushed to array clientRefArr

```<code>if(params.sorting().clientRef) {

        var clientRefArr = [];

        tableData.sort(function(a, b){

            a.renewalUIs.forEach(function(data, i){
                clientRefArr.push(data.patentUI.clientRef);
            })

            return clientRefArr.sort(function(a, b){
                console.log(a.localeCompare(b))
                // return a.localeCompare(b)
            })

        })

    orderedData = tableData;

}

return orderedData;
</code>```

Question

Why is the error Cannot read property 'localeCompare' of null being returned?Am I approaching this issue completely wrong?

```<code>//JSON

[
 0: {
     transRef: "IX1000013"
     renewalProgress: 30
     renewalUIs: [
        0: {
            patentUI: {
               business: null
               clientRef: P0101011 // this is the required value
            }
            renewalAttemptsMade: 1
            renewalDueDate: 1514764740000
         }
     ]

   },
 1: {
     transRef: "IX100333"
     renewalProgress: 55
     renewalUIs: [
        0: {
            patentUI: {
               business: null
               clientRef: P0101011 // this is the required value
            }
            renewalAttemptsMade: 1
            renewalDueDate: 1514764740000
         },
        1: {
            patentUI: {
               business: null
               clientRef: P5551011 // this is the required value
            }
            renewalAttemptsMade: 3
            renewalDueDate: 174834740000
         }
     ]

   }
]
</code>```

答:
You could take a default value for both parts

```<code>(a || '').localeCompare(b || '')
</code>```

for sorting the null values or even all falsy values to top.

An attempt with the given data (I changed some value, to get some sorting).

It now sorts the inner arrays renewalUIs first and then it takes the first element for sorting the outer array.

var array = [{ transRef: "IX1000013", renewalProgress: 30, renewalUIs: [{ patentUI: { business: null, clientRef: "P9101011" }, renewalAttemptsMade: 1, renewalDueDate: 1514764740000 }] }, { transRef: "IX100333", renewalProgress: 55, renewalUIs: [{ patentUI: { business: null, clientRef: "P7101011" }, renewalAttemptsMade: 1, renewalDueDate: 1514764740000 }, { patentUI: { business: null, clientRef: "P5551011" }, renewalAttemptsMade: 3, renewalDueDate: 174834740000 }] }];

array.forEach(function (o) {
    o.renewalUIs.sort(function (a, b) {
        return a.patentUI.clientRef.localeCompare(b.patentUI.clientRef);
    });
});

array.sort(function (a, b) {
    return a.renewalUIs[0].patentUI.clientRef.localeCompare(b.renewalUIs[0].patentUI.clientRef);
});

console.log(array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have nested arrays within an object, and I need to extract these values, and sort them into alphabetical order which will then be displayed in a table.

I am using the localeCompare method but it is returning:

Cannot read property 'localeCompare' of null

To be honest, I am not sure I am approaching this correctly. Using sort you can compare a to b to sort them into alphabetical order. I am getting confused how to compare the values from the arrays within a and b. I am using the first sort on tableData to access the array, and the using a second sort to compare the values that I pushed to array clientRefArr

if(params.sorting().clientRef) {

        var clientRefArr = [];

        tableData.sort(function(a, b){

            a.renewalUIs.forEach(function(data, i){
                clientRefArr.push(data.patentUI.clientRef);
            })

            return clientRefArr.sort(function(a, b){
                console.log(a.localeCompare(b))
                // return a.localeCompare(b)
            })

        })

    orderedData = tableData;

}

return orderedData;

Question

Why is the error Cannot read property 'localeCompare' of null being returned?Am I approaching this issue completely wrong?

//JSON

[
 0: {
     transRef: "IX1000013"
     renewalProgress: 30
     renewalUIs: [
        0: {
            patentUI: {
               business: null
               clientRef: P0101011 // this is the required value
            }
            renewalAttemptsMade: 1
            renewalDueDate: 1514764740000
         }
     ]

   },
 1: {
     transRef: "IX100333"
     renewalProgress: 55
     renewalUIs: [
        0: {
            patentUI: {
               business: null
               clientRef: P0101011 // this is the required value
            }
            renewalAttemptsMade: 1
            renewalDueDate: 1514764740000
         },
        1: {
            patentUI: {
               business: null
               clientRef: P5551011 // this is the required value
            }
            renewalAttemptsMade: 3
            renewalDueDate: 174834740000
         }
     ]

   }
]

Body:
You could take a default value for both parts

(a || '').localeCompare(b || '')

for sorting the null values or even all falsy values to top.

An attempt with the given data (I changed some value, to get some sorting).

It now sorts the inner arrays renewalUIs first and then it takes the first element for sorting the outer array.

var array = [{ transRef: "IX1000013", renewalProgress: 30, renewalUIs: [{ patentUI: { business: null, clientRef: "P9101011" }, renewalAttemptsMade: 1, renewalDueDate: 1514764740000 }] }, { transRef: "IX100333", renewalProgress: 55, renewalUIs: [{ patentUI: { business: null, clientRef: "P7101011" }, renewalAttemptsMade: 1, renewalDueDate: 1514764740000 }, { patentUI: { business: null, clientRef: "P5551011" }, renewalAttemptsMade: 3, renewalDueDate: 174834740000 }] }];

array.forEach(function (o) {
    o.renewalUIs.sort(function (a, b) {
        return a.patentUI.clientRef.localeCompare(b.patentUI.clientRef);
    });
});

array.sort(function (a, b) {
    return a.renewalUIs[0].patentUI.clientRef.localeCompare(b.renewalUIs[0].patentUI.clientRef);
});

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Using NOT LIKE for multiple mutiple columns
I want to search for particular value in multiple columns. Is there any way to optimize this query?

```<code>SELECT TOP (200) Events.EventDate, AVDCAV.CAVCH1, AVDCAV.CAVCH2, AVDCAV.CAVCH3, AVDCAV.CAVCH4, AVDCAV.CAVCH5, AVDCAV.CAVCH6, AVDCAV.CAVCH7, AVDCAV.CAVCH8, AVDCAV.CAVCH9
FROM AVDCAV
   INNER JOIN Events ON AVDCAV.IDEvent=Events.EventID
WHERE CAVCH9 NOT LIKE '0.0000000000' OR CAVCH8 NOT LIKE '0.0000000000' OR CAVCH7 NOT LIKE '0.0000000000' OR CAVCH1 NOT LIKE '0.0000000000'
ORDER BY AVDCAV.IDEvent DESC
</code>```

I'm getting the data from SQL Express 2008 R2.

答:
Without knowing table sizes, current indices etc, you could try adding this index

```<code>CREATE NONCLUSTERED INDEX IX_AVDCAV ON AVDCAV ( IDEvent )
INCLUDE ( CAVCH1, CAVCH2, CAVCH3, CAVCH4, CAVCH5, CAVCH6, CAVCH7, CAVCH8, CAVCH9 )
</code>```

to see if performance improves

Body:
I want to search for particular value in multiple columns. Is there any way to optimize this query?

SELECT TOP (200) Events.EventDate, AVDCAV.CAVCH1, AVDCAV.CAVCH2, AVDCAV.CAVCH3, AVDCAV.CAVCH4, AVDCAV.CAVCH5, AVDCAV.CAVCH6, AVDCAV.CAVCH7, AVDCAV.CAVCH8, AVDCAV.CAVCH9
FROM AVDCAV
   INNER JOIN Events ON AVDCAV.IDEvent=Events.EventID
WHERE CAVCH9 NOT LIKE '0.0000000000' OR CAVCH8 NOT LIKE '0.0000000000' OR CAVCH7 NOT LIKE '0.0000000000' OR CAVCH1 NOT LIKE '0.0000000000'
ORDER BY AVDCAV.IDEvent DESC

I'm getting the data from SQL Express 2008 R2.

Body:
Without knowing table sizes, current indices etc, you could try adding this index

CREATE NONCLUSTERED INDEX IX_AVDCAV ON AVDCAV ( IDEvent )
INCLUDE ( CAVCH1, CAVCH2, CAVCH3, CAVCH4, CAVCH5, CAVCH6, CAVCH7, CAVCH8, CAVCH9 )

to see if performance improves


问:
Wordpress plugins and git sync across environments
I've searched a lot about this problem, but I didn't found a "perfect" solution. I am using Wordpress with GIT and I'm currently using this gitignore:

https://gist.github.com/salcode/9940509

My question is on the plugins management:

It's very useful to have plugins tracked across environments and this gitignore tracks them unless you ignore specific plugins (like hello.php ecc..) which is fine. The problem is when the plugins have been updated. The files will sync because they are tracked in the GIT repo, which is ok. But what if the updated version of the plugin needs a DB update/upgrade, too? If so, you must always deactivate and activate again all the updated and pulled plugins to ensure eventual tables of the plugins are synced, too.

Do you have a solution for this problem or it is better to not track the plugins at all and install them manually on each environment which is a little bit frustrating to me?

Thanks

答:
You can inject Plugin dependencies with TGM Plugin Activation

This library allow you to make an list of plugins that need to be installed in your theme/plugin. Is very easy to use and give you an better control (force activation/desactivation, private/git plugins, etc).

This way, you don't need to track the plugins folder.

Much better, you can track only your project this way (the plugin or theme only).

NOTE: Even if you use this tool, always integrate with external plugins safely (detect if it is activated, if function exists, using hooks and filters, etc). This way your project cannot crash WordPress.


答:
Here's an ugly way...</p>

```<code>declare @table table (last_run_date int, last_run_time int)
insert into @table
values
(20171116,100234),
(20171116,91316)

select
    cast(cast(cast(last_run_date as varchar) as datetime) + ' ' + stuff(stuff(last_run_time,len(last_run_time) - 1,0,':'),len(stuff(last_run_time,len(last_run_time) - 1,0,':')) - 4,0,':') as datetime)
from @table
</code>```

Title: Convert int 20171116101856 to yyyymmddhhmmss format to be used in datediff function

Body:
Here's an ugly way...

declare @table table (last_run_date int, last_run_time int)
insert into @table
values
(20171116,100234),
(20171116,91316)

select
    cast(cast(cast(last_run_date as varchar) as datetime) + ' ' + stuff(stuff(last_run_time,len(last_run_time) - 1,0,':'),len(stuff(last_run_time,len(last_run_time) - 1,0,':')) - 4,0,':') as datetime)
from @table


问:
Multi threading IMAP backup [python]
I have the following python script which works freat to save IMAP folder to local .eml files. I want to do backup of my old email, but it has pretty large inbox. Is there anyway the below code can be modified with multi threads? Or perhaps several loops, so that it works faster on large IMAP folders?

Thanks a mil!

```<code>import sys
import imaplib
import getpass

IMAP_SERVER = ''
EMAIL_ACCOUNT = ""
EMAIL_FOLDER = "Inbox"
OUTPUT_DIRECTORY = './'

PASSWORD = getpass.getpass()

def process_mailbox(M):
    """
    Dump all emails in the folder to files in output directory.
    """

    rv, data = M.search(None, "ALL")
    if rv != 'OK':
        print "No messages found!"
        return

    for num in data[0].split():
        rv, data = M.fetch(num, '(RFC822)')
        if rv != 'OK':
            print "ERROR getting message", num
            return
        print "Writing message ", num

        f = open('%s/%s.eml' %(OUTPUT_DIRECTORY, num), 'wb')
        f.write(data[0][1])
        f.close()

def main():
    M = imaplib.IMAP4_SSL(IMAP_SERVER)
    M.login(EMAIL_ACCOUNT, PASSWORD)
    rv, data = M.select(EMAIL_FOLDER)
    if rv == 'OK':
        print "Processing mailbox: ", EMAIL_FOLDER
        process_mailbox(M)
        M.close()
    else:
        print "ERROR: Unable to open mailbox ", rv
    M.logout()

if __name__ == "__main__":
    main()
</code>```

答:
Have you tried fetching more than one message at a time?  Fetch is more than capable of fetching multiple messages: m.fetch("1:*", (RFC822)") will fetch ALL the messages in your mailbox, but that's a good way to run out of memory.

If you have lots of memory, maybe try fetching in batches of one hundred.  This will probably speed it up about 20 to 50 times, since the bottleneck is usually network roundtrips.

Title: Multi threading IMAP backup [python]

Body:
I have the following python script which works freat to save IMAP folder to local .eml files. I want to do backup of my old email, but it has pretty large inbox. Is there anyway the below code can be modified with multi threads? Or perhaps several loops, so that it works faster on large IMAP folders?

Thanks a mil!

import sys
import imaplib
import getpass

IMAP_SERVER = ''
EMAIL_ACCOUNT = ""
EMAIL_FOLDER = "Inbox"
OUTPUT_DIRECTORY = './'

PASSWORD = getpass.getpass()

def process_mailbox(M):
    """
    Dump all emails in the folder to files in output directory.
    """

    rv, data = M.search(None, "ALL")
    if rv != 'OK':
        print "No messages found!"
        return

    for num in data[0].split():
        rv, data = M.fetch(num, '(RFC822)')
        if rv != 'OK':
            print "ERROR getting message", num
            return
        print "Writing message ", num

        f = open('%s/%s.eml' %(OUTPUT_DIRECTORY, num), 'wb')
        f.write(data[0][1])
        f.close()

def main():
    M = imaplib.IMAP4_SSL(IMAP_SERVER)
    M.login(EMAIL_ACCOUNT, PASSWORD)
    rv, data = M.select(EMAIL_FOLDER)
    if rv == 'OK':
        print "Processing mailbox: ", EMAIL_FOLDER
        process_mailbox(M)
        M.close()
    else:
        print "ERROR: Unable to open mailbox ", rv
    M.logout()

if __name__ == "__main__":
    main()


问:
How to convert a column with missing values to string?
I need to export a dataframe from pandas to Microsoft SQL Server using SQL Alchemy. Many columns are strings, with missing values and with some very long integers, e.g. 999999999999999999999999999999999 . These numbers are some kind of foreign key, so the value itself doesn't mean anything, so I can convert those to strings.

This causes the following error in SQL Alchemy when trying to export to SQL:

OverflowError: int too big to convert
```
<p>I tried converting to string with <code>astype(str)</code>, but then I run into the problem that missing values, identified as nans, are converted into the string 'nan' - so SQL does not see them as nulls but as the string 'nan'.</p>
<p><strong>The only solution I have found is to first convert to str then replace 'nan' with <code>numpy.nan</code>. Is there a better way?</strong> This is cumbersome, relatively slow, and as unpythonic as it can get: first I convert everything to string, the conversion turns nulls into strings, so I convert those into NaN, which can be a float only, and I end up with a mixed-type column.</p>
<p>Or do I simply have to suck it up and accept that pandas is dreadful at dealing with missing values?</p>
<p>I have an example below:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np, pandas as pd, time

from sqlalchemy import create_engine, MetaData, Table, select
import sqlalchemy as sqlalchemy

start=time.time()
ServerName = "DESKTOP-MRX\SQLEXPRESS"
Database = 'MYDATABASE'
params = '?driver=SQL+Server+Native+Client+11.0'
engine = create_engine('mssql+pyodbc://' + ServerName + '/'+ Database + params, encoding ='latin1' )
conn=engine.connect()

df=pd.DataFrame()
df['mixed']=np.arange(0,9)
df.iloc[0,0]='test'
df['numb']=3.0
df['text']='my string'
df.iloc[0,2]=np.nan
df.iloc[1,2]=999999999999999999999999999999999

df['text']=df['text'].astype(str).replace('nan',np.nan)

df.to_sql('test_df_mixed_types', engine, schema='dbo', if_exists='replace')
</code>```

答:
Using np.where would certainly be a bit faster compared to replace i.e

```<code>df['text'] = np.where(pd.isnull(df['text']),df['text'],df['text'].astype(str))
</code>```

Timings :

```<code>%%timeit
df['text'].astype(str).replace('nan',np.nan)
1000 loops, best of 3: 536 µs per loop

%%timeit
np.where(pd.isnull(df['text']),df['text'],df['text'].astype(str))
1000 loops, best of 3: 274 µs per loop

x = pd.concat([df['text']]*10000)
%%timeit
np.where(pd.isnull(x),x,x.astype(str))
10 loops, best of 3: 28.8 ms per loop

%%timeit
x.astype(str).replace('nan',np.nan)
10 loops, best of 3: 33.5 ms per loop
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to export a dataframe from pandas to Microsoft SQL Server using SQL Alchemy. Many columns are strings, with missing values and with some very long integers, e.g. 999999999999999999999999999999999 . These numbers are some kind of foreign key, so the value itself doesn't mean anything, so I can convert those to strings.

This causes the following error in SQL Alchemy when trying to export to SQL:

OverflowError: int too big to convert

I tried converting to string with astype(str), but then I run into the problem that missing values, identified as nans, are converted into the string 'nan' - so SQL does not see them as nulls but as the string 'nan'.

The only solution I have found is to first convert to str then replace 'nan' with numpy.nan. Is there a better way? This is cumbersome, relatively slow, and as unpythonic as it can get: first I convert everything to string, the conversion turns nulls into strings, so I convert those into NaN, which can be a float only, and I end up with a mixed-type column.

Or do I simply have to suck it up and accept that pandas is dreadful at dealing with missing values?

I have an example below:

import numpy as np, pandas as pd, time

from sqlalchemy import create_engine, MetaData, Table, select
import sqlalchemy as sqlalchemy

start=time.time()
ServerName = "DESKTOP-MRX\SQLEXPRESS"
Database = 'MYDATABASE'
params = '?driver=SQL+Server+Native+Client+11.0'
engine = create_engine('mssql+pyodbc://' + ServerName + '/'+ Database + params, encoding ='latin1' )
conn=engine.connect()

df=pd.DataFrame()
df['mixed']=np.arange(0,9)
df.iloc[0,0]='test'
df['numb']=3.0
df['text']='my string'
df.iloc[0,2]=np.nan
df.iloc[1,2]=999999999999999999999999999999999

df['text']=df['text'].astype(str).replace('nan',np.nan)

df.to_sql('test_df_mixed_types', engine, schema='dbo', if_exists='replace')

Body:
Using np.where would certainly be a bit faster compared to replace i.e

df['text'] = np.where(pd.isnull(df['text']),df['text'],df['text'].astype(str))

Timings :

%%timeit
df['text'].astype(str).replace('nan',np.nan)
1000 loops, best of 3: 536 µs per loop

%%timeit
np.where(pd.isnull(df['text']),df['text'],df['text'].astype(str))
1000 loops, best of 3: 274 µs per loop

x = pd.concat([df['text']]*10000)
%%timeit
np.where(pd.isnull(x),x,x.astype(str))
10 loops, best of 3: 28.8 ms per loop

%%timeit
x.astype(str).replace('nan',np.nan)
10 loops, best of 3: 33.5 ms per loop


问:
Get order on observer event
im trying to get the order data from the observer, but is returning me null, is happening me only on the "sales_order_credit_memo_save_after", dont understang why is happening in this specific one. The event is for sure loading the right method, but in the order data gets null.

my code here.
config.xml:

```<code><events>
            <sales_order_save_after>
                <observers>
                    <ordertest>
                        <type>model</type>
                        <class>ordertest/observer</class>
                        <method>createInvoice</method>
                    </ordertest>
                </observers>
            </sales_order_save_after>

            <sales_order_creditmemo_save_after>
                <observers>
                    <ordertest>
                        <type>model</type>
                        <class>ordertest/observer</class>
                        <method>createCredit</method>
                    </ordertest>
                </observers>
            </sales_order_creditmemo_save_after>
        </events>
</code>```

Observer:

```<code>public function createCredit($observer) {
        $order = $observer->getEvent()->getOrder();
var_dump($order);
die;
</code>```

答:
I needed to add getCreditmomo method to get the order:</p>

```<code>$order = $observer->getEvent()->getCreditmemo()->getOrder();
</code>```

Title: Get order on observer event

Body:
im trying to get the order data from the observer, but is returning me null, is happening me only on the "sales_order_credit_memo_save_after", dont understang why is happening in this specific one. The event is for sure loading the right method, but in the order data gets null.

my code here.
config.xml:

<events>
            <sales_order_save_after>
                <observers>
                    <ordertest>
                        <type>model</type>
                        <class>ordertest/observer</class>
                        <method>createInvoice</method>
                    </ordertest>
                </observers>
            </sales_order_save_after>

            <sales_order_creditmemo_save_after>
                <observers>
                    <ordertest>
                        <type>model</type>
                        <class>ordertest/observer</class>
                        <method>createCredit</method>
                    </ordertest>
                </observers>
            </sales_order_creditmemo_save_after>
        </events>

Observer:

public function createCredit($observer) {
        $order = $observer->getEvent()->getOrder();
var_dump($order);
die;

Body:
I needed to add getCreditmomo method to get the order:

$order = $observer->getEvent()->getCreditmemo()->getOrder();


问:
Laravel required_if does not accept other parameters
I have some problems with Laravel's validation. I'm using required_if validator.

What I want to achieve: When the hilightColorBool is true the hilightColor should be required, should be integer between min:1 and max:5.

```<code>...
'hilightColorBool' => 'required|boolean',
'hilightColor' => 'required_if:hilightColorBool,1|integer|min:1|max:5'
...
</code>```

But when I'm doing it like above it always returns that hilghtColor is bool, when I do remove the integer, min and max from hilightColor it works good, but I need to validate anyway if it is integer between 1 and 5. It seems weird to me.

答:
Going on from my comment, i may do it like this:

```<code>$rules = [
    'hilightColorBool' => 'required|boolean',
];

if (is_bool($request->get('hilightColorBool'))) {
    $rules['hilightColor'] = 'required|integer|min:1|max:5';
}
</code>```

then simply do:

```<code>$request->validate($rules);
</code>```

Body:
I have some problems with Laravel's validation. I'm using required_if validator.

What I want to achieve: When the hilightColorBool is true the hilightColor should be required, should be integer between min:1 and max:5.

...
'hilightColorBool' => 'required|boolean',
'hilightColor' => 'required_if:hilightColorBool,1|integer|min:1|max:5'
...

But when I'm doing it like above it always returns that hilghtColor is bool, when I do remove the integer, min and max from hilightColor it works good, but I need to validate anyway if it is integer between 1 and 5. It seems weird to me.

Body:
Going on from my comment, i may do it like this:

$rules = [
    'hilightColorBool' => 'required|boolean',
];

if (is_bool($request->get('hilightColorBool'))) {
    $rules['hilightColor'] = 'required|integer|min:1|max:5';
}

then simply do:

$request->validate($rules);


问:
IDE's Java runtime (1.8u66) is outdated - this may cause stability issues. Please update to 1.8.0u112 or newer while opening PyCharm Community Edition
I recently downloaded PyCharm Community Edition for automation development using Python3. When i launch pycharm i am getting following alert in Event Log to upgrade my Java runtime.
I am using Centos 6.7 and how can i update my Java runtime?

I have tried switching Java runtime on PyCharm but since i have not upgraded the java runtime on my machine i am not able to select the lates runtime on PyCharm.

Error:
IDE's Java runtime (1.8u66) is outdated - this may cause stability issues. Please update to 1.8.0u112 or newer

答:
If you don't have the latest JDK, download it from: Download latest JAVA JDK HERE

Then ---> Start the IDE, use Help | Find Action (Ctrl+Shift+A or Cmd+Shift+A on Mac), type "Switch IDE Boot JDK" select it, press Enter.


答:
inline-block takes into account the whitespace. You need to remove it in order to make this work

Section 1

Section 2
```

Title: Dividing the page into columns using inline block not working

Body:
I want a solution by using inline-block not by using float:left.

    *{
     margin:0;
  padding:0;
 }
 body{
     margin:0;
  padding:0;
 }

     Section 1

     Section 2

Is there a solution ?

Body:
inline-block takes into account the whitespace. You need to remove it in order to make this work

<div style="width: 50%;background-color: #4caf50;display: inline-block;">Section 1</div><div style="width: 50%;background-color: #ff5722;display: inline-block;">Section 2</div>


问:
Oracle SQL - Count XML nodes in a clob type column
I was trying to write an optimized SQL query to count a specific XML node in clob type column, for now I'm using a REGEXP_COUNT to browse through all rows and all XMLs, but this is terribly slow.

Like this:

```<code>SELECT sum(REGEXP_COUNT(clobtype_column_withXMLs, '/Node_Closing_tag', 1)) as 'Node_number' FROM MY_TABLE;
</code>```

This works, but with hundreds of millions of tags it takes literally ages.

I want to bypass the XML structure and shorten the count time. I have found some things, but most of them involve changing the column type to xml and use xquery and other DML functions.

In my case I can't modify the table, I only need the number, how many times the specified node occurs in the column.

My table structure:

not an XML Table, various column types and a CLOB type column, in which every row contains a different sized XML (hundreds of millions of characters).
The XML has pretty complex structure, the one node I'm searching for is in the middle:

```<code>1/2/3/4/5/I'm_searching_for_this/contains_multiple_nodes
</code>```

Is there any fast way to count nodes in a structure like this, without modifying anything in the table? With fast I mean, count 500 million nodes in a couple of hours maximum. (text search takes 24h+)

答:
The replace and measure length difference trick shoudl work for you with the same result as the REGEXP_COUNT (not necessary on the same precision when you parse XML and counts elements, which should have the ultimate precision).

The advantage of the REPLACE approach is that it will be the fastest implementation.

Simple

replace each occurence of the searched substring in the original string with NULL

calculate the difference of length of the original string and the replaced one

divide the result with the length of the substring to get the result count

.

```<code>select
 sum(REGEXP_COUNT(clobtype_column_withXMLs, '/Node_Closing_tag', 1)) cnt1,
 sum( (length(clobtype_column_withXMLs) - length(replace(clobtype_column_withXMLs,'/Node_Closing_tag',null)))  / length('/Node_Closing_tag')) cnt2
from tst
</code>```

I'd recomend to perform some test using different search substrings

```<code> /tag
 tag/
 <tag>
 </tag>
 <tag/>
</code>```

and compare the results to see if this imethod is reliable.

Body:
I was trying to write an optimized SQL query to count a specific XML node in clob type column, for now I'm using a REGEXP_COUNT to browse through all rows and all XMLs, but this is terribly slow.

Like this:

SELECT sum(REGEXP_COUNT(clobtype_column_withXMLs, '/Node_Closing_tag', 1)) as 'Node_number' FROM MY_TABLE;

This works, but with hundreds of millions of tags it takes literally ages.

I want to bypass the XML structure and shorten the count time. I have found some things, but most of them involve changing the column type to xml and use xquery and other DML functions.

In my case I can't modify the table, I only need the number, how many times the specified node occurs in the column.

My table structure:

not an XML Table, various column types and a CLOB type column, in which every row contains a different sized XML (hundreds of millions of characters).
The XML has pretty complex structure, the one node I'm searching for is in the middle:

1/2/3/4/5/I'm_searching_for_this/contains_multiple_nodes

Is there any fast way to count nodes in a structure like this, without modifying anything in the table? With fast I mean, count 500 million nodes in a couple of hours maximum. (text search takes 24h+)

Body:
The replace and measure length difference trick shoudl work for you with the same result as the REGEXP_COUNT (not necessary on the same precision when you parse XML and counts elements, which should have the ultimate precision).

The advantage of the REPLACE approach is that it will be the fastest implementation.

Simple

replace each occurence of the searched substring in the original string with NULL

calculate the difference of length of the original string and the replaced one

divide the result with the length of the substring to get the result count

.

select
 sum(REGEXP_COUNT(clobtype_column_withXMLs, '/Node_Closing_tag', 1)) cnt1,
 sum( (length(clobtype_column_withXMLs) - length(replace(clobtype_column_withXMLs,'/Node_Closing_tag',null)))  / length('/Node_Closing_tag')) cnt2
from tst

I'd recomend to perform some test using different search substrings

 /tag
 tag/
 <tag>
 </tag>
 <tag/>

and compare the results to see if this imethod is reliable.