问:
angular 2 function continue before return data from API
I have a problem in Angular 2 that function continue work and does not waiting getting data from API.

HTTPHelper Class

```<code>import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { ReturnResultViewModel } from './ReturnResultViewModel';

export class HttpHelpers {

     _result: any = null;
     _errormsg: any = null;
     _returnResultViewModel: ReturnResultViewModel;

     constructor(private http: Http) {
         this._returnResultViewModel = new ReturnResultViewModel();
    }

    postaction(param: any, path: string) {
        let body = JSON.stringify(param);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(path, body, options)
            .map((m:Response) =>  m.json())
    }
}
</code>```

HomeUserService Class

```<code>import 'rxjs/add/operator/map';
import { HttpHelpers } from '../../../HttpHelpers';
import { usersHome } from "././Home.users.ViewModel";
import { ReturnResultViewModel } from "../../../ReturnResultViewModel";

import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
Injectable()

export class HomeUsersService extends HttpHelpers {
    private _UrlLogin: string = "Accounts/getAllUsers";

    constructor( @Inject(Http) private _http: Http) {
        super(_http);
    }
    private _usersHome: usersHome[];
    getAllUsers(): usersHome[]{

        alert(2);
         this.postaction(null, this._UrlLogin)
            .subscribe(result =>
                this._returnResultViewModel = result);

         if (this._returnResultViewModel == null)
         {
             alert("NULL");
             return null;
         }
         else {
             alert("Has DATA");
             this._usersHome = this._returnResultViewModel.result;
             alert(this._usersHome.length)
             return this._usersHome;
         }

    }
}
</code>```

HomeUserComponent Class

```<code>export class HomeUserComponent implements OnInit{

    _usersHome: [usersHome];
    constructor( private _homeUsersService: HomeUsersService, private _router: Router) {}

   ngOnInit() {
        alert(1);
        var x =  this._homeUsersService.getAllUsers();
   }
}
</code>```

答:
The code within the .subscribe() is asynchronous. This means it is not executed right away, but sometime later.

If you have a code x that depends on the execution of the asynchronous bit, you have to place that x inside the .subscribe() part itself or use other mechanisms, like callbacks or promises.

Try as follows:

```<code>getAllUsers(): usersHome[]{

    alert(2);
     this.postaction(null, this._UrlLogin)
        .subscribe((result) => {                    // changed here

            this._returnResultViewModel = result;   // changed here

     if (this._returnResultViewModel == null)
     {
         alert("NULL");
         return null;
     }
     else {
         alert("Has DATA");
         this._usersHome = this._returnResultViewModel.result;
         alert(this._usersHome.length)
         return this._usersHome;
     }

   }                                               // added this
}
</code>```

I placed the code that depends on the asynchronous part (this._returnResultViewModel = result;) inside the function that is given to .subscribe().

Body:
I have a problem in Angular 2 that function continue work and does not waiting getting data from API.

HTTPHelper Class

import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { ReturnResultViewModel } from './ReturnResultViewModel';

export class HttpHelpers {

     _result: any = null;
     _errormsg: any = null;
     _returnResultViewModel: ReturnResultViewModel;

     constructor(private http: Http) {
         this._returnResultViewModel = new ReturnResultViewModel();
    }

    postaction(param: any, path: string) {
        let body = JSON.stringify(param);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(path, body, options)
            .map((m:Response) =>  m.json())
    }
}

HomeUserService Class

import 'rxjs/add/operator/map';
import { HttpHelpers } from '../../../HttpHelpers';
import { usersHome } from "././Home.users.ViewModel";
import { ReturnResultViewModel } from "../../../ReturnResultViewModel";

import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
Injectable()

export class HomeUsersService extends HttpHelpers {
    private _UrlLogin: string = "Accounts/getAllUsers";

    constructor( @Inject(Http) private _http: Http) {
        super(_http);
    }
    private _usersHome: usersHome[];
    getAllUsers(): usersHome[]{

        alert(2);
         this.postaction(null, this._UrlLogin)
            .subscribe(result =>
                this._returnResultViewModel = result);

         if (this._returnResultViewModel == null)
         {
             alert("NULL");
             return null;
         }
         else {
             alert("Has DATA");
             this._usersHome = this._returnResultViewModel.result;
             alert(this._usersHome.length)
             return this._usersHome;
         }

    }
}

HomeUserComponent Class

export class HomeUserComponent implements OnInit{

    _usersHome: [usersHome];
    constructor( private _homeUsersService: HomeUsersService, private _router: Router) {}

   ngOnInit() {
        alert(1);
        var x =  this._homeUsersService.getAllUsers();
   }
}

Body:
The code within the .subscribe() is asynchronous. This means it is not executed right away, but sometime later.

If you have a code x that depends on the execution of the asynchronous bit, you have to place that x inside the .subscribe() part itself or use other mechanisms, like callbacks or promises.

Try as follows:

getAllUsers(): usersHome[]{

    alert(2);
     this.postaction(null, this._UrlLogin)
        .subscribe((result) => {                    // changed here

            this._returnResultViewModel = result;   // changed here

     if (this._returnResultViewModel == null)
     {
         alert("NULL");
         return null;
     }
     else {
         alert("Has DATA");
         this._usersHome = this._returnResultViewModel.result;
         alert(this._usersHome.length)
         return this._usersHome;
     }

   }                                               // added this
}

I placed the code that depends on the asynchronous part (this._returnResultViewModel = result;) inside the function that is given to .subscribe().


来源: stackexchange

问:
can I specify the return type in the hql words
Hi:
I am using hibernate3.6,I meet some problem when do some querying.

Take this hql for exmaple:

```<code>String hql="select count(distinct ip),sum(bytes) from Entity en where ....
Query q=Session.createQuery(hql);
List<?> list=q.list();
</code>```

Now I can retrive the columen properties from the list by the following way:

```<code>    String[] properties={"count","sum"};
    for (Object obj : list) {
            Map<String, Object> m = new HashMap<String, Object>();
            Object[] props = (Object[]) obj;
            if(properties.length!=props.length) throw ....
            for (int i = 0; i < props.length; i++) {
                m.put(properties[i], props[i]);
            }
    }
</code>```

Now,my problem is that,when the hql result no set,the count is 0,but the sum is null. I want it 0 also.

Of course,I can do the converting explicitly if the know the column name and type(they are the count,sum in the above example) of the result table from db,but now I did not know.

That's to say,I can not use something like this:

```<code>if(props[i]=null) props[i]=0;
m.put(properties[i], props[i]);
</code>```

Since the type of props[i] may be string,in this case if its value is null, it should be "".

So I wonder if I can sepcify the converting type in the hql words? maybe someting like this:

select count(distinct
  ip), (long) sum(bytes) from Entity en
  where ....

select count(distinct ip),(converet
  ..sum(bytes)) from Entity en where
  ....

Is this possible?

BWT,I use mysql 5.1.

Thanks.

UPDATE:
@zinan.yumak:

Your answer seems like this;

```<code>select new Wrapper(count(distinct ip),sum(bytes)) from Entity en where...
</code>```

If so I have to create enougth extra class like Wrapper since there are so many types of select in my appliction.like:

```<code>select new AnotherWrapper(broswer,count(distinct brower)) from Entity en where...

......
</code>```

答:
I think what you need is a result transformer. Create a model class for your query.
Then add null checks or other checks into your setter methods. Something like this,

```<code>String hql="select count(distinct ip) as ip, sum(bytes) as bytes from Entity en where ....
Query q=Session.createQuery(hql).setResultTransformer(Transformers.aliasToBean(Model.class));
</code>```

And in your Model class,

```<code>class Model {
    private String ip = "";
    private BigDecimal bytes = BigDecimal.ZERO;

    public void setIp(String anIp) {
        if ( aString != null) {
            this.ip = anIp;
        }
    }

    public void setBytes(String aByte) {
        if ( aByte != null) {
            this.byte = aByte;
        }
    }
    .
    .
    .
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hi:
I am using hibernate3.6,I meet some problem when do some querying.

Take this hql for exmaple:

String hql="select count(distinct ip),sum(bytes) from Entity en where ....
Query q=Session.createQuery(hql);
List<?> list=q.list();

Now I can retrive the columen properties from the list by the following way:

    String[] properties={"count","sum"};
    for (Object obj : list) {
            Map<String, Object> m = new HashMap<String, Object>();
            Object[] props = (Object[]) obj;
            if(properties.length!=props.length) throw ....
            for (int i = 0; i < props.length; i++) {
                m.put(properties[i], props[i]);
            }
    }

Now,my problem is that,when the hql result no set,the count is 0,but the sum is null. I want it 0 also.

Of course,I can do the converting explicitly if the know the column name and type(they are the count,sum in the above example) of the result table from db,but now I did not know.

That's to say,I can not use something like this:

if(props[i]=null) props[i]=0;
m.put(properties[i], props[i]);

Since the type of props[i] may be string,in this case if its value is null, it should be "".

So I wonder if I can sepcify the converting type in the hql words? maybe someting like this:

select count(distinct
  ip), (long) sum(bytes) from Entity en
  where ....

select count(distinct ip),(converet
  ..sum(bytes)) from Entity en where
  ....

Is this possible?

BWT,I use mysql 5.1.

Thanks.

UPDATE:
@zinan.yumak:

Your answer seems like this;

select new Wrapper(count(distinct ip),sum(bytes)) from Entity en where...

If so I have to create enougth extra class like Wrapper since there are so many types of select in my appliction.like:

select new AnotherWrapper(broswer,count(distinct brower)) from Entity en where...

......

Body:
I think what you need is a result transformer. Create a model class for your query.
Then add null checks or other checks into your setter methods. Something like this,

String hql="select count(distinct ip) as ip, sum(bytes) as bytes from Entity en where ....
Query q=Session.createQuery(hql).setResultTransformer(Transformers.aliasToBean(Model.class));

And in your Model class,

class Model {
    private String ip = "";
    private BigDecimal bytes = BigDecimal.ZERO;

    public void setIp(String anIp) {
        if ( aString != null) {
            this.ip = anIp;
        }
    }

    public void setBytes(String aByte) {
        if ( aByte != null) {
            this.byte = aByte;
        }
    }
    .
    .
    .
}


问:
How can I share a CSS subclass without repeating myself
I have two different CSS classes which should both use an identical subclass, like this:

```<code>.front {
  display:flex;
  justify-content: center;
  align-items: center;

  .instructions {
    position:absolute;
    etc.
  }
 }

.back {
  padding: 5%;
  etc.;

  .instructions {
    position:absolute;
    etc.
  }
}
</code>```

Is there a way to do this in a DRY way? One solution would be to make .instructions a top level selector on its own, but I'd like to keep the notion of hierarchy here.  Thanks!

答:
What about this?</p>

```<code>    .front {
      display:flex;
      justify-content: center;
      align-items: center;
     }

    .back {
      padding: 5%;
      etc.;
    }

    .back, .front {
      .instructions {
        position:absolute;
        etc.
      }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two different CSS classes which should both use an identical subclass, like this:

.front {
  display:flex;
  justify-content: center;
  align-items: center;

  .instructions {
    position:absolute;
    etc.
  }
 }

.back {
  padding: 5%;
  etc.;

  .instructions {
    position:absolute;
    etc.
  }
}

Is there a way to do this in a DRY way? One solution would be to make .instructions a top level selector on its own, but I'd like to keep the notion of hierarchy here.  Thanks!

Body:
What about this?

    .front {
      display:flex;
      justify-content: center;
      align-items: center;
     }

    .back {
      padding: 5%;
      etc.;
    }

    .back, .front {
      .instructions {
        position:absolute;
        etc.
      }
    }


答:
Have you tried to use mixin?

A mixin lets you make groups of CSS declarations that you want to reuse throughout your site.
  http://sass-lang.com/guide#topic-6

define a mixin

```<code>@mixin instructions {
    position:absolute;
    etc.
}
</code>```

and use it

```<code>.front {
  display:flex;
  justify-content: center;
  align-items: center;

  .instructions {
    @include instructions;
  }
 }

.back {
  padding: 5%;
  etc.;

  .instructions {
    @include instructions;
  }
}
</code>```

also you can move .instructions into mixin:

```<code>@mixin instructions {
    .instructions {
        position:absolute;
        etc.
    }
}
.front {
  display:flex;
  justify-content: center;
  align-items: center;
  @include instructions;
 }

.back {
  padding: 5%;
  etc.;
  @include instructions;
}
</code>```

Title: How can I share a CSS subclass without repeating myself

Body:
Have you tried to use mixin?

A mixin lets you make groups of CSS declarations that you want to reuse throughout your site.
  http://sass-lang.com/guide#topic-6

define a mixin

@mixin instructions {
    position:absolute;
    etc.
}

and use it

.front {
  display:flex;
  justify-content: center;
  align-items: center;

  .instructions {
    @include instructions;
  }
 }

.back {
  padding: 5%;
  etc.;

  .instructions {
    @include instructions;
  }
}

also you can move .instructions into mixin:

@mixin instructions {
    .instructions {
        position:absolute;
        etc.
    }
}
.front {
  display:flex;
  justify-content: center;
  align-items: center;
  @include instructions;
 }

.back {
  padding: 5%;
  etc.;
  @include instructions;
}


问:
Understanding when random_shuffle_queue runs out of elements and close it
I have 1000 images with size 32x32x3 stored in a dummy.tfrecord file. I want to iterate over the datasets twice (2 epochs), so I specify tf.train.string_input_producer([dummy.tfrecord], num_epochs=2). For batch size 100 I would expect tf.train.shuffle_batch to run 2 * 10 = 20 iterations, since it takes 10 batches of 100 to exhaust 1000 images.

I followed this answer and it did produce 20 iterations as expected. However, at the end, I received the error:

```<code>RandomShuffleQueue '_1_shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)
</code>```

Which makes sense, since there 0 image left in the queue.

How do I close the queues and exit cleanly? That is, there shouldn't be an error.

Here's the full script:

```<code>import numpy as np
import tensorflow as tf

NUM_IMGS = 1000
tfrecord_file = 'dummy.tfrecord'

def read_from_tfrecord(filenames):
    tfrecord_file_queue = tf.train.string_input_producer(filenames,
            num_epochs=2)
    reader = tf.TFRecordReader()
    _, tfrecord_serialized = reader.read(tfrecord_file_queue)

    tfrecord_features = tf.parse_single_example(tfrecord_serialized,
                        features={
                            'label': tf.FixedLenFeature([], tf.string),
                            'image': tf.FixedLenFeature([], tf.string),
                        }, name='features')

    image = tf.decode_raw(tfrecord_features['image'], tf.uint8)
    image = tf.reshape(image, shape=(32, 32, 3))

    label = tf.cast(tfrecord_features['label'], tf.string)

    #provide batches
    images, labels = tf.train.shuffle_batch([image, label],
            batch_size=100,
            num_threads=4,
            capacity=50,
            min_after_dequeue=1)

    return images, labels

imgs, lbls = read_from_tfrecord([tfrecord_file])
init_op = tf.group(tf.global_variables_initializer(),
        tf.local_variables_initializer())

with tf.Session() as sess:
    sess.run(init_op)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    while not coord.should_stop():
        labels, images = sess.run([lbls, imgs])
        print(images.shape) #PRINTED 20 TIMES BUT FAILED AT THE 21ST
    coord.request_stop()
    coord.join(threads)
</code>```

Here's the script that generates the dummy.tfrecord file, if anyone wants to reproduce:

```<code>def generate_image_binary():
    images = np.random.randint(0,255, size=(NUM_POINTS, 32, 32, 3),
            dtype=np.uint8)
    labels = np.random.randint(0,2, size=(NUM_POINTS, 1))
    return labels, images

def write_to_tfrecord(labels, images, tfrecord_file):
    writer = tf.python_io.TFRecordWriter(tfrecord_file)

    for i in range(NUM_POINTS):
        example = tf.train.Example(features=tf.train.Features(feature={
                    'label':
                    tf.train.Feature(bytes_list=tf.train.BytesList(value=[labels[i].tobytes()])),
                    'image':
                    tf.train.Feature(bytes_list=tf.train.BytesList(value=[images[i].tobytes()]))
                    }))
        writer.write(example.SerializeToString())
    writer.close()

tfrecord_file = 'dummy.tfrecord'
labels, images= generate_image_binary()
write_to_tfrecord(labels, images, tfrecord_file)
</code>```

答:
The Coordinator can catch and handle exceptions like the tf.errors.OutOfRangeError, which is used to report that a queue was closed.
You can make your code change to handle the above exception :

```<code>with tf.Session() as sess:
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
try:
    while not coord.should_stop():
        labels, images = sess.run([lbls, imgs])
        print(images.shape) #PRINTED 20 TIMES BUT FAILED AT THE 21ST
except Exception, e:
    # When done, ask the threads to stop.
    coord.request_stop(e)

finally:
    coord.request_stop()
   # Wait for threads to finish.
coord.join(threads)
</code>```

Body:
I have 1000 images with size 32x32x3 stored in a dummy.tfrecord file. I want to iterate over the datasets twice (2 epochs), so I specify tf.train.string_input_producer([dummy.tfrecord], num_epochs=2). For batch size 100 I would expect tf.train.shuffle_batch to run 2 * 10 = 20 iterations, since it takes 10 batches of 100 to exhaust 1000 images.

I followed this answer and it did produce 20 iterations as expected. However, at the end, I received the error:

RandomShuffleQueue '_1_shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)

Which makes sense, since there 0 image left in the queue.

How do I close the queues and exit cleanly? That is, there shouldn't be an error.

Here's the full script:

import numpy as np
import tensorflow as tf

NUM_IMGS = 1000
tfrecord_file = 'dummy.tfrecord'

def read_from_tfrecord(filenames):
    tfrecord_file_queue = tf.train.string_input_producer(filenames,
            num_epochs=2)
    reader = tf.TFRecordReader()
    _, tfrecord_serialized = reader.read(tfrecord_file_queue)

    tfrecord_features = tf.parse_single_example(tfrecord_serialized,
                        features={
                            'label': tf.FixedLenFeature([], tf.string),
                            'image': tf.FixedLenFeature([], tf.string),
                        }, name='features')

    image = tf.decode_raw(tfrecord_features['image'], tf.uint8)
    image = tf.reshape(image, shape=(32, 32, 3))

    label = tf.cast(tfrecord_features['label'], tf.string)

    #provide batches
    images, labels = tf.train.shuffle_batch([image, label],
            batch_size=100,
            num_threads=4,
            capacity=50,
            min_after_dequeue=1)

    return images, labels

imgs, lbls = read_from_tfrecord([tfrecord_file])
init_op = tf.group(tf.global_variables_initializer(),
        tf.local_variables_initializer())

with tf.Session() as sess:
    sess.run(init_op)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    while not coord.should_stop():
        labels, images = sess.run([lbls, imgs])
        print(images.shape) #PRINTED 20 TIMES BUT FAILED AT THE 21ST
    coord.request_stop()
    coord.join(threads)

Here's the script that generates the dummy.tfrecord file, if anyone wants to reproduce:

def generate_image_binary():
    images = np.random.randint(0,255, size=(NUM_POINTS, 32, 32, 3),
            dtype=np.uint8)
    labels = np.random.randint(0,2, size=(NUM_POINTS, 1))
    return labels, images

def write_to_tfrecord(labels, images, tfrecord_file):
    writer = tf.python_io.TFRecordWriter(tfrecord_file)

    for i in range(NUM_POINTS):
        example = tf.train.Example(features=tf.train.Features(feature={
                    'label':
                    tf.train.Feature(bytes_list=tf.train.BytesList(value=[labels[i].tobytes()])),
                    'image':
                    tf.train.Feature(bytes_list=tf.train.BytesList(value=[images[i].tobytes()]))
                    }))
        writer.write(example.SerializeToString())
    writer.close()

tfrecord_file = 'dummy.tfrecord'
labels, images= generate_image_binary()
write_to_tfrecord(labels, images, tfrecord_file)

Body:
The Coordinator can catch and handle exceptions like the tf.errors.OutOfRangeError, which is used to report that a queue was closed.
You can make your code change to handle the above exception :

with tf.Session() as sess:
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
try:
    while not coord.should_stop():
        labels, images = sess.run([lbls, imgs])
        print(images.shape) #PRINTED 20 TIMES BUT FAILED AT THE 21ST
except Exception, e:
    # When done, ask the threads to stop.
    coord.request_stop(e)

finally:
    coord.request_stop()
   # Wait for threads to finish.
coord.join(threads)


问:
Finding Maximum Value of Array
I'm trying to loop through my array to find the maximum value and print the value. However, nothing is being printed to the console. Can you please take a look at my code below to see what I've done incorrectly.

```<code>for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
  array[c] = in.nextInt();

maxInt = array[0];
minInt = array[0];

for (c = 0; c < n; c++) {
    if (array[c] > maxInt) {
        maxInt = array[c];
    }
    else {
        break;
    }
}
System.out.println("Max int is: " + maxInt);
}
</code>```

EDIT:

Full class:

```<code>import java.util.Scanner;

public class MaxMinOfArray {
public static void main(String[] args) {
int c, n, search, array[];
int maxInt, minInt;

Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt(); //asks user to specify array size
array = new int[n]; //creates array of specified array size

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
array[c] = in.nextInt();

maxInt = array[0];
minInt = array[0];

for (c = 1; c < n; c++) {
if (array[c] > maxInt) {
    maxInt = array[c];
}
}
System.out.println("Max int is: " + maxInt);
}
}
</code>```

答:
As others indicated, you don't want to do

```<code>else {
    break;
}
</code>```

That means that it'll stop looping as soon as it finds a number that isn't larger than the current max. Since you're starting with the first item in the list, which trivially isn't larger than itself, you break immediately.

Even if you changed it to start at c = 1, the only case where this code could possibly work as written is if the user entered numbers in ascending order. (In that case, doing a linear search like this would be pointless anyway since you could literally just find the last item in the array and know that it'll be the largest item).

Also, you should check to see if array[c] is smaller than the current minimum value in your for loop; there's no reason at all to do this in a separate loop.

Remember, if you're doing a linear search for the max value of an unsorted array, you always must go through the entire array to make sure you didn't miss a greater value. For example, if you only search half of the array, how do you know that the half that you didn't search doesn't contain the max value?

Title: Finding Maximum Value of Array

Body:
I'm trying to loop through my array to find the maximum value and print the value. However, nothing is being printed to the console. Can you please take a look at my code below to see what I've done incorrectly.

for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
  array[c] = in.nextInt();

maxInt = array[0];
minInt = array[0];

for (c = 0; c < n; c++) {
    if (array[c] > maxInt) {
        maxInt = array[c];
    }
    else {
        break;
    }
}
System.out.println("Max int is: " + maxInt);
}

EDIT:

Full class:

import java.util.Scanner;

public class MaxMinOfArray {
public static void main(String[] args) {
int c, n, search, array[];
int maxInt, minInt;

Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt(); //asks user to specify array size
array = new int[n]; //creates array of specified array size

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++) //loops through array until each index has had a value input by the user
array[c] = in.nextInt();

maxInt = array[0];
minInt = array[0];

for (c = 1; c < n; c++) {
if (array[c] > maxInt) {
    maxInt = array[c];
}
}
System.out.println("Max int is: " + maxInt);
}
}

Body:
As others indicated, you don't want to do

else {
    break;
}

That means that it'll stop looping as soon as it finds a number that isn't larger than the current max. Since you're starting with the first item in the list, which trivially isn't larger than itself, you break immediately.

Even if you changed it to start at c = 1, the only case where this code could possibly work as written is if the user entered numbers in ascending order. (In that case, doing a linear search like this would be pointless anyway since you could literally just find the last item in the array and know that it'll be the largest item).

Also, you should check to see if array[c] is smaller than the current minimum value in your for loop; there's no reason at all to do this in a separate loop.

Remember, if you're doing a linear search for the max value of an unsorted array, you always must go through the entire array to make sure you didn't miss a greater value. For example, if you only search half of the array, how do you know that the half that you didn't search doesn't contain the max value?


答:
Remove your this part of code.

else {
    break;
}
```

Because when c==0 in that time array[c] == maxInt. So it goes to else part and break your for loop.

Title: Finding Maximum Value of Array

Body:
Remove your this part of code.

else {
    break;
}

Because when c==0 in that time array[c] == maxInt. So it goes to else part and break your for loop.


问:
SWI-Prolog parsing DCG predicate doesn't work
I have a predicate with the goal of parsing a grammar.
The productions of the grammar are:

S-> B
 B->bB
 B->b

The predicate is intended to take in a list and determine whether or not the list belongs to the grammar. My code is as follows:

```<code>s(List,[]):- b(List,[]).
b(List,[]):-'C'(List,b,X), b(X,[]).
b([b|List],List).
</code>```

The predicate seems to be able to determine that [b] is a solution, however, it is unable to detect that [b,b,b] is also a solution.

For instance,

```<code>?-s([b],[]).
 true.
?-s([b,b,b],[]).
 false.
</code>```

I think the second line of my code isn't doing what I want it to, but I'm not sure how to fix it.

答:
If you are willing to understand the basics of Prolog and DCGs, see this solution:</p>

```<code>s(List):- b(List,[]).
b([b|List],Rest):- b(List,Rest).
b([b],[]).
</code>```

Body:
I have a predicate with the goal of parsing a grammar.
The productions of the grammar are:

S-> B
 B->bB
 B->b

The predicate is intended to take in a list and determine whether or not the list belongs to the grammar. My code is as follows:

s(List,[]):- b(List,[]).
b(List,[]):-'C'(List,b,X), b(X,[]).
b([b|List],List).

The predicate seems to be able to determine that [b] is a solution, however, it is unable to detect that [b,b,b] is also a solution.

For instance,

?-s([b],[]).
 true.
?-s([b,b,b],[]).
 false.

I think the second line of my code isn't doing what I want it to, but I'm not sure how to fix it.

Body:
If you are willing to understand the basics of Prolog and DCGs, see this solution:

s(List):- b(List,[]).
b([b|List],Rest):- b(List,Rest).
b([b],[]).


问:
Queries on Tree Path with Modifications
Question:

You are given a Tree with n Nodes(can be upto 10^5) and n-1 bidirectional edges. And lets say each node contains two values:

It's index(Just a unique number for node), lets say it will be from 1 to n.

And It's value Vi, which can vary from 1 to 10^8

Now there will be multiple same type of queries(number of queries can be upto 10^5) on this same tree, as follows:

You are given node1, node2 and a value P(can vary from 1 to 10^8).

And for every this type of query, you just have to find number of nodes in path from node1 to node2 whose value is less than P.

NOTE: There will be unique path between all the nodes and no two edges belong to same pair of nodes.

Required Time Complexity O(nLog(n)) or can be in other terms but should be solvable in 1 Sec with given constraints.

What I have Tried:

(A). I could solve it easily if value of P would be fixed, using LCA approach in O(nLog(n)) by storing following info at each node:

Number of nodes whose value is less than P, from root to given node.

But here P is varying way too much so this will not help.

(B). Other approach I was thinking is, using simple DFS. But that will also take O(nq), where q is number of queries. Again as n and q both are varying between 1 to 10^5 so this will not help too in given time constraint.

I could not think anything else. Any help would be appreciated. :)

Source:

I read this problem somewhere on SPOJ I guess. But cannot find it now. Tried searching it on Web but could not find solution for it anywhere (Codeforces, CodeChef, SPOJ, StackOverflow).

答:
Let ans(v, P) be the answer on a vertical path from the root to v and the given value of P.

How can we compute it? There's a simple offline solution: we can store all queries for the given node in a vector associated with it, run the depth-first search keep all values on the current path from the path in data structure that can do the following:

add a value

delete a value

count the number elements smaller than X

Any balanced binary-search tree would do. You can make it even simpler: if you know all the queries beforehand, you can compress the numbers so that they're in the [0..n - 1] range and use a binary index tree.

Back to the original problem: the answer to a (u, v, P) query is clearly ans(v, P) + ans(u, P) - 2 * ans(LCA(u, v), P).

That's it. The time complexity is O((N + Q) log N).

Title: Queries on Tree Path with Modifications


问:
How is the `__getattribute__` method involved in the lookup procedures?
Python in a Nutshell describes:

the lookup procedure when getting an attribute from a class, e.g. cls.name (see the first part in Why are the lookup procedures for getting an attribute from a class and from an instance different?)

the lookup procedure when getting an attribute from an instance, e.g. obj.name

How is the __getattribute__ method involved in the above lookup procedures?

Is the __getattribute__ method called somewhere in the lookup procedures?

Or, are the lookup procedures started by calling __getattribute__, which then does all the work in the two links?

Thanks.

答:
TLDR: Attribute lookup starts with calling __getattribute__ and it does all the work mentioned in the links. Based on the type of the object either object.__getattribute__ or type.__getattribute__ is called.

Any attribute lookup results in LOAD_ATTR bytecode internally.

```<code>>>> import dis
>>> dis.dis(lambda: foo.x)
  1           0 LOAD_GLOBAL              0 (foo)
              2 LOAD_ATTR                1 (x)
              4 RETURN_VALUE
</code>```

LOAD_ATTR then calls PyObject_GetAttr.

PyObject_GetAttr now looks for either tp_getattro or tp_getattr(deprecated) slot on the object's type.

```<code>PyObject *

PyObject_GetAttr(PyObject *v, PyObject *name)
{
    PyTypeObject *tp = Py_TYPE(v);
    ...
    if (tp->tp_getattro != NULL)
        return (*tp->tp_getattro)(v, name);
    if (tp->tp_getattr != NULL) {
        const char *name_str = PyUnicode_AsUTF8(name);
        if (name_str == NULL)
            return NULL;
        return (*tp->tp_getattr)(v, (char *)name_str);
    }
    ...
}
</code>```

Now if an object has its own implementation of __getattribute__ then that is used else it falls back to  either object.__getattribute__ or type.__getattribute__ based on the type. tp_getattro slot in case of object points to PyObject_GenericGetAttr and for type it points to type_getattro.

PyObject_GenericGetAttr and type_getattro basically do all the work of checking for descriptors, dictionary, slots etc(based on the type) and try to return a value. If they fail to find it even after everything then AttributeError is raised and if the object's type defined __getattr__ then it will be invoked.

Body:
TLDR: Attribute lookup starts with calling __getattribute__ and it does all the work mentioned in the links. Based on the type of the object either object.__getattribute__ or type.__getattribute__ is called.

Any attribute lookup results in LOAD_ATTR bytecode internally.

>>> import dis
>>> dis.dis(lambda: foo.x)
  1           0 LOAD_GLOBAL              0 (foo)
              2 LOAD_ATTR                1 (x)
              4 RETURN_VALUE

LOAD_ATTR then calls PyObject_GetAttr.

PyObject_GetAttr now looks for either tp_getattro or tp_getattr(deprecated) slot on the object's type.

PyObject *

PyObject_GetAttr(PyObject *v, PyObject *name)
{
    PyTypeObject *tp = Py_TYPE(v);
    ...
    if (tp->tp_getattro != NULL)
        return (*tp->tp_getattro)(v, name);
    if (tp->tp_getattr != NULL) {
        const char *name_str = PyUnicode_AsUTF8(name);
        if (name_str == NULL)
            return NULL;
        return (*tp->tp_getattr)(v, (char *)name_str);
    }
    ...
}

Now if an object has its own implementation of __getattribute__ then that is used else it falls back to  either object.__getattribute__ or type.__getattribute__ based on the type. tp_getattro slot in case of object points to PyObject_GenericGetAttr and for type it points to type_getattro.

PyObject_GenericGetAttr and type_getattro basically do all the work of checking for descriptors, dictionary, slots etc(based on the type) and try to return a value. If they fail to find it even after everything then AttributeError is raised and if the object's type defined __getattr__ then it will be invoked.


问:
How to programatically create a folder at a Sharepoint site
this question is related with this one. How can I create a folder to put the files I upload inside them without using the SharePoint API (I'm executing the application on another host)?

Thanks in advance.

答:
```<code>     SPSite _MySite = new SPSite("http://adfsaccount:2222/");
                SPWeb _MyWeb = _MySite.OpenWeb();

                SPDocumentLibrary _MyDocLibrary = (SPDocumentLibrary) _MyWeb.Lists["My Documents"];
                SPFolderCollection _MyFolders = _MyWeb.Folders;
                _MyFolders.Add("http://adfsaccount:2222/My%20Documents/" + txtUpload.Text + "/");
                _MyDocLibrary.Update();
_MyWeb.Dispose();
_MySite .Dispose();
</code>```


问:
SQL - How to find which page is the first for users?
I have a table like this:

```<code>+----------+-------------------------------------+----------------------------------+
| user_id  | time                                | url                              |
+----------+-------------------------------------+----------------------------------+
| 1        | 02.04.2017 8:56                     | www.landingpage.com/              |
| 1        | 02.04.2017 8:57                     | www.landingpage.com/about-us     |
| 1        | 02.04.2017 8:58                     | www.landingpage.com/faq          |
| 2        | 02.04.2017 6:34                     | www.landingpage.com/about-us     |
| 2        | 02.04.2017 6:35                     | www.landingpage.com/how-to-order |
| 3        | 03.04.2017 9:11                     | www.landingpage.com/             |
| 3        | 03.04.2017 9:12                     | www.landingpage.com/contact      |
| 3        | 03.04.2017 9:13                     | www.landingpage.com/about-us     |
| 3        | 03.04.2017 9:14                     | www.landingpage.com/our-legacy   |
| 3        | 03.04.2017 9:15                     | www.landingpage.com/             |
+----------+-------------------------------------+----------------------------------+
</code>```

I want to figure out which page is the first for most users (first page a user see when he comes to the site) and count the number of times it is viewed as the first page.

Is there a way to write a query to do this? I guess I need to use

```<code>MIN(time)
</code>```

in conjunction with grouping but I don't know how.

So regarding the sample I provided it should be like:

```<code>url                                       url_count
---------------------------------------------------
www.landingpage.com/                      2
www.landingpage.com/about-us              1
</code>```

Thanks!

答:
```<code>SELECT *
FROM my_table
WHERE time IN
(
  SELECT min(time)
  FROM my_table
  GROUP BY url
);
</code>```

Body:
I have a table like this:

+----------+-------------------------------------+----------------------------------+
| user_id  | time                                | url                              |
+----------+-------------------------------------+----------------------------------+
| 1        | 02.04.2017 8:56                     | www.landingpage.com/              |
| 1        | 02.04.2017 8:57                     | www.landingpage.com/about-us     |
| 1        | 02.04.2017 8:58                     | www.landingpage.com/faq          |
| 2        | 02.04.2017 6:34                     | www.landingpage.com/about-us     |
| 2        | 02.04.2017 6:35                     | www.landingpage.com/how-to-order |
| 3        | 03.04.2017 9:11                     | www.landingpage.com/             |
| 3        | 03.04.2017 9:12                     | www.landingpage.com/contact      |
| 3        | 03.04.2017 9:13                     | www.landingpage.com/about-us     |
| 3        | 03.04.2017 9:14                     | www.landingpage.com/our-legacy   |
| 3        | 03.04.2017 9:15                     | www.landingpage.com/             |
+----------+-------------------------------------+----------------------------------+

I want to figure out which page is the first for most users (first page a user see when he comes to the site) and count the number of times it is viewed as the first page.

Is there a way to write a query to do this? I guess I need to use

MIN(time)

in conjunction with grouping but I don't know how.

So regarding the sample I provided it should be like:

url                                       url_count
---------------------------------------------------
www.landingpage.com/                      2
www.landingpage.com/about-us              1

Thanks!


答:
instead of a @mixin, which looks too complex for this job, you can use @extend

This is one of the most useful features of Sass. Using @extend lets
  you share a set of CSS properties from one selector to another. It
  helps keep your Sass very DRY.

The emphasis is mine about the DRY, given that's what you are asking about

something like this:

.instructions {
    position:absolute;
 }

.front {
  display:flex;
  justify-content: center;
  align-items: center;
  @extend .instructions

 }

.back {
  padding: 5%;
  @extend .instructions
}
```

<p>which compiles into this:</p>

<pre class="lang-css prettyprint-override"><code>.instructions, .front, .back {
  position: absolute;
}

.front {
  display: flex;
  justify-content: center;
  align-items: center;
}

.back {
  padding: 5%;
}
</code>```

you can see a demo here

Body:
instead of a @mixin, which looks too complex for this job, you can use @extend

This is one of the most useful features of Sass. Using @extend lets
  you share a set of CSS properties from one selector to another. It
  helps keep your Sass very DRY.

The emphasis is mine about the DRY, given that's what you are asking about

something like this:

.instructions {
    position:absolute;
 }

.front {
  display:flex;
  justify-content: center;
  align-items: center;
  @extend .instructions

 }

.back {
  padding: 5%;
  @extend .instructions
}

which compiles into this:

.instructions, .front, .back {
  position: absolute;
}

.front {
  display: flex;
  justify-content: center;
  align-items: center;
}

.back {
  padding: 5%;
}

you can see a demo here


问:
Add a badge on icon in Ionic 3
I need to add a number badge to the cart icon in ionic 3 so that the user gets the update of number of elements in the cart without actually visiting the page i tried to use the code of button and badge together but it was of no use

```<code>  <button ion-button icon-only (click)="cart()">
      <ion-icon name="cart"> <ion-badge item-end>260k</ion-badge></ion-icon>
  </button>
</code>```

Above code displays the badge next to the cart icon but not over it, so is there a way to add badge to the icon itself like we have in notification alert badges?

答:
I think you will have to use some CSS and absolute positioning to place the badge above the left corner of the cart icon.

Something like this:

```<code><button id="cart-btn" ion-button icon-only (click)="cart()">
      <ion-icon name="cart"></ion-icon>
      <ion-badge id="cart-badge">260k</ion-badge>
</button>
</code>```

CSS

```<code>#cart-btn {
   position: relative;
}

#cart-badge {
   position: absolute;
   top: 0px;
   right: 0px;
}
</code>```

Title: Add a badge on icon in Ionic 3

Body:
I need to add a number badge to the cart icon in ionic 3 so that the user gets the update of number of elements in the cart without actually visiting the page i tried to use the code of button and badge together but it was of no use

  <button ion-button icon-only (click)="cart()">
      <ion-icon name="cart"> <ion-badge item-end>260k</ion-badge></ion-icon>
  </button>

Above code displays the badge next to the cart icon but not over it, so is there a way to add badge to the icon itself like we have in notification alert badges?

Body:
I think you will have to use some CSS and absolute positioning to place the badge above the left corner of the cart icon.

Something like this:

<button id="cart-btn" ion-button icon-only (click)="cart()">
      <ion-icon name="cart"></ion-icon>
      <ion-badge id="cart-badge">260k</ion-badge>
</button>

CSS

#cart-btn {
   position: relative;
}

#cart-badge {
   position: absolute;
   top: 0px;
   right: 0px;
}


问:
Installing HAXM on Windows 10 for Android Studio
Android Studio told me to install HAXM, so I downloaded it and when I went to install, it said This computer does not support Intel Virtualization Technology. After some search, I found that if you uncheck Hyper-V in control panel, all will be well. The problem I'm facing is, it isn't even checked. Is there any other way to fix this issue or does my computer just really not support VT-X?

答:
Make sure Virtualization is enabled in BIOS (advanced Firmware for
  windows 10)

and install manually from
https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager/

after running installation batch file, silent_install.bat of downloaded zip file.

tns run android  -->Should open up the simulator!


问:
Hooking up React Native to back-end (with Express)
I made a UI with React Native, as well as a Cheerio.js scraper (with Cron Job to activate it once every day) I'll use to grab certain data from the web, so it can render in the UI. However, I have no idea how to link the two of them.

I am pretty sure I can do this with Express (which I am most comfortable with for the back-end), but can someone tell me exactly what I need to do to connect my front-end to a back-end?

Just in case, I am a junior dev (better on the front-end than the back-end) so please keep your answers simple. Even if your answers are more conceptual, rather than code-based, I'd really appreciate it.

答:
API

I'm quite happy with GraphQL as an alternative to REST. However, there are many ways to connect through an api. Your client needs the link to where your server is running, and your server needs to enable that.

Tutorials

I think I couldn't explain it better than this tutorial (with example on Github): https://medium.com/react-native-training/react-native-with-apollo-server-and-client-part-1-efb7d15d2361

https://medium.com/react-native-training/react-native-with-apollo-part-2-apollo-client-8b4ad4915cf5

And following Stephen Grider's tutorial on Udemy for deeper understanding of GraphQL. He is using React and not React Native in his tutorial but the syntax remains very close.
https://www.udemy.com/graphql-with-react-course/learn/v4/overview

Important notice - The first tutorials use "apollo-server" while udemy's tutorial uses graphql. apollo-server changes quite often and graphql may be clearer.

Example

Here's how my bridge between the two looks like. The biggest difficulty was dealing with Cors for the front-end version of the app (Next.js) and finding out that the server can be accessed on http://10.0.3.2:8080/graphql (may vary) instead of localhost:8080.

My index.android.js (client side):

```<code>import React from 'react'
import { AppRegistry } from 'react-native'
import App from './app'

import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { ApolloProvider } from 'react-apollo'

const Client = () => {
  const networkInterface = createNetworkInterface({
   uri: 'http://10.0.3.2:8080/graphql'
  })
  const client = new ApolloClient({
    networkInterface
  });
  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>)
}

AppRegistry.registerComponent('apolloclient', () => Client);
</code>```

My app.js server side

```<code>const express = require('express');
// const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const chalk = require('chalk');

// New imports
// NEVER FORGET to require the models,
// in which schemas are registered for a certain model
// forgetting it would throw "Schema hasn't been registered for model..."
const models = require('./models');
const expressGraphQL = require('express-graphql');
const schema = require('./schema/schema');

const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// My mongoLab URI
const MONGO_URI = 'mongodb://xxx:xxx@xxx.mlab.com:xxx/xxx';

// mongoose's built in promise library is deprecated, replace it with ES2015 Promise
mongoose.Promise = global.Promise;

// Connect to the mongoDB instance and log a message
// on success or failure
mongoose.connect(MONGO_URI);
mongoose.connection.once('open', () => console.log(`${chalk.blue(`  Connected to MongoLab instance `)}`));
mongoose.connection.on('error', error => console.log(`${chalk.yellow(`⚠  Error connecting to MongoLab: ` + error + ` ⚠`)}`));

app.use(cors());

// We pass the schema as an option to our expressGraphQL middleware
app.use('/graphql', expressGraphQL({
  schema,
  graphiql: true
}))

module.exports = app;
</code>```

my index.js (server side):

```<code>const app = require('./app');
const chalk = require('chalk');

const PORT = 8080;

app.listen(PORT, () => {
  console.log(`${chalk.green(`✔  Server started on http://localhost:${PORT} ✔`)}`);
});
</code>```

Body:
API

I'm quite happy with GraphQL as an alternative to REST. However, there are many ways to connect through an api. Your client needs the link to where your server is running, and your server needs to enable that.

Tutorials

I think I couldn't explain it better than this tutorial (with example on Github): https://medium.com/react-native-training/react-native-with-apollo-server-and-client-part-1-efb7d15d2361

https://medium.com/react-native-training/react-native-with-apollo-part-2-apollo-client-8b4ad4915cf5

And following Stephen Grider's tutorial on Udemy for deeper understanding of GraphQL. He is using React and not React Native in his tutorial but the syntax remains very close.
https://www.udemy.com/graphql-with-react-course/learn/v4/overview

Important notice - The first tutorials use "apollo-server" while udemy's tutorial uses graphql. apollo-server changes quite often and graphql may be clearer.

Example

Here's how my bridge between the two looks like. The biggest difficulty was dealing with Cors for the front-end version of the app (Next.js) and finding out that the server can be accessed on http://10.0.3.2:8080/graphql (may vary) instead of localhost:8080.

My index.android.js (client side):

import React from 'react'
import { AppRegistry } from 'react-native'
import App from './app'

import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { ApolloProvider } from 'react-apollo'

const Client = () => {
  const networkInterface = createNetworkInterface({
   uri: 'http://10.0.3.2:8080/graphql'
  })
  const client = new ApolloClient({
    networkInterface
  });
  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>)
}

AppRegistry.registerComponent('apolloclient', () => Client);

My app.js server side

const express = require('express');
// const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const chalk = require('chalk');

// New imports
// NEVER FORGET to require the models,
// in which schemas are registered for a certain model
// forgetting it would throw "Schema hasn't been registered for model..."
const models = require('./models');
const expressGraphQL = require('express-graphql');
const schema = require('./schema/schema');

const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// My mongoLab URI
const MONGO_URI = 'mongodb://xxx:xxx@xxx.mlab.com:xxx/xxx';

// mongoose's built in promise library is deprecated, replace it with ES2015 Promise
mongoose.Promise = global.Promise;

// Connect to the mongoDB instance and log a message
// on success or failure
mongoose.connect(MONGO_URI);
mongoose.connection.once('open', () => console.log(`${chalk.blue(`  Connected to MongoLab instance `)}`));
mongoose.connection.on('error', error => console.log(`${chalk.yellow(`⚠  Error connecting to MongoLab: ` + error + ` ⚠`)}`));

app.use(cors());

// We pass the schema as an option to our expressGraphQL middleware
app.use('/graphql', expressGraphQL({
  schema,
  graphiql: true
}))

module.exports = app;

my index.js (server side):

const app = require('./app');
const chalk = require('chalk');

const PORT = 8080;

app.listen(PORT, () => {
  console.log(`${chalk.green(`✔  Server started on http://localhost:${PORT} ✔`)}`);
});


答:
You can query as below:

```<code>Select top (1) with ties *
    from yourtable
order by row_number() over(partition by user_id order by [time])
</code>```

You can use outer query to get the same as below:

```<code>Select * from (
    Select *, RowN = row_number() over(partition by user_id order by [time]) from yourtable) a
Where a.RowN = 1
</code>```

Title: SQL - How to find which page is the first for users?

Body:
You can query as below:

Select top (1) with ties *
    from yourtable
order by row_number() over(partition by user_id order by [time])

You can use outer query to get the same as below:

Select * from (
    Select *, RowN = row_number() over(partition by user_id order by [time]) from yourtable) a
Where a.RowN = 1


问:
How to initiate a function using data(){} but not mounted(){} while using vue-resource
This works, but I need to use mounted(){} to initiate the function which I think can be avoided but not sure how.

```<code><script>
  export default {
    data () {
      return {
        domains: [],
      }
    },

    methods: {
      fetchDomains() {
        let _this = this;

        api._get({url: 'api/domains'})
          .then(function (response) {
            _this.domains = response.data;
          })
      }
    },

    mounted() {
      this.fetchDomains()
    }
  }
</script>
</code>```

This code doesn't work, but I like to do something like this. Initiating the function in data(){} itself.

```<code><script>
  export default {
    data () {
      return {
        domains: this.fetchDomains(),
      }
    },

    methods: {
      fetchDomains() {
        let data = [];

        api._get({url: 'api/domains'})
          .then(function (response) {
            data = response.data;
          })

        return data
      }
    }
  }
</script>
</code>```

Thanks in advance.

答:
I might be deviating slightly from the question (since it explicitly mentions the data property), but I think this might be helpful. Personally, if I want to provide some data with more complex logic I use the computed property. This is great in my opinion and you can read more about it in the docs. The problem in this case is that it doesn't work entirely as expected with asynchronous operations...

However, there is a lovely little module called vue-async-computed which can be found here. It solves this specific problem by providing an asyncComputed property and keeps the code really clean!

Body:
This works, but I need to use mounted(){} to initiate the function which I think can be avoided but not sure how.

This code doesn't work, but I like to do something like this. Initiating the function in data(){} itself.

Thanks in advance.

ContentLicense: CC BY-SA 4.0


问:
How to get text from unmanaged application to a c# application?
I have a 3rd party application, which creates several windows of which each has a textbox with text I want. I then want to use that information within my application, so I just need to obtain that information (possible trigger some commands back to it later on by pressing buttons)

The 3rd party application is un-managed C++.
My application is C# (.NET 4.0).

I have seen that you can do 'hooks' into other application but I'll be honest I am completely lost of which route to take and how to go about it.

Some advice would be great.

答:
You will need to use COM interop. More here

http://msdn.microsoft.com/en-us/library/aa645736%28v=vs.71%29.aspx

http://www.liensberger.it/web/blog/?p=323


问:
Using "this" as parameter in an existing Javascript function called by jQuery.on() event
Problem:

I have some selects with options in my HTML code and I have set an on change event handler, to figure out, when a selection will be changed.

The following code shows the jQuery code to get the on change:

```<code> $(document).on('change', '.anyHtmlSelect', updateState);
</code>```

I have an existing Javascript function, that should be used as callback function.

The Javascript function looks like:

```<code>function updateState(element)
{
    var currentId = element.attr("id");
}
</code>```

Question:

How can I get the changed select as element?

I have tried the following:

```<code> $(document).on('change', '.anyHtmlSelect', updateState($(this));
</code>```

but it doesn't work.

答:
After some research I have found a solution I would share with you.

In my solution, I created an anonymous function, which calls the updateState function with $(this) as parameter.

```<code>$(document).on('change', '.anyHtmlSelect', function () {
    updateState($(this));
});
</code>```

Is there a better solution?

Body:
Problem:

I have some selects with options in my HTML code and I have set an on change event handler, to figure out, when a selection will be changed.

The following code shows the jQuery code to get the on change:

 $(document).on('change', '.anyHtmlSelect', updateState);

I have an existing Javascript function, that should be used as callback function.

The Javascript function looks like:

function updateState(element)
{
    var currentId = element.attr("id");
}

Question:

How can I get the changed select as element?

I have tried the following:

 $(document).on('change', '.anyHtmlSelect', updateState($(this));

but it doesn't work.

Body:
After some research I have found a solution I would share with you.

In my solution, I created an anonymous function, which calls the updateState function with $(this) as parameter.

$(document).on('change', '.anyHtmlSelect', function () {
    updateState($(this));
});

Is there a better solution?


问:
Xcode is complaining that I need an icon for an iPhone 7 but there is nowher
I am so confused!!!! I've created an app which works great on all IOS phones and iPads but Xcode is complaining that I need an icon for iPone 7. It's stating that it wants an icon of 60x60@2x. OK....lets add it...I've gone into Assets--> Appicon and there is no place to add the icon Xcode is complaining about. On the iPad the icon is visible but on the iPhone 7 it's blank:

As you can see from below there is nowhere to add it:

Where do i put the image?

This is the warning I'm getting:

Blah/Blah/Blah/Assets.xcassets: A 60x60@2x app icon is required for iPhone apps targeting iOS 7.0 and later

Because I've got an old iPad which cannot be updated above IOS 9.3, I'm wondering if this is the indue?

I've set the Deployment Info like so:

Deployment info

Any help you can give will be appreciated, and I will take abuse if it's something simple, but being team players I'm sure that won't happen :)

My name is Alex by the way and I've only been coding in Swift for 3 months, so go easy on me :)

Alex

答:
You have no iPhone icons in your assets at all according to your screenshot. It looks like you originally created the app for iPad and went universal later?

With the app icons open in your asset catalogue, open the inspector on the right hand side (see this SO answer for an image - different problem, same solution) and check the empty boxes to get spaces to add appropriate app icons.


问:
which language choose for server side programming laravel or nodejs
I know Html, CSS, javascript, bootstrap so I wanted to move on now I am confused which server side language to choose I learned basic PHP. I have a project to complete which has real-time collaboration, file uploads etc. Now I wanted to learn and complete my project within 2or3 months. Need some suggestion. TIA</p>

答:
Although you can create real-time applications using PHP, Node.js is "naturally" a better fit for this kind of application. Besides that as you said that you are choosing a new language to learn, I suggest you to see which one is becoming more expressive and that will probably have more attraction on the market from now on. The Developers Survey from Stack Overflow is a good source of information for you to start this research.

2017:
https://insights.stackoverflow.com/survey/2017#most-popular-technologies

2016:
https://insights.stackoverflow.com/survey/2016#technology-most-popular-technologies

As a basis for what I said about Node.js and real-time applications:

Why the Hell Would You Use Node.js

https://medium.com/the-node-js-collection/why-the-hell-would-you-use-node-js-4b053b94ab8e

Where Node.js really shines is in building fast, scalable network
  applications, as it’s capable of handling a huge number of
  simultaneous connections with high throughput, which equates to high
  scalability. How it works under-the-hood is pretty interesting.
  Compared to traditional web-serving techniques where each connection
  (request) spawns a new thread, taking up system RAM and eventually
  maxing-out at the amount of RAM available, Node.js operates on a
  single-thread, using non-blocking I/O calls, allowing it to support
  tens of thousands of concurrent connections (held in the event loop).

What aspects of Node.js make it suitable for real-time web applications?

https://www.quora.com/What-aspects-of-Node-js-make-it-suitable-for-real-time-web-applications

And here goes some suggestions for your adventure:

https://socket.io/

http://restify.com/#socketio


问:
Retrieving the right position of a scaled UIView
I'm having trouble retrieving the current position of a view, absolutely in the iPhone screen, when the view is scaled.
Here is a minimal example of what I've done.

I have a single elliptical view on screen. When I tap, it grows and start to shiver to show that it is selected. Then I can drag the view all over the screen.

Here is the code:

ViewController

```<code>import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // The View
    let toDrag = MyView(frame: CGRect(x: 0, y: 0, width: 50, height: 40))
    toDrag.center = CGPoint(x:100, y:100)
    // The gesture recognizer
    let panGestRec = UIPanGestureRecognizer(target: self, action:#selector(self.panView(sender:)))
    toDrag.addGestureRecognizer(panGestRec)

    self.view.addSubview(toDrag)
}

func panView(sender: UIPanGestureRecognizer) {
    guard let senderView = sender.view else { return }

    if sender.state == .recognized { print("Pan Recognized", terminator:"")}
    if sender.state == .began { print("Pan began", terminator: "") }
    if sender.state == .changed { print("Pan changed", terminator: "") }
    if sender.state == .ended { print("Pan ended", terminator: "") }

    let point = senderView.convert(senderView.center, to: nil)

    print (" point \(point)")
    let translation = sender.translation(in: self.view)
    senderView.center = CGPoint(x: senderView.center.x + translation.x, y: senderView.center.y + translation.y)
    sender.setTranslation(CGPoint.zero, in: self.view)
}
}
</code>```

MyView

```<code>import UIKit

class MyView: UIView {

var isAnimated: Bool = false

override init(frame: CGRect) {
    super.init(frame: frame) // calls designated initializer
    self.isOpaque = false
    self.backgroundColor = UIColor.clear
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.isOpaque = false
    self.backgroundColor = UIColor.clear
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    isAnimated = true
    rotate1()
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    isAnimated = false
    endRotation()
}

override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    isAnimated = false
    endRotation()
}

override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else {return}
    context.addEllipse(in: rect)
    context.setLineWidth(1.0)
    context.setStrokeColor(UIColor.black.cgColor)
    context.setFillColor(UIColor.red.cgColor)
    context.drawPath(using: .fillStroke)
}

func rotate1() {
    guard isAnimated else { return }
    UIView.animate(withDuration: 0.05, delay:0.0, options: [], animations: {
        self.transform = CGAffineTransform.init(rotationAngle:.pi/16).scaledBy(x: 1.5, y: 1.5)
    }, completion: { _ in
        self.rotate2()
    })
}

func rotate2() {
    guard isAnimated else { return }
    UIView.animate(withDuration: 0.05, delay:0.0, options: [], animations: {
        self.transform = CGAffineTransform.init(rotationAngle:.pi/(-16)).scaledBy(x: 1.5, y: 1.5)
    }, completion: { _ in
        self.rotate1()
    })

}
func endRotation () {
    // End existing animation
    UIView.animate(withDuration: 0.5, delay:0.0, options: .beginFromCurrentState, animations: {
        self.transform = CGAffineTransform.init(rotationAngle:0 ).scaledBy(x: 1, y: 1)
    }, completion: nil)
}
}
</code>```

With this version, here are some displays of the position

```<code>Pan began point (233.749182687299, 195.746572421573)
Pan changed point (175.265022520054, 181.332358181369)
Pan changed point (177.265022520054, 184.332358181369)
Pan changed point (177.265022520054, 184.332358181369)
Pan changed point (178.265022520054, 185.332358181369)
Pan changed point (179.265022520054, 186.332358181369)
Pan changed point (180.265022520054, 187.332358181369)
Pan changed point (180.265022520054, 188.332358181369)
Pan changed point (181.265022520054, 188.332358181369)
Pan RecognizedPan ended point (181.265022520054, 189.332358181369)
</code>```

You can see that the first position (began point) isn't correct: the view was animated at that moment. The other positions are OK, when dragging, the view don't animate.

If I comment the code in rotate1 and rotate2, all the positions are correct, so I assume that the sizing and eventually the rotation of the view are interfering in the result. My question is: how can I retrieve the correct position of the view, when it is scaled? Obviously, the line

senderView.convert(senderView.center, to: nil)

didn't make what I thought : converting the coordinate to the fixed size screen coordinates?

答:
In fact, I had another problem with view convert (Retrieve the right position of a subView with auto-layout)
and my problem was the same, so the solution is here...

I didn't use the method correctly. If I change using beninho85's solution (and even more cleaner cosyn's method to use just one view), it works! I can have the right coordinates even if the view is animated.

I just had to replace, in  ViewController :

let point = senderView.convert(senderView.center, to: nil)

with

let point = senderView.convert(CGPoint(x:senderView.bounds.midX, y:senderView.bounds.midY), to: nil)

Body:
I'm having trouble retrieving the current position of a view, absolutely in the iPhone screen, when the view is scaled.
Here is a minimal example of what I've done.

I have a single elliptical view on screen. When I tap, it grows and start to shiver to show that it is selected. Then I can drag the view all over the screen.

Here is the code:

ViewController

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // The View
    let toDrag = MyView(frame: CGRect(x: 0, y: 0, width: 50, height: 40))
    toDrag.center = CGPoint(x:100, y:100)
    // The gesture recognizer
    let panGestRec = UIPanGestureRecognizer(target: self, action:#selector(self.panView(sender:)))
    toDrag.addGestureRecognizer(panGestRec)

    self.view.addSubview(toDrag)
}

func panView(sender: UIPanGestureRecognizer) {
    guard let senderView = sender.view else { return }

    if sender.state == .recognized { print("Pan Recognized", terminator:"")}
    if sender.state == .began { print("Pan began", terminator: "") }
    if sender.state == .changed { print("Pan changed", terminator: "") }
    if sender.state == .ended { print("Pan ended", terminator: "") }

    let point = senderView.convert(senderView.center, to: nil)

    print (" point \(point)")
    let translation = sender.translation(in: self.view)
    senderView.center = CGPoint(x: senderView.center.x + translation.x, y: senderView.center.y + translation.y)
    sender.setTranslation(CGPoint.zero, in: self.view)
}
}

MyView

import UIKit

class MyView: UIView {

var isAnimated: Bool = false

override init(frame: CGRect) {
    super.init(frame: frame) // calls designated initializer
    self.isOpaque = false
    self.backgroundColor = UIColor.clear
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.isOpaque = false
    self.backgroundColor = UIColor.clear
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    isAnimated = true
    rotate1()
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    isAnimated = false
    endRotation()
}

override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    isAnimated = false
    endRotation()
}

override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else {return}
    context.addEllipse(in: rect)
    context.setLineWidth(1.0)
    context.setStrokeColor(UIColor.black.cgColor)
    context.setFillColor(UIColor.red.cgColor)
    context.drawPath(using: .fillStroke)
}

func rotate1() {
    guard isAnimated else { return }
    UIView.animate(withDuration: 0.05, delay:0.0, options: [], animations: {
        self.transform = CGAffineTransform.init(rotationAngle:.pi/16).scaledBy(x: 1.5, y: 1.5)
    }, completion: { _ in
        self.rotate2()
    })
}

func rotate2() {
    guard isAnimated else { return }
    UIView.animate(withDuration: 0.05, delay:0.0, options: [], animations: {
        self.transform = CGAffineTransform.init(rotationAngle:.pi/(-16)).scaledBy(x: 1.5, y: 1.5)
    }, completion: { _ in
        self.rotate1()
    })

}
func endRotation () {
    // End existing animation
    UIView.animate(withDuration: 0.5, delay:0.0, options: .beginFromCurrentState, animations: {
        self.transform = CGAffineTransform.init(rotationAngle:0 ).scaledBy(x: 1, y: 1)
    }, completion: nil)
}
}

With this version, here are some displays of the position

Pan began point (233.749182687299, 195.746572421573)
Pan changed point (175.265022520054, 181.332358181369)
Pan changed point (177.265022520054, 184.332358181369)
Pan changed point (177.265022520054, 184.332358181369)
Pan changed point (178.265022520054, 185.332358181369)
Pan changed point (179.265022520054, 186.332358181369)
Pan changed point (180.265022520054, 187.332358181369)
Pan changed point (180.265022520054, 188.332358181369)
Pan changed point (181.265022520054, 188.332358181369)
Pan RecognizedPan ended point (181.265022520054, 189.332358181369)

You can see that the first position (began point) isn't correct: the view was animated at that moment. The other positions are OK, when dragging, the view don't animate.

If I comment the code in rotate1 and rotate2, all the positions are correct, so I assume that the sizing and eventually the rotation of the view are interfering in the result. My question is: how can I retrieve the correct position of the view, when it is scaled? Obviously, the line

senderView.convert(senderView.center, to: nil)

didn't make what I thought : converting the coordinate to the fixed size screen coordinates?


问:
regex only spaces - javascript
I need to filter a field composed of only spaces; something like:

```<code>if (word == /((\s)+)/ ) return 'no name'
</code>```

but it doesn't work ... any other ideas?
thank you for your ideas!

答:
How about NOT checking "word" by RegExp but using RegExp to replace all whitespaces and look what's left. If it's empty "word" is only composed by whitespaces:

```<code>   if (word.replace(/\s+/, "") === "") {
      console && console.log("empty string found!");
      return 'no name';
   }
</code>```

Title: regex only spaces - javascript

Body:
I need to filter a field composed of only spaces; something like:

if (word == /((\s)+)/ ) return 'no name'

but it doesn't work ... any other ideas?
thank you for your ideas!

Body:
How about NOT checking "word" by RegExp but using RegExp to replace all whitespaces and look what's left. If it's empty "word" is only composed by whitespaces:

   if (word.replace(/\s+/, "") === "") {
      console && console.log("empty string found!");
      return 'no name';
   }


问:
Is there a way to unlock all http methods without changing the war file?
I have a .war file deployed in Jetty (I didn't build it, and it's not possible to create a new instance).

An OPTIONS request to http://example.com/rest/object/{uuid}responds with HEAD, DELETE, GET, OPTIONS. The people that built the war claim that it's not an issue with their file.

Is there a Jetty config file I can change to allow all the http methods?

If this is something I have to do in a Jetty Java file, I am a Jetty noob, so please be verbose, or point me to some docs that I can read.

Note: I can POST via CURL, but not via http...

Edit: (I was posting to a different Endpoint with CURL)

答:
This is not an answer to the question I posted, but it allowed me to understand what was happening, which lead to the question being irrelevant for my particular issue. With that being said, I won't mark this as the answer in the event it is answerable (which I don't think it is, you'll see why in a minute).

The short answer is I was trying to POST to an endpoint that expects the object to already exist:

```<code>http://example.com/rest/object/{uuid}
</code>```

What I should have done was use an endpoint, where if you POST, it understands you want to create a new object:

```<code>http://example.com/rest/object
</code>```

The longer answer

Let's say you have a REST Endpoint that allows you to get a specific object, like this:

```<code>http://example.com/rest/object/{uuid}
</code>```

Since you're dealing with a specific object, you typically wouldn't want to POST a new object there. POST means 'create a new object'. If you were able to POST there, you'd essentially be overwriting that Object... and that's what PUT is for, but it's debatable. Also, PUT wasn't an option either...

So, because of its subjective nature, some Web Services limit request methods so you must do it the way the architects intended. The REST Server I am running doesn't have much in the way of documentation, so I was unaware of these restrictions, and am still puzzled by it.

What I thought I was doing was saying "OK, I want to create an object with this id. So if I POST my data to that specific UUID, the server will know I want to create a new object." What I should have been saying is "OK, I want to create a new object. It's UUID is already defined in the data, so all I need to do is send it to the endpoint that handles those objects, and expects a POST." Like this:

```<code>http://example.com/rest/object
</code>```

Body:
This is not an answer to the question I posted, but it allowed me to understand what was happening, which lead to the question being irrelevant for my particular issue. With that being said, I won't mark this as the answer in the event it is answerable (which I don't think it is, you'll see why in a minute).

The short answer is I was trying to POST to an endpoint that expects the object to already exist:

http://example.com/rest/object/{uuid}

What I should have done was use an endpoint, where if you POST, it understands you want to create a new object:

http://example.com/rest/object

The longer answer

Let's say you have a REST Endpoint that allows you to get a specific object, like this:

http://example.com/rest/object/{uuid}

Since you're dealing with a specific object, you typically wouldn't want to POST a new object there. POST means 'create a new object'. If you were able to POST there, you'd essentially be overwriting that Object... and that's what PUT is for, but it's debatable. Also, PUT wasn't an option either...

So, because of its subjective nature, some Web Services limit request methods so you must do it the way the architects intended. The REST Server I am running doesn't have much in the way of documentation, so I was unaware of these restrictions, and am still puzzled by it.

What I thought I was doing was saying "OK, I want to create an object with this id. So if I POST my data to that specific UUID, the server will know I want to create a new object." What I should have been saying is "OK, I want to create a new object. It's UUID is already defined in the data, so all I need to do is send it to the endpoint that handles those objects, and expects a POST." Like this:

http://example.com/rest/object


问:
Passing a long value from one fragment through the main activity to another fragment
I have a main_activity containing two fragments. When a button is clicked on beatTimeFragment, I want beatTimeFragment to determine the msec past 1970 that the button was pressed and pass it to toneTimeFragment by way of the main activity. The toneTimeFragment will then compare the response to a standard beat and give an offSet.

Every example i have seen passes string data rather than long data. In my code, I tried passing String data then converting it to long data. The string data gets transfered (i can was it show string). But the long gives a response of 0 or it kick me out if i do not have the exception.

Is there a way to get the conversion to work or if not, how do i set up for a long data transfer rather than String by removing the

```<code>beatTimeDisplay.getText().toString()
</code>```

at the end of the beatTimeFragment?

main_activity

```<code>public class MainActivity extends AppCompatActivity implements
BeatTimeFragment.BeatTimeListener{

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

//Get called by BeatTimeFragment when button is pushed
@Override
public void sendBeatData(String beatTime) {
    ToneTimeFragment toneFragment = (ToneTimeFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
    toneFragment.setBeatLong(beatTime);
}
}
</code>```

toneTimeFragment

```<code>public class ToneTimeFragment extends Fragment {

public void setBeatLong(String beatTime) {
    try {
        beatTimeL = Long.parseLong(beatTime);
    } catch (NumberFormatException e) {
        System.out.println("NumberFormatException: " + e.getMessage());
    }
    // beatTimeL = Long.parseLong(beatTime);
    offSet = beatTimeL - toneTime;
    offSetView.setText(beatTime + " msec");
</code>```

beatTimeFragment

```<code>public class BeatTimeFragment extends Fragment {

private static Button beatBtn;
private static TextView beatTimeDisplay;
int q = 0;
long beatTime = 0;

//set up sending beatTime
BeatTimeListener activityCommander;

public interface BeatTimeListener{
    public void sendBeatData(String beatTime);
}

//setup to send data to top
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        activityCommander = (BeatTimeListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString());
    }
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.beat_time_fragment, container, false);

    beatTimeDisplay = (TextView) view.findViewById(R.id.beatTimeDisplay);
    final Button beatBtn = (Button) view.findViewById(R.id.beatBtn);

    beatBtn.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v){

                    long beatTime= System.currentTimeMillis();
                    TextView view1 = (TextView) view.findViewById(R.id.beatTimeDisplay);
                    view1.setText(beatTime + " msec");
                    readySendBeat(v);

                }
            }

    );

    return view;
}

//calls to send data when button clicked
public void readySendBeat(View v) {
    activityCommander.sendBeatData(beatTimeDisplay.getText().toString());
     }
}
</code>```

答:
While debugging, i realized that i was not passing my beatTime value into the readySendBeat method in the BeatTimeFragment. When i added the object to the method then I was able to pass the data and no longer get a value of 0.</p>

```<code>public void readySendBeat(Long beatTime){
    activityCommander.sendBeatData(beatTime);
    }
</code>```

Body:
I have a main_activity containing two fragments. When a button is clicked on beatTimeFragment, I want beatTimeFragment to determine the msec past 1970 that the button was pressed and pass it to toneTimeFragment by way of the main activity. The toneTimeFragment will then compare the response to a standard beat and give an offSet.

Every example i have seen passes string data rather than long data. In my code, I tried passing String data then converting it to long data. The string data gets transfered (i can was it show string). But the long gives a response of 0 or it kick me out if i do not have the exception.

Is there a way to get the conversion to work or if not, how do i set up for a long data transfer rather than String by removing the

beatTimeDisplay.getText().toString()

at the end of the beatTimeFragment?

main_activity

public class MainActivity extends AppCompatActivity implements
BeatTimeFragment.BeatTimeListener{

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

//Get called by BeatTimeFragment when button is pushed
@Override
public void sendBeatData(String beatTime) {
    ToneTimeFragment toneFragment = (ToneTimeFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
    toneFragment.setBeatLong(beatTime);
}
}

toneTimeFragment

public class ToneTimeFragment extends Fragment {

public void setBeatLong(String beatTime) {
    try {
        beatTimeL = Long.parseLong(beatTime);
    } catch (NumberFormatException e) {
        System.out.println("NumberFormatException: " + e.getMessage());
    }
    // beatTimeL = Long.parseLong(beatTime);
    offSet = beatTimeL - toneTime;
    offSetView.setText(beatTime + " msec");

beatTimeFragment

public class BeatTimeFragment extends Fragment {

private static Button beatBtn;
private static TextView beatTimeDisplay;
int q = 0;
long beatTime = 0;

//set up sending beatTime
BeatTimeListener activityCommander;

public interface BeatTimeListener{
    public void sendBeatData(String beatTime);
}

//setup to send data to top
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        activityCommander = (BeatTimeListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString());
    }
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.beat_time_fragment, container, false);

    beatTimeDisplay = (TextView) view.findViewById(R.id.beatTimeDisplay);
    final Button beatBtn = (Button) view.findViewById(R.id.beatBtn);

    beatBtn.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v){

                    long beatTime= System.currentTimeMillis();
                    TextView view1 = (TextView) view.findViewById(R.id.beatTimeDisplay);
                    view1.setText(beatTime + " msec");
                    readySendBeat(v);

                }
            }

    );

    return view;
}

//calls to send data when button clicked
public void readySendBeat(View v) {
    activityCommander.sendBeatData(beatTimeDisplay.getText().toString());
     }
}

Body:
While debugging, i realized that i was not passing my beatTime value into the readySendBeat method in the BeatTimeFragment. When i added the object to the method then I was able to pass the data and no longer get a value of 0.

public void readySendBeat(Long beatTime){
    activityCommander.sendBeatData(beatTime);
    }


答:
The first argument that is automatically passed to an event handler is a reference to the event itself, not the element that caused the event. To access the DOM element that triggered the event, use this:

Simply change:

```<code>function updateState(element)
{
    var currentId = element.attr("id");
}
</code>```

to:

```<code>function updateState(event) {
    var currentId = this.attr("id");
}
</code>```

Title: Using "this" as parameter in an existing Javascript function called by jQuery.on() event

Body:
The first argument that is automatically passed to an event handler is a reference to the event itself, not the element that caused the event. To access the DOM element that triggered the event, use this:

Simply change:

function updateState(element)
{
    var currentId = element.attr("id");
}

to:

function updateState(event) {
    var currentId = this.attr("id");
}


问:
unable to import BlogML.XML in my wordpress blog
I am unable to import BlogML.XML in my word press blog. It giving the following error
after creating .htaccess ->

The uploaded file could not be moved to /htdocs/blog.myblog.com/wp-content/uploads/2010/12.

The following are the content of my .htaccess file-->

php_value upload_max_filesize 40M

php_value post_max_size 40M

php_value max_execution_time 2000

php_value max_input_time 2000

答:
I would say that there is a permission issue with the uploads folder. Can you upload any file (like an image) using the Media Library? If not, you have to fix the permissions (most probably the group of the upload folder).

To set the correct permissions, connect to your sevrer through SSH, navigate to the wp-content folder and use the following commands:

```<code>chgrp GROUP_NAME_OF_APACHE_SERVER -R .
chmod g+w -R .
</code>```

That should fix the upload issue.

Body:
I would say that there is a permission issue with the uploads folder. Can you upload any file (like an image) using the Media Library? If not, you have to fix the permissions (most probably the group of the upload folder).

To set the correct permissions, connect to your sevrer through SSH, navigate to the wp-content folder and use the following commands:

chgrp GROUP_NAME_OF_APACHE_SERVER -R .
chmod g+w -R .

That should fix the upload issue.


问:
Pandas load text file error: CParserError: Error tokenizing data
Pandas load text file error: CParserError: Error tokenizing data.

I'm a new pandas learner. I'm trying to use pandas to open a text file. I write code in python, then access to the right path and run the python file, but failed.

Here is the original data. There's no field name, all the rows of data are separated with space:

```<code>2017-07-02 23:59:51127.0.0.1 GET /ecvv_product/EcvvSearchProduct.aspx cid=202104&p=&pageindex=&kw=electric-skateboard 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 986 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvHotSearchProduct.aspx kw=hydrogen-motor 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 2539 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvSearchProduct.aspx cid=100005713&p=&pageindex=&kw=electric-skateboard 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 1172 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvHotSearchProduct.aspx kw=stainless-stand 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 3152 31.7.188.55
</code>```

Here is my simple python code:

```<code>import pandas as pd

DATA_FILE='data.log'
df = pd.read_table(DATA_FILE, sep=" ")

print(df)
</code>```

But I got error as follows:

```<code>Traceback (most recent call last):
  File "open.py", line 7, in <module>
    df = pd.read_table(DATA_FILE, sep=" ")
  File "C:\Users\hh\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 646, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\hh\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 401, in _read
    data = parser.read()
  File "C:\Users\hh\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 939, in read
    ret = self._engine.read(nrows)
  File "C:\Users\hh\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 1508, in read
    data = self._reader.read(nrows)
  File "pandas\parser.pyx", line 848, in pandas.parser.TextReader.read (pandas\parser.c:10415)
  File "pandas\parser.pyx", line 870, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:10691)
  File "pandas\parser.pyx", line 924, in pandas.parser.TextReader._read_rows (pandas\parser.c:11437)
  File "pandas\parser.pyx", line 911, in pandas.parser.TextReader._tokenize_rows (pandas\parser.c:11308)
  File "pandas\parser.pyx", line 2024, in pandas.parser.raise_parser_error (pandas\parser.c:27037)
pandas.io.common.CParserError: Error tokenizing data. C error: Expected 6 fields in line 4, saw 17
</code>```

There must be something run with my python code. How to get the correct syntax code?

答:
You missed a space on the first line:

```<code>2017-07-02 23:59:51127.0.0.1
</code>```

Replace to:

```<code>2017-07-02 23:59:51 127.0.0.1
</code>```

Just tested:

```<code>In [12]: cat data.log
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvSearchProduct.aspx cid=202104&p=&pageindex=&kw=electric-skateboard 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 986 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvHotSearchProduct.aspx kw=hydrogen-motor 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 2539 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvSearchProduct.aspx cid=100005713&p=&pageindex=&kw=electric-skateboard 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 1172 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvHotSearchProduct.aspx kw=stainless-stand 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 3152 31.7.188.55

In [13]: dx = pd.read_table('data.log', sep=" ", header=None)

In [14]: dx
Out[14]:
           0         1          2    3   \
0  2017-07-02  23:59:51  127.0.0.1  GET
1  2017-07-02  23:59:51  127.0.0.1  GET
2  2017-07-02  23:59:51  127.0.0.1  GET
3  2017-07-02  23:59:51  127.0.0.1  GET

                                        4   \
0     /ecvv_product/EcvvSearchProduct.aspx
1  /ecvv_product/EcvvHotSearchProduct.aspx
2     /ecvv_product/EcvvSearchProduct.aspx
3  /ecvv_product/EcvvHotSearchProduct.aspx

                                                  5     6  7          8   \
0    cid=202104&p=&pageindex=&kw=electric-skateboard  8082  -  127.0.0.1
1                                  kw=hydrogen-motor  8082  -  127.0.0.1
2  cid=100005713&p=&pageindex=&kw=electric-skateb...  8082  -  127.0.0.1
3                                 kw=stainless-stand  8082  -  127.0.0.1

                                                  9  10   11  12  13    14  \
0  Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;...  -  200   0   0   986
1  Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;...  -  200   0   0  2539
2  Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;...  -  200   0   0  1172
3  Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;...  -  200   0   0  3152

            15
0  31.7.188.55
1  31.7.188.55
2  31.7.188.55
3  31.7.188.55
</code>```

Body:
Pandas load text file error: CParserError: Error tokenizing data.

I'm a new pandas learner. I'm trying to use pandas to open a text file. I write code in python, then access to the right path and run the python file, but failed.

Here is the original data. There's no field name, all the rows of data are separated with space:

2017-07-02 23:59:51127.0.0.1 GET /ecvv_product/EcvvSearchProduct.aspx cid=202104&p=&pageindex=&kw=electric-skateboard 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 986 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvHotSearchProduct.aspx kw=hydrogen-motor 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 2539 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvSearchProduct.aspx cid=100005713&p=&pageindex=&kw=electric-skateboard 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 1172 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvHotSearchProduct.aspx kw=stainless-stand 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 3152 31.7.188.55

Here is my simple python code:

import pandas as pd

DATA_FILE='data.log'
df = pd.read_table(DATA_FILE, sep=" ")

print(df)

But I got error as follows:

Traceback (most recent call last):
  File "open.py", line 7, in <module>
    df = pd.read_table(DATA_FILE, sep=" ")
  File "C:\Users\hh\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 646, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\hh\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 401, in _read
    data = parser.read()
  File "C:\Users\hh\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 939, in read
    ret = self._engine.read(nrows)
  File "C:\Users\hh\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 1508, in read
    data = self._reader.read(nrows)
  File "pandas\parser.pyx", line 848, in pandas.parser.TextReader.read (pandas\parser.c:10415)
  File "pandas\parser.pyx", line 870, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:10691)
  File "pandas\parser.pyx", line 924, in pandas.parser.TextReader._read_rows (pandas\parser.c:11437)
  File "pandas\parser.pyx", line 911, in pandas.parser.TextReader._tokenize_rows (pandas\parser.c:11308)
  File "pandas\parser.pyx", line 2024, in pandas.parser.raise_parser_error (pandas\parser.c:27037)
pandas.io.common.CParserError: Error tokenizing data. C error: Expected 6 fields in line 4, saw 17

There must be something run with my python code. How to get the correct syntax code?

Body:
You missed a space on the first line:

2017-07-02 23:59:51127.0.0.1

Replace to:

2017-07-02 23:59:51 127.0.0.1

Just tested:

In [12]: cat data.log
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvSearchProduct.aspx cid=202104&p=&pageindex=&kw=electric-skateboard 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 986 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvHotSearchProduct.aspx kw=hydrogen-motor 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 2539 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvSearchProduct.aspx cid=100005713&p=&pageindex=&kw=electric-skateboard 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 1172 31.7.188.55
2017-07-02 23:59:51 127.0.0.1 GET /ecvv_product/EcvvHotSearchProduct.aspx kw=stainless-stand 8082 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;+DigExt;+DTS+Agent - 200 0 0 3152 31.7.188.55

In [13]: dx = pd.read_table('data.log', sep=" ", header=None)

In [14]: dx
Out[14]:
           0         1          2    3   \
0  2017-07-02  23:59:51  127.0.0.1  GET
1  2017-07-02  23:59:51  127.0.0.1  GET
2  2017-07-02  23:59:51  127.0.0.1  GET
3  2017-07-02  23:59:51  127.0.0.1  GET

                                        4   \
0     /ecvv_product/EcvvSearchProduct.aspx
1  /ecvv_product/EcvvHotSearchProduct.aspx
2     /ecvv_product/EcvvSearchProduct.aspx
3  /ecvv_product/EcvvHotSearchProduct.aspx

                                                  5     6  7          8   \
0    cid=202104&p=&pageindex=&kw=electric-skateboard  8082  -  127.0.0.1
1                                  kw=hydrogen-motor  8082  -  127.0.0.1
2  cid=100005713&p=&pageindex=&kw=electric-skateb...  8082  -  127.0.0.1
3                                 kw=stainless-stand  8082  -  127.0.0.1

                                                  9  10   11  12  13    14  \
0  Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;...  -  200   0   0   986
1  Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;...  -  200   0   0  2539
2  Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;...  -  200   0   0  1172
3  Mozilla/4.0+(compatible;+MSIE+5.0;+Windows+NT;...  -  200   0   0  3152

            15
0  31.7.188.55
1  31.7.188.55
2  31.7.188.55
3  31.7.188.55


问:
Return same format as requests for JSON errors in Phoenix
I currently have a Phoenix application that has both JSON and HTML endpoints.

I would like to return the errors that are the most appropriate for the given request, but it always defaults to the render("XXX.html, _) function even when the request's format is application/json.

Is there a way to return JSON for requests of type application/json and HTML for everything else?

答:
You may wanna check the render_errors option (see docs) in your config.exs file and add the json format as well as html.

```<code>config :my_app, MyApp.Endpoint,
  # ...
  render_errors: [view: MyApp.ErrorView, accepts: ~w(html json)]
</code>```

Also, be sure to be sending the appropriate Accept header.

Body:
You may wanna check the render_errors option (see docs) in your config.exs file and add the json format as well as html.

config :my_app, MyApp.Endpoint,
  # ...
  render_errors: [view: MyApp.ErrorView, accepts: ~w(html json)]

Also, be sure to be sending the appropriate Accept header.