问:
Django Rest Framework global timestamp
I have a simple Django model:

```<code>class Item(models.Model):
    category = models.ForeignKey(Category)
    system = models.ForeignKey(System)
    company = models.ForeignKey(Company)
    catalog_number = models.CharField(max_length=55)
    name = models.CharField(max_length=255)
    description = models.CharField(max_length=755)
    price_usd = models.DecimalField(max_digits=22, decimal_places=2)
    price_cad = models.DecimalField(max_digits=22, decimal_places=2)
    price_eur = models.DecimalField(max_digits=22, decimal_places=2)
    price_gbp = models.DecimalField(max_digits=22, decimal_places=2)
    notes = models.TextField()

    def __unicode__(self):
         return self.name
</code>```

And I'm using Django Rest Framework to expose a simple API endpoint:

```<code>from .models import Item
from rest_framework import serializers
from rest_framework import permissions

class ItemSerializer(serializers.HyperlinkedModelSerializer):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    category = serializers.RelatedField(source='category')
    system = serializers.RelatedField(source='system')
    company = serializers.RelatedField(source='company')

    class Meta:
        model = Item
        fields = (
            'catalog_number',
            'price_usd',
            'price_cad',
            'price_eur',
            'price_gbp',
        )
</code>```

My question is, I would like to include a single timestamp with json dump which would allow a consumer application to determine if the data has been updated since it was last accessed. Basically a global timestamp for when the database was last updated.

Should this be a queryset in the serializer which finds the most recent timestamp (not yet declared in the model) from the Item model? Or is there some setting in Django/ Rest Framework which allows determination of when the database was last updated?

答:
You can you TimeStampedModel of django_extensions
 as deacribed in docs

TimeStampedModel - An Abstract Base Class model that provides self-managed
  created and modified fields.

```<code>from django_extensions.db.models import TimeStampedModel

class Item(TimeStampedModel):
    ...
    ...
</code>```

you can use modified field to determine when the Item
  last updated.

Title: Django Rest Framework global timestamp

Body:
I have a simple Django model:

class Item(models.Model):
    category = models.ForeignKey(Category)
    system = models.ForeignKey(System)
    company = models.ForeignKey(Company)
    catalog_number = models.CharField(max_length=55)
    name = models.CharField(max_length=255)
    description = models.CharField(max_length=755)
    price_usd = models.DecimalField(max_digits=22, decimal_places=2)
    price_cad = models.DecimalField(max_digits=22, decimal_places=2)
    price_eur = models.DecimalField(max_digits=22, decimal_places=2)
    price_gbp = models.DecimalField(max_digits=22, decimal_places=2)
    notes = models.TextField()

    def __unicode__(self):
         return self.name

And I'm using Django Rest Framework to expose a simple API endpoint:

from .models import Item
from rest_framework import serializers
from rest_framework import permissions

class ItemSerializer(serializers.HyperlinkedModelSerializer):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    category = serializers.RelatedField(source='category')
    system = serializers.RelatedField(source='system')
    company = serializers.RelatedField(source='company')

    class Meta:
        model = Item
        fields = (
            'catalog_number',
            'price_usd',
            'price_cad',
            'price_eur',
            'price_gbp',
        )

My question is, I would like to include a single timestamp with json dump which would allow a consumer application to determine if the data has been updated since it was last accessed. Basically a global timestamp for when the database was last updated.

Should this be a queryset in the serializer which finds the most recent timestamp (not yet declared in the model) from the Item model? Or is there some setting in Django/ Rest Framework which allows determination of when the database was last updated?

Body:
You can you TimeStampedModel of django_extensions
 as deacribed in docs

TimeStampedModel - An Abstract Base Class model that provides self-managed
  created and modified fields.

from django_extensions.db.models import TimeStampedModel

class Item(TimeStampedModel):
    ...
    ...

you can use modified field to determine when the Item
  last updated.


来源: stackexchange

问:
Tensorflow Dataset extremely slow compared to queues
To do same task with Dataset-API seems to be 10-100 times slower than with queues.

This is what I am trying to do with Datasets:

```<code>dataset = tf.data.TFRecordDataset(filenames).repeat()
dataset = dataset.batch(100)
dataset = dataset.map(_parse_function)
dataset = dataset.prefetch(1000)
d = dataset.make_one_shot_iterator()

%timeit -n 200 sess.run(d.get_next())
</code>```

and this with queues:

```<code>filename_queue = tf.train.string_input_producer(filenames, capacity=1)

reader = tf.TFRecordReader()
_, serialized_example = reader.read_up_to(filename_queue, 100)

features = _parse_function(serialized_example)

coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
tf.train.start_queue_runners()

%timeit -n 200 sess.run(features)
</code>```

Observed results:

Dataset:
23.6 ms ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 200 loops each)

Queue:
481 µs ± 91.7 µs per loop (mean ± std. dev. of 7 runs, 200 loops each)

Why this happens? How to make the Dataset work faster?

Using tensorflow 1.4 and python 3.5

Full code to reproduce:

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

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))

def create_data(i):
    tfrecords_filename = '_temp/dstest/tt%d.tfr' % i

    writer = tf.python_io.TFRecordWriter(tfrecords_filename)

    for j in range(1000):
        f = tf.train.Features(feature={
            'x': _int64_feature([j]),
            "y": _int64_feature(np.random.randint(5, 100, size=np.random.randint(6)))
        })

        example = tf.train.Example(features=f)
        writer.write(example.SerializeToString())

    writer.close()
    return tfrecords_filename

def _parse_function(example_proto):
    features = {
        "x": tf.FixedLenFeature((), tf.int64),
        "y": tf.FixedLenSequenceFeature((), tf.int64, allow_missing=True)
    }
    parsed_features = tf.parse_example(example_proto, features)
    return parsed_features

os.makedirs("_temp/dstest", exist_ok=True)
sess = tf.InteractiveSession()

filenames = [create_data(i) for i in range(5)]

#### DATASET
dataset = tf.data.TFRecordDataset(filenames).repeat()
dataset = dataset.batch(100)
dataset = dataset.map(_parse_function)
dataset = dataset.prefetch(1000)
d = dataset.make_one_shot_iterator()

%timeit -n 200 sess.run(d.get_next())

#### QUEUE
filename_queue = tf.train.string_input_producer(filenames, capacity=1)

reader = tf.TFRecordReader()
_, serialized_example = reader.read_up_to(filename_queue, 100)

features = _parse_function(serialized_example)

coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
tf.train.start_queue_runners()

%timeit -n 200 sess.run(features)

coord.request_stop()
coord.join(threads)
</code>```

答:
Oh I figured it out. I am not supposed to call d.get_next() multiple times.

When I change it to be:

```<code>d = dataset.make_one_shot_iterator().get_next()
%timeit -n 200 sess.run(d)
</code>```

Then the speed is similar to the queue version, even without pre-fetching.

And ineed the result of sess.run call is always different.

ContentLicense: CC BY-SA 3.0

Body:
To do same task with Dataset-API seems to be 10-100 times slower than with queues.

This is what I am trying to do with Datasets:

dataset = tf.data.TFRecordDataset(filenames).repeat()
dataset = dataset.batch(100)
dataset = dataset.map(_parse_function)
dataset = dataset.prefetch(1000)
d = dataset.make_one_shot_iterator()

%timeit -n 200 sess.run(d.get_next())

and this with queues:

filename_queue = tf.train.string_input_producer(filenames, capacity=1)

reader = tf.TFRecordReader()
_, serialized_example = reader.read_up_to(filename_queue, 100)

features = _parse_function(serialized_example)

coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
tf.train.start_queue_runners()

%timeit -n 200 sess.run(features)

Observed results:

Dataset:
23.6 ms ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 200 loops each)

Queue:
481 µs ± 91.7 µs per loop (mean ± std. dev. of 7 runs, 200 loops each)

Why this happens? How to make the Dataset work faster?

Using tensorflow 1.4 and python 3.5

Full code to reproduce:

import tensorflow as tf
import numpy as np
import glob
import os

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))

def create_data(i):
    tfrecords_filename = '_temp/dstest/tt%d.tfr' % i

    writer = tf.python_io.TFRecordWriter(tfrecords_filename)

    for j in range(1000):
        f = tf.train.Features(feature={
            'x': _int64_feature([j]),
            "y": _int64_feature(np.random.randint(5, 100, size=np.random.randint(6)))
        })

        example = tf.train.Example(features=f)
        writer.write(example.SerializeToString())

    writer.close()
    return tfrecords_filename

def _parse_function(example_proto):
    features = {
        "x": tf.FixedLenFeature((), tf.int64),
        "y": tf.FixedLenSequenceFeature((), tf.int64, allow_missing=True)
    }
    parsed_features = tf.parse_example(example_proto, features)
    return parsed_features

os.makedirs("_temp/dstest", exist_ok=True)
sess = tf.InteractiveSession()

filenames = [create_data(i) for i in range(5)]

#### DATASET
dataset = tf.data.TFRecordDataset(filenames).repeat()
dataset = dataset.batch(100)
dataset = dataset.map(_parse_function)
dataset = dataset.prefetch(1000)
d = dataset.make_one_shot_iterator()

%timeit -n 200 sess.run(d.get_next())

#### QUEUE
filename_queue = tf.train.string_input_producer(filenames, capacity=1)

reader = tf.TFRecordReader()
_, serialized_example = reader.read_up_to(filename_queue, 100)

features = _parse_function(serialized_example)

coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
tf.train.start_queue_runners()

%timeit -n 200 sess.run(features)

coord.request_stop()
coord.join(threads)

Body:
Oh I figured it out. I am not supposed to call d.get_next() multiple times.

When I change it to be:

d = dataset.make_one_shot_iterator().get_next()
%timeit -n 200 sess.run(d)

Then the speed is similar to the queue version, even without pre-fetching.

And ineed the result of sess.run call is always different.


问:
Data table multiple condition with string vector
I would like to subset a data table with a condition that I want to apply on all column in vector of strings with a & condition in between. Example:

```<code>library(data.table)
test <- setDT(as.data.frame(list(ID = c(rep(1,10),rep(2,10)), time = rep(c(1:10),2),
                                 Input = rep(c(array(data = 0, dim = 5),1,array(data = 0, dim = 4)),2),
                                 replicate(4,sample(c(1:20), 10, replace = TRUE)))))

signalcolumns <- colnames(test)[! colnames(test) %in% c("ID","Input","time")]
</code>```

Now I want

```<code>test[X1 > 5 & X2 > 5 & X3 > 5 & X4 > 5]
</code>```

and I would like to write it with the signalcolumns.

```<code>test[get(signalcolumns) > 5]
</code>```

doesn't work as it set the condition only on the first X1 column. I don't see what syntax I could use here. I though of trying to evaluate an expression like

```<code>c(paste0(signalcolumns[1:(length(signalcolumns)-1)],">5 &"),
paste0(signalcolumns[(length(signalcolumns)-1)],">5") )
</code>```

but I am a bit stuck here.

答:
After specifying the .SDcols as 'signalcolumns', loop through the Subset of data.table, check whether it is greater than 5, and then Reduce to a single vector of TRUE/FALSE for each row to subset the rows

```<code>test[test[, Reduce(`&`, lapply(.SD, `>`, 5)), .SDcols = signalcolumns]]
</code>```

Body:
I would like to subset a data table with a condition that I want to apply on all column in vector of strings with a & condition in between. Example:

library(data.table)
test <- setDT(as.data.frame(list(ID = c(rep(1,10),rep(2,10)), time = rep(c(1:10),2),
                                 Input = rep(c(array(data = 0, dim = 5),1,array(data = 0, dim = 4)),2),
                                 replicate(4,sample(c(1:20), 10, replace = TRUE)))))

signalcolumns <- colnames(test)[! colnames(test) %in% c("ID","Input","time")]

Now I want

test[X1 > 5 & X2 > 5 & X3 > 5 & X4 > 5]

and I would like to write it with the signalcolumns.

test[get(signalcolumns) > 5]

doesn't work as it set the condition only on the first X1 column. I don't see what syntax I could use here. I though of trying to evaluate an expression like

c(paste0(signalcolumns[1:(length(signalcolumns)-1)],">5 &"),
paste0(signalcolumns[(length(signalcolumns)-1)],">5") )

but I am a bit stuck here.

Body:
After specifying the .SDcols as 'signalcolumns', loop through the Subset of data.table, check whether it is greater than 5, and then Reduce to a single vector of TRUE/FALSE for each row to subset the rows

test[test[, Reduce(`&`, lapply(.SD, `>`, 5)), .SDcols = signalcolumns]]


问:
Using := in data.table with paste()
I have started using data.table for a large population model. So far, I have been impressed because using the data.table structure decreases my simulation run times by about 30%. I am trying to further optimize my code and have included a simplified example. My two questions are:

Is is possible to use the := operator with this code?

Would using the := operator be quicker (although, if I am able to answer my first question, I should be able to answer my question 2!)?

I am using R version 3.1.2 on a machine running Windows 7 with data.table version 1.9.4.

Here is my reproducible example:

```<code>library(data.table)

## Create  example table and set initial conditions
nYears = 10
exampleTable = data.table(Site = paste("Site", 1:3))
exampleTable[ , growthRate := c(1.1, 1.2, 1.3), ]
exampleTable[ , c(paste("popYears", 0:nYears, sep = "")) := 0, ]

exampleTable[ , "popYears0" := c(10, 12, 13)] # set the initial population size

for(yearIndex in 0:(nYears - 1)){
    exampleTable[[paste("popYears", yearIndex + 1, sep = "")]] <-
    exampleTable[[paste("popYears", yearIndex, sep = "")]] *
    exampleTable[, growthRate]
}
</code>```

I am trying to do something like:

```<code>for(yearIndex in 0:(nYears - 1)){
    exampleTable[ , paste("popYears", yearIndex + 1, sep = "") :=
    paste("popYears", yearIndex, sep = "") * growthRate, ]
}
</code>```

However, this does not work because the paste does not work with the data.table, for example:

```<code>exampleTable[ , paste("popYears", yearIndex + 1, sep = "")]
# [1] "popYears10"
</code>```

I have looked through the data.table documentation. Section 2.9 of the FAQ uses cat, but this produces a null output.

```<code>exampleTable[ , cat(paste("popYears", yearIndex + 1, sep = ""))]
# [1] popYears10NULL
</code>```

Also, I tried searching Google and rseek.org, but didn't find anything. If am missing an obvious search term, I would appreciate a search tip. I have always found searching for R operators to be hard because search engines don't like symbols (e.g., ":=") and "R" can be vague.

答:
Struggling with column names is a strong indicator that the wide format is probably not the best choice for the given problem. Therefore, I suggest to do the computations in long form and to reshape the result from long to wide format, finally.

```<code>nYears = 10
params = data.table(Site = paste("Site", 1:3),
                    growthRate = c(1.1, 1.2, 1.3),
                    pop = c(10, 12, 13))
long <- params[CJ(Site = Site, Year = 0:nYears), on = "Site"][
  , growth := cumprod(shift(growthRate, fill = 1)), by = Site][
    , pop := pop * growth][]
dcast(long, Site + growthRate ~ sprintf("popYears%02i", Year), value.var = "pop")
</code>```

```<code>     Site growthRate popYears 0 popYears 1 popYears 2 popYears 3 popYears 4 popYears 5 popYears 6 popYears 7 popYears 8 popYears 9 popYears10
1: Site 1        1.1         10       11.0      12.10     13.310    14.6410   16.10510   17.71561   19.48717   21.43589   23.57948   25.93742
2: Site 2        1.2         12       14.4      17.28     20.736    24.8832   29.85984   35.83181   42.99817   51.59780   61.91736   74.30084
3: Site 3        1.3         13       16.9      21.97     28.561    37.1293   48.26809   62.74852   81.57307  106.04499  137.85849  179.21604
</code>```

Explanation

First, the parameters are  expanded to cover 11 years (including year 0) using the cross join function CJ() and a subsequent right join on Site:

```<code>params[CJ(Site = Site, Year = 0:nYears), on = "Site"]
</code>```

```<code>       Site growthRate pop Year
 1: Site 1        1.1  10    0
 2: Site 1        1.1  10    1
 3: Site 1        1.1  10    2
 4: Site 1        1.1  10    3
 5: Site 1        1.1  10    4
 6: Site 1        1.1  10    5
 7: Site 1        1.1  10    6
 8: Site 1        1.1  10    7
 9: Site 1        1.1  10    8
10: Site 1        1.1  10    9
11: Site 1        1.1  10   10
12: Site 2        1.2  12    0
13: Site 2        1.2  12    1
14: Site 2        1.2  12    2
15: Site 2        1.2  12    3
16: Site 2        1.2  12    4
17: Site 2        1.2  12    5
18: Site 2        1.2  12    6
19: Site 2        1.2  12    7
20: Site 2        1.2  12    8
21: Site 2        1.2  12    9
22: Site 2        1.2  12   10
23: Site 3        1.3  13    0
24: Site 3        1.3  13    1
25: Site 3        1.3  13    2
26: Site 3        1.3  13    3
27: Site 3        1.3  13    4
28: Site 3        1.3  13    5
29: Site 3        1.3  13    6
30: Site 3        1.3  13    7
31: Site 3        1.3  13    8
32: Site 3        1.3  13    9
33: Site 3        1.3  13   10
      Site growthRate pop Year
</code>```

Then the growth is computed from the shifted growth rates using the cumulative product function cumprod() separately for each Site. The shift is required to skip the initial year for each Site. Then the population is computed by multiplying with the intial population.

Finally, the data.table is reshaped from long to wide format using dcast(). The column headers are created on-the-fly using sprintf() to ensure the correct order of columns.

Title: Using := in data.table with paste()

Body:
I have started using data.table for a large population model. So far, I have been impressed because using the data.table structure decreases my simulation run times by about 30%. I am trying to further optimize my code and have included a simplified example. My two questions are:

Is is possible to use the := operator with this code?

Would using the := operator be quicker (although, if I am able to answer my first question, I should be able to answer my question 2!)?

I am using R version 3.1.2 on a machine running Windows 7 with data.table version 1.9.4.

Here is my reproducible example:

library(data.table)

## Create  example table and set initial conditions
nYears = 10
exampleTable = data.table(Site = paste("Site", 1:3))
exampleTable[ , growthRate := c(1.1, 1.2, 1.3), ]
exampleTable[ , c(paste("popYears", 0:nYears, sep = "")) := 0, ]

exampleTable[ , "popYears0" := c(10, 12, 13)] # set the initial population size

for(yearIndex in 0:(nYears - 1)){
    exampleTable[[paste("popYears", yearIndex + 1, sep = "")]] <-
    exampleTable[[paste("popYears", yearIndex, sep = "")]] *
    exampleTable[, growthRate]
}

I am trying to do something like:

for(yearIndex in 0:(nYears - 1)){
    exampleTable[ , paste("popYears", yearIndex + 1, sep = "") :=
    paste("popYears", yearIndex, sep = "") * growthRate, ]
}

However, this does not work because the paste does not work with the data.table, for example:

exampleTable[ , paste("popYears", yearIndex + 1, sep = "")]
# [1] "popYears10"

I have looked through the data.table documentation. Section 2.9 of the FAQ uses cat, but this produces a null output.

exampleTable[ , cat(paste("popYears", yearIndex + 1, sep = ""))]
# [1] popYears10NULL

Also, I tried searching Google and rseek.org, but didn't find anything. If am missing an obvious search term, I would appreciate a search tip. I have always found searching for R operators to be hard because search engines don't like symbols (e.g., ":=") and "R" can be vague.

Body:
Struggling with column names is a strong indicator that the wide format is probably not the best choice for the given problem. Therefore, I suggest to do the computations in long form and to reshape the result from long to wide format, finally.

nYears = 10
params = data.table(Site = paste("Site", 1:3),
                    growthRate = c(1.1, 1.2, 1.3),
                    pop = c(10, 12, 13))
long <- params[CJ(Site = Site, Year = 0:nYears), on = "Site"][
  , growth := cumprod(shift(growthRate, fill = 1)), by = Site][
    , pop := pop * growth][]
dcast(long, Site + growthRate ~ sprintf("popYears%02i", Year), value.var = "pop")

     Site growthRate popYears 0 popYears 1 popYears 2 popYears 3 popYears 4 popYears 5 popYears 6 popYears 7 popYears 8 popYears 9 popYears10
1: Site 1        1.1         10       11.0      12.10     13.310    14.6410   16.10510   17.71561   19.48717   21.43589   23.57948   25.93742
2: Site 2        1.2         12       14.4      17.28     20.736    24.8832   29.85984   35.83181   42.99817   51.59780   61.91736   74.30084
3: Site 3        1.3         13       16.9      21.97     28.561    37.1293   48.26809   62.74852   81.57307  106.04499  137.85849  179.21604

Explanation

First, the parameters are  expanded to cover 11 years (including year 0) using the cross join function CJ() and a subsequent right join on Site:

params[CJ(Site = Site, Year = 0:nYears), on = "Site"]

       Site growthRate pop Year
 1: Site 1        1.1  10    0
 2: Site 1        1.1  10    1
 3: Site 1        1.1  10    2
 4: Site 1        1.1  10    3
 5: Site 1        1.1  10    4
 6: Site 1        1.1  10    5
 7: Site 1        1.1  10    6
 8: Site 1        1.1  10    7
 9: Site 1        1.1  10    8
10: Site 1        1.1  10    9
11: Site 1        1.1  10   10
12: Site 2        1.2  12    0
13: Site 2        1.2  12    1
14: Site 2        1.2  12    2
15: Site 2        1.2  12    3
16: Site 2        1.2  12    4
17: Site 2        1.2  12    5
18: Site 2        1.2  12    6
19: Site 2        1.2  12    7
20: Site 2        1.2  12    8
21: Site 2        1.2  12    9
22: Site 2        1.2  12   10
23: Site 3        1.3  13    0
24: Site 3        1.3  13    1
25: Site 3        1.3  13    2
26: Site 3        1.3  13    3
27: Site 3        1.3  13    4
28: Site 3        1.3  13    5
29: Site 3        1.3  13    6
30: Site 3        1.3  13    7
31: Site 3        1.3  13    8
32: Site 3        1.3  13    9
33: Site 3        1.3  13   10
      Site growthRate pop Year

Then the growth is computed from the shifted growth rates using the cumulative product function cumprod() separately for each Site. The shift is required to skip the initial year for each Site. Then the population is computed by multiplying with the intial population.

Finally, the data.table is reshaped from long to wide format using dcast(). The column headers are created on-the-fly using sprintf() to ensure the correct order of columns.


问:
updating enabled-status of QAction
When Delphi introduced actions some years ago now, one of the great advantages was that the status (enabled/disabled) of the action was handled in the event loop, rather than that the programmer had to think about updating these states concommittant to all status changes of the application. For example:

procedure TMyForm.SaveActionUpdate(Sender: TObject)
begin
    (sender as TAction).enabled := self.contentHasChanged();
end;

instead of

procedure TMyForm.onContentChanging(sender: TObject)
begin
    SaveAction.enabled := True;
    SaveAsAction.enabled := True;
    RevertAction ... etc.
end;

Now I am trying to rebuild some of these old Delphi programs in Python using Qt, but so far I have failed to figure out how to enable QActions without resorting to explicitly setting it enabled whenever my content changes. What would be a fruitful approach to do this?

答:
In C++:</p>

```<code>void MyForm::onSaveActionUpdateSlot() // must be a slot
{
    QAction* pAction = qobject_cast<QAction*>( sender() );
    if (pAction)  // if sent by QAction
       pAction->setEnbaled( this->contentHasChanged() );
}
</code>```

Title: updating enabled-status of QAction

Body:
In C++:

void MyForm::onSaveActionUpdateSlot() // must be a slot
{
    QAction* pAction = qobject_cast<QAction*>( sender() );
    if (pAction)  // if sent by QAction
       pAction->setEnbaled( this->contentHasChanged() );
}


问:
How do we specify maven dependencies in pyspark
While starting spark-submit / pyspark, we do have an option of specifying the jar files using the --jars option. How can we specify maven dependencies in pyspark. Do we have to pass all the jars all the time when running a pyspark application or there is a cleaner way ?

答:
According to https://spark.apache.org/docs/latest/submitting-applications.html there is an option to specify --packages in the form of a comma-delimited list of Maven coordinates.

```<code>./bin/spark-submit --packages my:awesome:package
</code>```

Body:
According to https://spark.apache.org/docs/latest/submitting-applications.html there is an option to specify --packages in the form of a comma-delimited list of Maven coordinates.

./bin/spark-submit --packages my:awesome:package


问:
Ionic Storage get not setting a public var
I am trying to set the token i have stored in the storage module of Ionic, to a public variable so i can call it later in the file, however when i try and set it and then call the variable from a different function i get a undefined error

code

```<code>import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Component, Injectable} from '@angular/core';
import { Storage } from "@ionic/storage";
import 'rxjs/add/operator/map';

@Injectable()
@Component({
 providers: [HttpClient]
})
export class DataProvider {
 public token:string;

constructor(public http: HttpClient, public storage: Storage) {
}

 authToken(){
  console.log('token function')
  this.storage.get('token').then((val) => {
   this.token = val;
   console.log(this.token);
  });
 }

 getsomething(){
  let headers = new HttpHeaders();
  headers = headers.set('Content-Type', 'application/json');
  this.authToken();
  console.log(this.token);
 }

}
</code>```

答:
It will be because the token is being read from storage using a promise, so when read in authToken the promise has resolved, but in getsomething you are trying to log the token before it has been set in the promise.

To be sure you have the token in getsomething you will need to return the promise from authToken

```<code>authToken(){
  console.log('token function')
  return this.storage.get('token').then((val) => {
   this.token = val;
   console.log(this.token);
  });
 }

getsomething(){
  let headers = new HttpHeaders();
  headers = headers.set('Content-Type', 'application/json');
  this.authToken().then(() => {
    console.log(this.token);
  })
 }
</code>```

Body:
I am trying to set the token i have stored in the storage module of Ionic, to a public variable so i can call it later in the file, however when i try and set it and then call the variable from a different function i get a undefined error

code

import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Component, Injectable} from '@angular/core';
import { Storage } from "@ionic/storage";
import 'rxjs/add/operator/map';

@Injectable()
@Component({
 providers: [HttpClient]
})
export class DataProvider {
 public token:string;

constructor(public http: HttpClient, public storage: Storage) {
}

 authToken(){
  console.log('token function')
  this.storage.get('token').then((val) => {
   this.token = val;
   console.log(this.token);
  });
 }

 getsomething(){
  let headers = new HttpHeaders();
  headers = headers.set('Content-Type', 'application/json');
  this.authToken();
  console.log(this.token);
 }

}

Body:
It will be because the token is being read from storage using a promise, so when read in authToken the promise has resolved, but in getsomething you are trying to log the token before it has been set in the promise.

To be sure you have the token in getsomething you will need to return the promise from authToken

authToken(){
  console.log('token function')
  return this.storage.get('token').then((val) => {
   this.token = val;
   console.log(this.token);
  });
 }

getsomething(){
  let headers = new HttpHeaders();
  headers = headers.set('Content-Type', 'application/json');
  this.authToken().then(() => {
    console.log(this.token);
  })
 }


问:
jQuery : Find prev element from current element
How to get a prev element from current element Like this.

```<code><p class='target'>Target</p>

<ol>
  <li>start</li>
  <ul>
    <li class='start'>mid</li>
  </ul>
</ol>
</code>```

For now, I'm in the start element.And I want to find the target element.

I try the below code to do this.

```<code> $('.start').prev('.target');
</code>```

But it didn't get the target DOM.

How can I do this?Any advice.

Update ::

My scenario is a bit complicated.

```<code>  <p>
  <ins>asdf</ins>
  </p>

<div>div (great-grandparent)
  <ul>
     <li><del>(second ancestor - second grandparent)</del></li>
     <ul>
       <li>
         <span>span</span>
       </li>
     </ul>
   </ul>
</div>
</code>```

Just assume I'm in the span and I try to find the "DEL and INS"
tags.What am I going to do?

And I try the below one.But it's not working.

```<code>$('span').closest('del');
$('span').closest('ins');
</code>```

And the structure of the HTML is changing every time.That's why I'm afraid of.

答:
 console.log($(".start").closest( "ol" ).prev().html())```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='target'>Target</p>
<ol>
  <li>start</li>
  <ul>
    <li class='start'>mid</li>
  </ul>
</ol></code>```

Body:
How to get a prev element from current element Like this.

Target

start

mid

For now, I'm in the start element.And I want to find the target element.

I try the below code to do this.

 $('.start').prev('.target');

But it didn't get the target DOM.

How can I do this?Any advice.

Update ::

My scenario is a bit complicated.

  asdf

div (great-grandparent)

(second ancestor - second grandparent)

         span

Just assume I'm in the span and I try to find the "DEL and INS"
tags.What am I going to do?

And I try the below one.But it's not working.

$('span').closest('del');
$('span').closest('ins');

And the structure of the HTML is changing every time.That's why I'm afraid of.

Body:
 console.log($(".start").closest( "ol" ).prev().html())

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='target'>Target</p>
<ol>
  <li>start</li>
  <ul>
    <li class='start'>mid</li>
  </ul>
</ol>


问:
CG change/saving context when drawing a subpath
If I am doing a simple drawing, and I want to change the line width/dash of certain sub paths, how can I achieve this without changing all the paths?  I have tried a few variations using CGContextSaveGState(context); but can't quite get it right.  Do this have to be totally different paths?  I really want them to not look painted over with shadows.</p>

```<code>- (void)drawPitch:(CGContextRef)context {

    // Push the context onto the stack
    UIGraphicsPushContext(context);

    //Reasonable defaults
    CGRect          pitchRect = CGRectMake(10, 10, 220, 344);
    CGSize          myShadowOffset = CGSizeMake(0,1);
    float           myColorValues[] = {0, 0, 0, 0.75};
    CGColorRef      myColor;
    CGColorSpaceRef myColorSpace;

    //Color Space
    myColorSpace = CGColorSpaceCreateDeviceRGB ();
    myColor = CGColorCreate (myColorSpace, myColorValues);

    // Set Stroke
    CGContextSetRGBStrokeColor(context, 1, 1, 1, 0.9);

    CGContextSetLineWidth(context, 4);

    // Pitch Outline at width:4
    CGContextAddRect(context, pitchRect);

    CGContextSaveGState(context);

    // Want this to be set width:2 just for the subpath
    CGContextSetLineWidth(context, 2);

    CGContextMoveToPoint(context, CGRectGetMinX(pitchRect), CGRectGetMinY(pitchRect) + (pitchRect.size.height * 0.50));
    CGContextAddLineToPoint(context, CGRectGetMaxX(pitchRect), CGRectGetMinY(pitchRect) + (pitchRect.size.height * 0.50));

    CGContextRestoreGState(context);

    // Set Line Shadow
    CGContextSetShadowWithColor(context, myShadowOffset, 10, myColor);

    // Stroke path
    CGContextStrokePath(context);

    // Pop the contect back on the stack
    UIGraphicsPopContext();
}
</code>```

答: The call to CGContextSetLineWidth() only affects the call to CGContextStrokePath(). A path only contains the coordinates and types of each segment, and does not contain information about line width or pattern or anything else. If you need to draw each segment with a different line width, then you need to use separate calls to CGContextStrokePath() with separate paths.

ContentLicense: CC BY-SA 2.5

Body:
If I am doing a simple drawing, and I want to change the line width/dash of certain sub paths, how can I achieve this without changing all the paths?  I have tried a few variations using CGContextSaveGState(context); but can't quite get it right.  Do this have to be totally different paths?  I really want them to not look painted over with shadows.

- (void)drawPitch:(CGContextRef)context {

    // Push the context onto the stack
    UIGraphicsPushContext(context);

    //Reasonable defaults
    CGRect          pitchRect = CGRectMake(10, 10, 220, 344);
    CGSize          myShadowOffset = CGSizeMake(0,1);
    float           myColorValues[] = {0, 0, 0, 0.75};
    CGColorRef      myColor;
    CGColorSpaceRef myColorSpace;

    //Color Space
    myColorSpace = CGColorSpaceCreateDeviceRGB ();
    myColor = CGColorCreate (myColorSpace, myColorValues);

    // Set Stroke
    CGContextSetRGBStrokeColor(context, 1, 1, 1, 0.9);

    CGContextSetLineWidth(context, 4);

    // Pitch Outline at width:4
    CGContextAddRect(context, pitchRect);

    CGContextSaveGState(context);

    // Want this to be set width:2 just for the subpath
    CGContextSetLineWidth(context, 2);

    CGContextMoveToPoint(context, CGRectGetMinX(pitchRect), CGRectGetMinY(pitchRect) + (pitchRect.size.height * 0.50));
    CGContextAddLineToPoint(context, CGRectGetMaxX(pitchRect), CGRectGetMinY(pitchRect) + (pitchRect.size.height * 0.50));

    CGContextRestoreGState(context);

    // Set Line Shadow
    CGContextSetShadowWithColor(context, myShadowOffset, 10, myColor);

    // Stroke path
    CGContextStrokePath(context);

    // Pop the contect back on the stack
    UIGraphicsPopContext();
}


问:
Lags data on Pandas dataframes
I'm using sklearn to make a forecast. Usually i will create lagged data to forecasting, this is easy if the feature only consist 1 column.

for example:

```<code>index  temperature
1      100
2      80
3      50
4      90
5      110
</code>```

Usually i will create another column with shifting the temperature value to create lagged data using function like:

```<code>dataframe.temperature.shift()
</code>```

So my dataframe become:

```<code>index  temperature temperature2 temperature3
1      100         NaN          NaN
2      80          100          NaN
3      50          80           100
4      90          50           80
5      110         90           50
</code>```

Then when i want to forecast, i can fit using code like:

```<code>x = dataframe.loc[:,('temperature3','temperature2')]
y = dataframe.temperature
model.fit([x],y)
</code>```

The problem is when i have a lot of column to create lag data, and need more lagged data for each column, my dataframe will be too big.

Is there any simple approach that i can use? Thanks!

For reference, this is my dataframe:

```<code>import pandas as pd
import talib

df = pd.read_csv('..\\data\\uj5.CSV', names=['date','time','open','high','low','close','volume'])
df.index = pd.to_datetime(df.date + df.time,format='%Y.%m.%d%H:%M')

# assuming this is the 'X', let say i need 100 lags of these column to predict the 'Y'
df['CDLBELTHOLD'] = talib.CDLBELTHOLD(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLCLOSINGMARUBOZU'] = talib.CDLCLOSINGMARUBOZU(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLDOJI'] = talib.CDLDOJI(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLHIKKAKE'] = talib.CDLHIKKAKE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLLONGLEGGEDDOJI'] = talib.CDLLONGLEGGEDDOJI(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLLONGLINE'] = talib.  CDLLONGLINE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLSHORTLINE'] = talib.CDLSHORTLINE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLSPINNINGTOP'] = talib.CDLSPINNINGTOP(df.open.values, df.high.values, df.low.values, df.close.values)
df['atr'] = talib.ATR(df.high.values, df.low.values, df.close.values,timeperiod=14)

#assuming this is the Y
df['target'] = #some int value
</code>```

答:
I wouldn't use pandas here if you end up with a large matrix . Numpy is more appropriate here:

```<code>import numpy as np

x = you_data_frame.values
max_lag = 10 # number of lags you want to have

m = np.array([])
for i in np.arange(len(x) - max_lag):
    new_row = x[i:i+max_lag][None, :]
    if len(m) == 0:
        m = new_row
    else:
        m = np.vstack([m, new_row])
</code>```

then you cat fit your data using

```<code>model.fit(m[:, 1:], m[:, 0])
</code>```

Title: Lags data on Pandas dataframes

Body:
I'm using sklearn to make a forecast. Usually i will create lagged data to forecasting, this is easy if the feature only consist 1 column.

for example:

index  temperature
1      100
2      80
3      50
4      90
5      110

Usually i will create another column with shifting the temperature value to create lagged data using function like:

dataframe.temperature.shift()

So my dataframe become:

index  temperature temperature2 temperature3
1      100         NaN          NaN
2      80          100          NaN
3      50          80           100
4      90          50           80
5      110         90           50

Then when i want to forecast, i can fit using code like:

x = dataframe.loc[:,('temperature3','temperature2')]
y = dataframe.temperature
model.fit([x],y)

The problem is when i have a lot of column to create lag data, and need more lagged data for each column, my dataframe will be too big.

Is there any simple approach that i can use? Thanks!

For reference, this is my dataframe:

import pandas as pd
import talib

df = pd.read_csv('..\\data\\uj5.CSV', names=['date','time','open','high','low','close','volume'])
df.index = pd.to_datetime(df.date + df.time,format='%Y.%m.%d%H:%M')

# assuming this is the 'X', let say i need 100 lags of these column to predict the 'Y'
df['CDLBELTHOLD'] = talib.CDLBELTHOLD(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLCLOSINGMARUBOZU'] = talib.CDLCLOSINGMARUBOZU(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLDOJI'] = talib.CDLDOJI(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLHIKKAKE'] = talib.CDLHIKKAKE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLLONGLEGGEDDOJI'] = talib.CDLLONGLEGGEDDOJI(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLLONGLINE'] = talib.  CDLLONGLINE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLSHORTLINE'] = talib.CDLSHORTLINE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLSPINNINGTOP'] = talib.CDLSPINNINGTOP(df.open.values, df.high.values, df.low.values, df.close.values)
df['atr'] = talib.ATR(df.high.values, df.low.values, df.close.values,timeperiod=14)

#assuming this is the Y
df['target'] = #some int value

Body:
I wouldn't use pandas here if you end up with a large matrix . Numpy is more appropriate here:

import numpy as np

x = you_data_frame.values
max_lag = 10 # number of lags you want to have

m = np.array([])
for i in np.arange(len(x) - max_lag):
    new_row = x[i:i+max_lag][None, :]
    if len(m) == 0:
        m = new_row
    else:
        m = np.vstack([m, new_row])

then you cat fit your data using

model.fit(m[:, 1:], m[:, 0])


问:
Maven scope provided and transitive dependencies
I have a dependency with one of the jar and i have marked it as provided in pom xml. It seems only some of the transitive dependency jar are marked as provided and not packaged with the war but others are still scope as compile and  packaged with war libs.Do i need to explicitly mark the scope as provided for all the transitive dependencies.

Dependency in pom xml:

```<code><dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <scope>provided</scope>
</dependency>
</code>```

Dependency tree:

```<code>[INFO] +- org.apache.camel:camel-ftp:jar:2.17.0.redhat-630262:provided
[INFO] |  +- com.jcraft:jsch:jar:0.1.54:provided
[INFO] |  +- commons-net:commons-net:jar:3.3.0.redhat-3:provided
[INFO] |  +- com.sun.xml.bind:jaxb-core:jar:2.2.11:compile
[INFO] |  \- com.sun.xml.bind:jaxb-impl:jar:2.2.11.redhat-2:compile
[INFO] +- org.apache.camel:camel-csv:jar:2.17.0.redhat-630262:provided
</code>```

plugin version Details:

```<code><maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <cdi.api.version>1.2.0.redhat-2</cdi.api.version>
        <javax.inject.version>1.0.0.redhat-6</javax.inject.version>
        <sonar.host.url>http://vfrde2srta0401.agcs.biz:9000</sonar.host.url>
        <xerces.version>2.11.0-22</xerces.version>
        <xmlunit.version>1.6</xmlunit.version>
        <maven.compilerplugin.version>3.7.0</maven.compilerplugin.version>
        <maven.releaseplugin.version>2.5.3</maven.releaseplugin.version>
        <maven.warplugin.version>3.2.0</maven.warplugin.version>
        <maven.jarplugin.version>3.0.2</maven.jarplugin.version>
        <maven.surefireplugin.version>2.20.1</maven.surefireplugin.version>
        <maven.coberturaplugin.version>2.7</maven.coberturaplugin.version>
</code>```

答:
Transitive dependencies scope set based on defined scope. Refer to Introduction to the Dependency Mechanism. You could verify this through changing scope and then verifying dependency tree (mvn dependency:tree).

```<code> <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <scope>provided</scope>
            <version>2.12.2</version>
   </dependency>

INFO] \- org.apache.camel:camel-ftp:jar:2.12.2:provided
[INFO]    +- org.apache.camel:camel-core:jar:2.12.2:provided
[INFO]    +- com.jcraft:jsch:jar:0.1.49:provided
[INFO]    \- commons-net:commons-net:jar:3.3:provided
</code>```

```<code><dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <!-- <scope>provided</scope> -->
            <version>2.12.2</version>
 </dependency>

 [INFO] \- org.apache.camel:camel-ftp:jar:2.12.2:compile
[INFO]    +- org.apache.camel:camel-core:jar:2.12.2:compile
[INFO]    +- com.jcraft:jsch:jar:0.1.49:compile
[INFO]    \- commons-net:commons-net:jar:3.3:compile
</code>```

```<code> <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <scope>runtime</scope>
            <version>2.12.2</version>
 </dependency>

\- org.apache.camel:camel-ftp:jar:2.12.2:runtime
[INFO]    +- org.apache.camel:camel-core:jar:2.12.2:runtime
[INFO]    +- com.jcraft:jsch:jar:0.1.49:runtime
[INFO]    \- commons-net:commons-net:jar:3.3:runtime
</code>```

```<code> <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <scope>test</scope>
            <version>2.12.2</version>
  </dependency>

[INFO] \- org.apache.camel:camel-ftp:jar:2.12.2:test
[INFO]    +- org.apache.camel:camel-core:jar:2.12.2:test
[INFO]    +- com.jcraft:jsch:jar:0.1.49:test
[INFO]    \- commons-net:commons-net:jar:3.3:test
</code>```

Body:
I have a dependency with one of the jar and i have marked it as provided in pom xml. It seems only some of the transitive dependency jar are marked as provided and not packaged with the war but others are still scope as compile and  packaged with war libs.Do i need to explicitly mark the scope as provided for all the transitive dependencies.

Dependency in pom xml:

<dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <scope>provided</scope>
</dependency>

Dependency tree:

[INFO] +- org.apache.camel:camel-ftp:jar:2.17.0.redhat-630262:provided
[INFO] |  +- com.jcraft:jsch:jar:0.1.54:provided
[INFO] |  +- commons-net:commons-net:jar:3.3.0.redhat-3:provided
[INFO] |  +- com.sun.xml.bind:jaxb-core:jar:2.2.11:compile
[INFO] |  \- com.sun.xml.bind:jaxb-impl:jar:2.2.11.redhat-2:compile
[INFO] +- org.apache.camel:camel-csv:jar:2.17.0.redhat-630262:provided

plugin version Details:

<maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <cdi.api.version>1.2.0.redhat-2</cdi.api.version>
        <javax.inject.version>1.0.0.redhat-6</javax.inject.version>
        <sonar.host.url>http://vfrde2srta0401.agcs.biz:9000</sonar.host.url>
        <xerces.version>2.11.0-22</xerces.version>
        <xmlunit.version>1.6</xmlunit.version>
        <maven.compilerplugin.version>3.7.0</maven.compilerplugin.version>
        <maven.releaseplugin.version>2.5.3</maven.releaseplugin.version>
        <maven.warplugin.version>3.2.0</maven.warplugin.version>
        <maven.jarplugin.version>3.0.2</maven.jarplugin.version>
        <maven.surefireplugin.version>2.20.1</maven.surefireplugin.version>
        <maven.coberturaplugin.version>2.7</maven.coberturaplugin.version>

Body:
Transitive dependencies scope set based on defined scope. Refer to Introduction to the Dependency Mechanism. You could verify this through changing scope and then verifying dependency tree (mvn dependency:tree).

 <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <scope>provided</scope>
            <version>2.12.2</version>
   </dependency>

INFO] \- org.apache.camel:camel-ftp:jar:2.12.2:provided
[INFO]    +- org.apache.camel:camel-core:jar:2.12.2:provided
[INFO]    +- com.jcraft:jsch:jar:0.1.49:provided
[INFO]    \- commons-net:commons-net:jar:3.3:provided

<dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <!-- <scope>provided</scope> -->
            <version>2.12.2</version>
 </dependency>

 [INFO] \- org.apache.camel:camel-ftp:jar:2.12.2:compile
[INFO]    +- org.apache.camel:camel-core:jar:2.12.2:compile
[INFO]    +- com.jcraft:jsch:jar:0.1.49:compile
[INFO]    \- commons-net:commons-net:jar:3.3:compile

 <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <scope>runtime</scope>
            <version>2.12.2</version>
 </dependency>

\- org.apache.camel:camel-ftp:jar:2.12.2:runtime
[INFO]    +- org.apache.camel:camel-core:jar:2.12.2:runtime
[INFO]    +- com.jcraft:jsch:jar:0.1.49:runtime
[INFO]    \- commons-net:commons-net:jar:3.3:runtime

 <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <scope>test</scope>
            <version>2.12.2</version>
  </dependency>

[INFO] \- org.apache.camel:camel-ftp:jar:2.12.2:test
[INFO]    +- org.apache.camel:camel-core:jar:2.12.2:test
[INFO]    +- com.jcraft:jsch:jar:0.1.49:test
[INFO]    \- commons-net:commons-net:jar:3.3:test

ContentLicense: CC BY-SA 4.0


问:
What determines autoselect for <select>?
I have a <select> tag with various options, and I would like to know what determines what happens when the user starts typing.

Say I have a list like the following:

```<code><select id="userlist">
<option value="nothing" selected="selected"></option>
<option value="AdamT">Adam T</option>
<option value="AidanC">Aidan C</option>
<option value="IanQ">Ian Q</option>
<option value="JamesR">James R</option>
</select>
</code>```

Sometimes if I type A followed by I, I end up with Aidan C selected.

Other times, if I type just fractionally slower, I end up with Ian Q selected.

What determines what ends up being selected, and at what speed of typing? Is it browser-specific, or is it set in the HTML spec?

答: The < select  > is setup so that it performs a new autocomplete in about 1000 milisecond intervals between key presses. If you keep typing before the timer is up, it will continue the autocomplete with your current prefix. However, if you wait a second between key presses, it will start a new prefix, forgetting what you previously typed.</p>

Body:
I have a <select> tag with various options, and I would like to know what determines what happens when the user starts typing.

Say I have a list like the following:

<select id="userlist">
<option value="nothing" selected="selected"></option>
<option value="AdamT">Adam T</option>
<option value="AidanC">Aidan C</option>
<option value="IanQ">Ian Q</option>
<option value="JamesR">James R</option>
</select>

Sometimes if I type A followed by I, I end up with Aidan C selected.

Other times, if I type just fractionally slower, I end up with Ian Q selected.

What determines what ends up being selected, and at what speed of typing? Is it browser-specific, or is it set in the HTML spec?


问:
How to make string to json with javascript? (like A//a1,A//a2,A//a3//a31 ..)
How to convert a string to JSON with javascript or jQuery? I've been thinking all day, but I do not get a good idea.

This task is to dynamically create the treeview in the client side (ASP.Net). My idea is to convert the string to an object and convert to JSON type. (String -> object -> JSON) I tried, but the day is gone. It is difficult to construct 2 more depth like A->a3->a31.

String is

```<code>var sString = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";
</code>```

and JSON format is

{
  "title": "A",
  "key": "1",
  "folder": true,
  "children": [{
      "title": "a1",
      "key": "2"
    }, {
      "title": "a2",
      "key": "3"
    }, {
      "title": "a3",
      "key": "4",
      "folder": true,
      "children": [{
          "title": "a31",
          "key": "5"
        }...
      }]
  }```

(This is fancytreeview plugin)

‘//‘ is depth and ‘,’ is split.

Please help me..

Edit)
I want to turn ‘sString’ to JSON format.. but It’s ok just JSON type string.

Please understand that my sentence is strange because my native language is not English.

Edit2)
oh.. I want to convert the string to an object and then convert it back to JSON format. I do not have the confidence to convert that string into JSON format right away. Because there are more than 8000 variants. If It’s can, let me know how.

答:
```<code>var key = 1; // keys start at 1

let addPaths = (root, paths) => {

    if (!paths || paths.length == 0)
        return;

    let path = paths.shift();

    //add nodes for the current path
    addNodes(root, path.split('//'));

    // keep going until all paths have been processed
    addPaths(root, paths);
};

let addNodes = (root, nodeList) => {

    if (!nodeList || nodeList.length == 0)
        return;

    let title = nodeList.shift();

    // find node under root with matching title
    let isRootNode = Array.isArray(root);

    node = (isRootNode ? root : root.children || []).find((node) => {
        return node.title == title;
    });

    if (!node){
        node = {
            title: title,
            key: key++
        }

        // are we at root of object?
        if (isRootNode)
            root.push(node);
        else
        {
            if (!root.children)
                root.children = [];

            root.children.push(node);
            root.folder = true;
        }
    }

    addNodes(node, nodeList);
};

let parse = (string) => {
    let object = [];

    let nodes = string.split(',');

    addPaths(object, nodes);

    return object
};
</code>```

console.log(JSON.stringify(parse("A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2"), null, 2));

Which results in:

```<code>[
  {
    "title": "A",
    "key": 1,
    "children": [
      {
        "title": "a1",
        "key": 2
      },
      {
        "title": "a2",
        "key": 3
      },
      {
        "title": "a3",
        "key": 4,
        "children": [
          {
            "title": "a31",
            "key": 5
          },
          {
            "title": "a32",
            "key": 6
          }
        ],
        "folder": true
      }
    ],
    "folder": true
  },
  {
    "title": "B",
    "key": 7
  },
  {
    "title": "C",
    "key": 8,
    "children": [
      {
        "title": "c1",
        "key": 9
      },
      {
        "title": "c2",
        "key": 10
      }
    ],
    "folder": true
  }
]
</code>```

Body:
How to convert a string to JSON with javascript or jQuery? I've been thinking all day, but I do not get a good idea.

This task is to dynamically create the treeview in the client side (ASP.Net). My idea is to convert the string to an object and convert to JSON type. (String -> object -> JSON) I tried, but the day is gone. It is difficult to construct 2 more depth like A->a3->a31.

String is

var sString = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";

and JSON format is

{
  "title": "A",
  "key": "1",
  "folder": true,
  "children": [{
      "title": "a1",
      "key": "2"
    }, {
      "title": "a2",
      "key": "3"
    }, {
      "title": "a3",
      "key": "4",
      "folder": true,
      "children": [{
          "title": "a31",
          "key": "5"
        }...
      }]
  }

(This is fancytreeview plugin)

‘//‘ is depth and ‘,’ is split.

Please help me..

Edit)
I want to turn ‘sString’ to JSON format.. but It’s ok just JSON type string.

Please understand that my sentence is strange because my native language is not English.

Edit2)
oh.. I want to convert the string to an object and then convert it back to JSON format. I do not have the confidence to convert that string into JSON format right away. Because there are more than 8000 variants. If It’s can, let me know how.

Body:
var key = 1; // keys start at 1

let addPaths = (root, paths) => {

    if (!paths || paths.length == 0)
        return;

    let path = paths.shift();

    //add nodes for the current path
    addNodes(root, path.split('//'));

    // keep going until all paths have been processed
    addPaths(root, paths);
};

let addNodes = (root, nodeList) => {

    if (!nodeList || nodeList.length == 0)
        return;

    let title = nodeList.shift();

    // find node under root with matching title
    let isRootNode = Array.isArray(root);

    node = (isRootNode ? root : root.children || []).find((node) => {
        return node.title == title;
    });

    if (!node){
        node = {
            title: title,
            key: key++
        }

        // are we at root of object?
        if (isRootNode)
            root.push(node);
        else
        {
            if (!root.children)
                root.children = [];

            root.children.push(node);
            root.folder = true;
        }
    }

    addNodes(node, nodeList);
};

let parse = (string) => {
    let object = [];

    let nodes = string.split(',');

    addPaths(object, nodes);

    return object
};

console.log(JSON.stringify(parse("A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2"), null, 2));

Which results in:

[
  {
    "title": "A",
    "key": 1,
    "children": [
      {
        "title": "a1",
        "key": 2
      },
      {
        "title": "a2",
        "key": 3
      },
      {
        "title": "a3",
        "key": 4,
        "children": [
          {
            "title": "a31",
            "key": 5
          },
          {
            "title": "a32",
            "key": 6
          }
        ],
        "folder": true
      }
    ],
    "folder": true
  },
  {
    "title": "B",
    "key": 7
  },
  {
    "title": "C",
    "key": 8,
    "children": [
      {
        "title": "c1",
        "key": 9
      },
      {
        "title": "c2",
        "key": 10
      }
    ],
    "folder": true
  }
]


问:
File Picker window not open in xamarin forms?
on Button click file picker window not open in xamarin forms-
I am using Xam.Plugin.FilePicker
Here is my button event code-</p>

```<code>async void FilePickerEvent(object sender, EventArgs e)
        {
            try
            {
                FileData filedata = new FileData();
                filedata = await CrossFilePicker.Current.PickFile();
                byte[] data = filedata.DataArray;
                string name = filedata.FileName;
                foreach(byte b in filedata.DataArray)
                {
                    string attachment = b.ToString();
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
        }
</code>```

答:
I tried this plugin on Android device and it works well. I installed the plugin in all projects and then added these permissions to AndroidManifest.xml file as it is in the documentation.

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Then in my MainPage.xaml I created a button

```<code><Button Text="Open File" Clicked="Button_Clicked" />
</code>```

And in my MainPage.xaml.cs created event

```<code>private async void Button_Clicked(object sender, EventArgs e)
{
    var file = await CrossFilePicker.Current.PickFile();
}
</code>```

I picked the file and retrieve the property FileName and DataArray without any problem.

There is a thread on xamarin forum or there is a issue list on their github.

Body:
on Button click file picker window not open in xamarin forms-
I am using Xam.Plugin.FilePicker
Here is my button event code-

async void FilePickerEvent(object sender, EventArgs e)
        {
            try
            {
                FileData filedata = new FileData();
                filedata = await CrossFilePicker.Current.PickFile();
                byte[] data = filedata.DataArray;
                string name = filedata.FileName;
                foreach(byte b in filedata.DataArray)
                {
                    string attachment = b.ToString();
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
        }

Body:
I tried this plugin on Android device and it works well. I installed the plugin in all projects and then added these permissions to AndroidManifest.xml file as it is in the documentation.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Then in my MainPage.xaml I created a button

<Button Text="Open File" Clicked="Button_Clicked" />

And in my MainPage.xaml.cs created event

private async void Button_Clicked(object sender, EventArgs e)
{
    var file = await CrossFilePicker.Current.PickFile();
}

I picked the file and retrieve the property FileName and DataArray without any problem.

There is a thread on xamarin forum or there is a issue list on their github.


问:
How to properly use JQuery and Bootstrap in latest Angular versions
Yes, this question may be repeated. But I just don't get this setup working in any way.

I tried prettty much everything:

Getting the libraries directly into the index.html through a CDN.

Installing them via NPM and then adding them to angular-cli.json script field.

Importing the modules directly into my components, both with aliased JQuery (import * as $ from 'jquery') and just plain import (import 'jquery').

I tried other setups, like doing the imports in the root component, importing these libraries in various locations... but I don't get this working.

Currently, I need to get working one Bootstrap modal, and one Datepicker component which also works with JQuery, but it's being impossible for me. Sometimes I get the '$ is undefined' and sometimes I get other errors.

So now, I will ask: which is the real solution for this problem in latest Angular versions? How should I make the imports?

Thank you!

EDIT: Current situation:

Added the dependencies to the angular-cli.json file:

"styles": [
        "styles.css",
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "../node_modules/font-awesome/css/font-awesome.css"
      ],
      "scripts": [
      "../node_modules/jquery/dist/jquery.min.js",
      "../node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
    ],

I try to call the .modal() function that bootstrap has to add to Jquery:

( $('#myModal')).modal({
  backdrop: true,
  focus: true,
  show: true
})

But it just throws...:

```<code>SegmentsComponent.html:15 ERROR ReferenceError: $ is not defined
    at SegmentsComponent.openModal (segments.component.ts:55)
    at Object.eval [as handleEvent] (SegmentsComponent.html:15)
    at handleEvent (core.js:13255)
    at callWithDebugContext (core.js:14740)
    at Object.debugHandleEvent [as handleEvent] (core.js:14327)
    at dispatchEvent (core.js:9704)
    at eval (core.js:10318)
    at HTMLAnchorElement.eval (platform-browser.js:2614)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4620)
</code>```

Any help?

答:
You need to install Jquery and bootstrap (popper for Bootstrap 4) with package managers or CDN. Your .angular-cli.json file must look like this:

```<code>"scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/popper.js/dist/umd/popper.js",
    "../node_modules/bootstrap/dist/js/bootstrap.js"
],
</code>```

Make sure these three files exist.

Body:
Yes, this question may be repeated. But I just don't get this setup working in any way.

I tried prettty much everything:

Getting the libraries directly into the index.html through a CDN.

Installing them via NPM and then adding them to angular-cli.json script field.

Importing the modules directly into my components, both with aliased JQuery (import * as $ from 'jquery') and just plain import (import 'jquery').

I tried other setups, like doing the imports in the root component, importing these libraries in various locations... but I don't get this working.

Currently, I need to get working one Bootstrap modal, and one Datepicker component which also works with JQuery, but it's being impossible for me. Sometimes I get the '$ is undefined' and sometimes I get other errors.

So now, I will ask: which is the real solution for this problem in latest Angular versions? How should I make the imports?

Thank you!

EDIT: Current situation:

Added the dependencies to the angular-cli.json file:

"styles": [
        "styles.css",
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "../node_modules/font-awesome/css/font-awesome.css"
      ],
      "scripts": [
      "../node_modules/jquery/dist/jquery.min.js",
      "../node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
    ],

I try to call the .modal() function that bootstrap has to add to Jquery:

( $('#myModal')).modal({
  backdrop: true,
  focus: true,
  show: true
})

But it just throws...:

SegmentsComponent.html:15 ERROR ReferenceError: $ is not defined
    at SegmentsComponent.openModal (segments.component.ts:55)
    at Object.eval [as handleEvent] (SegmentsComponent.html:15)
    at handleEvent (core.js:13255)
    at callWithDebugContext (core.js:14740)
    at Object.debugHandleEvent [as handleEvent] (core.js:14327)
    at dispatchEvent (core.js:9704)
    at eval (core.js:10318)
    at HTMLAnchorElement.eval (platform-browser.js:2614)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4620)

Any help?

Body:
You need to install Jquery and bootstrap (popper for Bootstrap 4) with package managers or CDN. Your .angular-cli.json file must look like this:

"scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/popper.js/dist/umd/popper.js",
    "../node_modules/bootstrap/dist/js/bootstrap.js"
],

Make sure these three files exist.


问:
MySQL JSON query on a subquery
I have a Table A

```<code>    id
    something
    jsonModel
</code>```

jsonModel could look like this

```<code>{
   "text":"foo",
   "subkey1":{
      "entity":{
         "name":"foo",
         "customId":"59d61ffcf5bcb11f250d73275a252b62624eac000180ab59"
      }
   }
}
</code>```

I'm trying to select a row from table A when a certain ID is contained in the the jsonModel.

I have tried this but it does not work saying I'm not allowed to use wildcards in the expression

```<code>SELECT
    *
FROM A
WHERE json_contains(jsonModel,'59d61ffcf5bcb11f250d73275a252b62624eac000180ab59', $**.customId)
</code>```

Is there a way to achieve this knowing that I do not know where in the model customId can be?

EDIT:

I ended up writing this which works but I don't know which solution between this or wchiquito is best

```<code>SELECT *
from A WHERE
JSON_CONTAINS(JSON_EXTRACT(jsonModel, '$**.customId'),  '"59d61ffcf5bcb11f250d73275a252b62624eac000180ab59"');
</code>```

答:
Even tough its not correct or best approach but it works,</p>

```<code>SELECT * from `A` where `jsonModel` like '%customId%59d61ffcf5bcb11f250d73275a252b62624eac000180ab59%'
</code>```

Title: MySQL JSON query on a subquery

Body:
I have a Table A

    id
    something
    jsonModel

jsonModel could look like this

{
   "text":"foo",
   "subkey1":{
      "entity":{
         "name":"foo",
         "customId":"59d61ffcf5bcb11f250d73275a252b62624eac000180ab59"
      }
   }
}

I'm trying to select a row from table A when a certain ID is contained in the the jsonModel.

I have tried this but it does not work saying I'm not allowed to use wildcards in the expression

SELECT
    *
FROM A
WHERE json_contains(jsonModel,'59d61ffcf5bcb11f250d73275a252b62624eac000180ab59', $**.customId)

Is there a way to achieve this knowing that I do not know where in the model customId can be?

EDIT:

I ended up writing this which works but I don't know which solution between this or wchiquito is best

SELECT *
from A WHERE
JSON_CONTAINS(JSON_EXTRACT(jsonModel, '$**.customId'),  '"59d61ffcf5bcb11f250d73275a252b62624eac000180ab59"');

Body:
Even tough its not correct or best approach but it works,

SELECT * from `A` where `jsonModel` like '%customId%59d61ffcf5bcb11f250d73275a252b62624eac000180ab59%'


问:
c# show/hide controls depending on user properties
In my application each user has one clientid but multiple roles.

For example user John has clientid=1 and roles=userx, userz

What I want to achieve is to hide or show controls of my application regarding the user's clientid and role

I have this array in my DB:

```<code>[dbo].[MyMenus](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [controlid] [nvarchar](500) NULL,
    [clientid_available] [nvarchar](50) NULL,
    [clientid_hidden] [nvarchar](50) NULL,
    [role_available] [nvarchar](500) NULL,
    [role_hidden] [nvarchar](500) NULL
</code>```

Where clientid_available, clientid_hidden, role_available, role_hidden contain values separated by comma. If a control has clientid_available then clientid_hidden is null and vice versa. Same thing for role_available and role_hidden

Example: 0 | Control1 | 0,1 | null | userx | null Which means that Control will be visible to users with clientid 0,1 and users in userx role

Here is my code until now:

```<code>var hiddenControls = from c in dc.MyMenus
                                 where c.clientid_hidden != null || c.role_hidden != null
                                 select c;

            var visibleControls = from c in dc.MyMenus
                                  where c.clientid_available != null || c.clientid_available != null
                                  select c;

foreach (var c in hiddenControls)
                {
                    if (c.clientid_hidden != null)
                    {
                        if (c.clientid_hidden.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }

foreach (var c in visibleControls)
                {
                    if (c.clientid_available != null)
                    {
                        if (c.clientid_available.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }
</code>```

But I dont know the logic for the role handling. Because role_available, role_hidden can have multiple values separated by ',' and current user can have multiple roles Roles.GetRolesForUser(HttpContext.Current.User.ToString())

答:
I'm not sure I totally understand the question, and it looks pretty horrible way to do it... But I think you're looking for:</p>

```<code>var userroles = Roles.GetRolesForUser(HttpContext.Current.User.ToString());
    if (c.role_available.Split(',').Any(cr => userroles.Any(ru => ru.RoleName== cr)))
                    {

                            (this.Page.FindControl(c.controlid)).Visible = true;
                    }
    else{
       (this.Page.FindControl(c.controlid)).Visible = false;
    }
</code>```

Body:
In my application each user has one clientid but multiple roles.

For example user John has clientid=1 and roles=userx, userz

What I want to achieve is to hide or show controls of my application regarding the user's clientid and role

I have this array in my DB:

[dbo].[MyMenus](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [controlid] [nvarchar](500) NULL,
    [clientid_available] [nvarchar](50) NULL,
    [clientid_hidden] [nvarchar](50) NULL,
    [role_available] [nvarchar](500) NULL,
    [role_hidden] [nvarchar](500) NULL

Where clientid_available, clientid_hidden, role_available, role_hidden contain values separated by comma. If a control has clientid_available then clientid_hidden is null and vice versa. Same thing for role_available and role_hidden

Example: 0 | Control1 | 0,1 | null | userx | null Which means that Control will be visible to users with clientid 0,1 and users in userx role

Here is my code until now:

var hiddenControls = from c in dc.MyMenus
                                 where c.clientid_hidden != null || c.role_hidden != null
                                 select c;

            var visibleControls = from c in dc.MyMenus
                                  where c.clientid_available != null || c.clientid_available != null
                                  select c;

foreach (var c in hiddenControls)
                {
                    if (c.clientid_hidden != null)
                    {
                        if (c.clientid_hidden.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }

foreach (var c in visibleControls)
                {
                    if (c.clientid_available != null)
                    {
                        if (c.clientid_available.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }

But I dont know the logic for the role handling. Because role_available, role_hidden can have multiple values separated by ',' and current user can have multiple roles Roles.GetRolesForUser(HttpContext.Current.User.ToString())

Body:
I'm not sure I totally understand the question, and it looks pretty horrible way to do it... But I think you're looking for:

var userroles = Roles.GetRolesForUser(HttpContext.Current.User.ToString());
    if (c.role_available.Split(',').Any(cr => userroles.Any(ru => ru.RoleName== cr)))
                    {

                            (this.Page.FindControl(c.controlid)).Visible = true;
                    }
    else{
       (this.Page.FindControl(c.controlid)).Visible = false;
    }


问:
Query to retreive data having Data = '1753/01/01'
I want to retrieve those records which have Data <= paramdate and also those records which have Date = '1753/01/01'

Thanks

答:
you could use DATEDIFF

DATEDIFF will return different time, day, month, pr year, based what you want to compare.
Example :

```<code>`DATEDIFF (DAY, '01/01/2017', '02/01/2017')`
</code>```

This will return 1, as the comparation is the day.
Note : datediff also could return negative value, as the position which is higher. Example :

```<code>'DATEDIFF (DAY, '02/01/2017', '01/01/2017')'
</code>```

will return -1

When you want to get the data that the date and the format are specified , you could use CONVERT to convert it to your formatted date and compare it like usual

Example :

```<code>WHERE CONVERT(VARCHAR, '2017/01/01', 103) = '01/01/2017'
</code>```

Body:
you could use DATEDIFF

DATEDIFF will return different time, day, month, pr year, based what you want to compare.
Example :

`DATEDIFF (DAY, '01/01/2017', '02/01/2017')`

This will return 1, as the comparation is the day.
Note : datediff also could return negative value, as the position which is higher. Example :

'DATEDIFF (DAY, '02/01/2017', '01/01/2017')'

will return -1

When you want to get the data that the date and the format are specified , you could use CONVERT to convert it to your formatted date and compare it like usual

Example :

WHERE CONVERT(VARCHAR, '2017/01/01', 103) = '01/01/2017'


问:
Automatically opening completion window in Eclipse
I am new to Eclipse and I want to know if it's possible to have the completion window open up automatically while I type (Visual Studio style) and not by clicking Ctrl + Space?

答:
It is possible. You can simply write: .abcdefghijklmnopqrstuvwxyz in Auto activation triggers for Java field, under Preferences > Java > Editor > Content Assist.

While writing Java code, after the dot . the window opens automatically after a configurable amount of time (default is 200 ms.)

In general, what you can do is add an auto activation trigger, for example _, so when you want the windows to popup, you type and delete that character (althought I don't think that's better than CTRL + SPACE).


问:
use a result from a query as a condition to another query
i have a query that return a single codeNumber
i want to use that code to as a where condtion in another query to return the name field

this is the query

```<code>select e1.SuperCODE
from (select EE.* from Table1 e , Table2 ee
where ee.CODE=e.CODE
and ee.TYPE_CODE=13
and E.ID=2089
order by E.FROM_DATE) e1
where  rownum = 1;
</code>```

the result from this query 490

i want to take this result
to put it in this query

```<code>select name from Table2 (the same table above)
where Table2.code= THE RESULT FROM ABOVE QUERY //490
</code>```

答:
Did you try just using = with a subquery:

```<code>select t2.*
from table2 t2
where t2.code = (select e1.SuperCODE
                 from (select ee.*
                       from Table1 e join
                            Table2 ee
                            on ee.CODE = e.CODE
                       where ee.TYPE_CODE = 13 and
                             e.ID = 2089
                       order by e.FROM_DATE
                      ) e1
                 where rownum = 1
                );
</code>```

Note the use of proper, explicit JOIN syntax.

Body:
i have a query that return a single codeNumber
i want to use that code to as a where condtion in another query to return the name field

this is the query

select e1.SuperCODE
from (select EE.* from Table1 e , Table2 ee
where ee.CODE=e.CODE
and ee.TYPE_CODE=13
and E.ID=2089
order by E.FROM_DATE) e1
where  rownum = 1;

the result from this query 490

i want to take this result
to put it in this query

select name from Table2 (the same table above)
where Table2.code= THE RESULT FROM ABOVE QUERY //490

Body:
Did you try just using = with a subquery:

select t2.*
from table2 t2
where t2.code = (select e1.SuperCODE
                 from (select ee.*
                       from Table1 e join
                            Table2 ee
                            on ee.CODE = e.CODE
                       where ee.TYPE_CODE = 13 and
                             e.ID = 2089
                       order by e.FROM_DATE
                      ) e1
                 where rownum = 1
                );

Note the use of proper, explicit JOIN syntax.


问:
Laravel: Query childless elements in a table
I have this simple table containing all categories:

Category:
id|name|parentid

Using Eloquent, how can I query all the categories that have no childs?

答:
You could do something like:

```<code>Category::whereNull('parent_id')->get();
</code>```

but it might be better setting up a 'children' relationship in the model and doing it using that:

Category.php

```<code>public function children()
{
    return $this->hasMany('App\Category', 'parent_id', 'id');
}
</code>```

Usage

```<code>Category::whereDoesntHave('children')->get();
</code>```

Body:
You could do something like:

Category::whereNull('parent_id')->get();

but it might be better setting up a 'children' relationship in the model and doing it using that:

Category.php

public function children()
{
    return $this->hasMany('App\Category', 'parent_id', 'id');
}

Usage

Category::whereDoesntHave('children')->get();


问:
Array method versus hashes
I have an object (returned from and API) that is either a hash or an array of hashes. I want to enclose it in an array if it is not already an array.

I tried to apply Array on it, which functions in an expected way with numbers or arrays:

```<code>Array(1) # => [1]
Array([1, 2]) # => [1, 2]
Array([{a: 1}, {b: 2}]) # => [{:a=>1}, {:b=>2}]
</code>```

but it fails with hashes:

```<code>Array({a: 1}) # => [[:a, 1]]
</code>```

which should be [{:a=>1}].

Alternatively, I could add a type check:

```<code>responses = [responses] if responses.is_a?(Hash)
</code>```

Is there a better solution?

答:
As @mudasobwa suggested, [responses].flatten is perhaps the cleanest solution:

```<code>[{a: 1}].flatten           #=> [{:a=>1}]
[[{a: 1}, {b: 2}]].flatten #=> [{:a=>1}, {:b=>2}]
</code>```

Clearly this inconsistent response format is not a great API design; but that's unfortunately the nature of working with external resources...

If each hash in the above array does represent a unique object, then I would leave that code as-is. However, if you actually have a different hash for each attribute of a single entity (?!), then you could further clean up the API response as follows:

```<code>[{a: 1}].flatten.reduce(:merge)           #=> {:a=>1}
[[{a: 1}, {b: 2}]].flatten.reduce(:merge) #=> {:a=>1, :b=>2}
</code>```

Title: Array method versus hashes

Body:
I have an object (returned from and API) that is either a hash or an array of hashes. I want to enclose it in an array if it is not already an array.

I tried to apply Array on it, which functions in an expected way with numbers or arrays:

Array(1) # => [1]
Array([1, 2]) # => [1, 2]
Array([{a: 1}, {b: 2}]) # => [{:a=>1}, {:b=>2}]

but it fails with hashes:

Array({a: 1}) # => [[:a, 1]]

which should be [{:a=>1}].

Alternatively, I could add a type check:

responses = [responses] if responses.is_a?(Hash)

Is there a better solution?

Body:
As @mudasobwa suggested, [responses].flatten is perhaps the cleanest solution:

[{a: 1}].flatten           #=> [{:a=>1}]
[[{a: 1}, {b: 2}]].flatten #=> [{:a=>1}, {:b=>2}]

Clearly this inconsistent response format is not a great API design; but that's unfortunately the nature of working with external resources...

If each hash in the above array does represent a unique object, then I would leave that code as-is. However, if you actually have a different hash for each attribute of a single entity (?!), then you could further clean up the API response as follows:

[{a: 1}].flatten.reduce(:merge)           #=> {:a=>1}
[[{a: 1}, {b: 2}]].flatten.reduce(:merge) #=> {:a=>1, :b=>2}


问:
Rails - EmailVeracity - setting the domain_check and timeout
I'm using EmailVeracity today as follows:

```<code>email = EmailVeracity::Address.new(params[:user][:email])
</code>```

I would like to know how to disable the domain_check and/or lower the timeout. I tried:

```<code>email = EmailVeracity::Address.new(params[:user][:email], :domain_check => false, :timeout => 5, :message => "is not valid")
</code>```

But get an ArgumentError, any ideas?

答:
Ok, look here: https://github.com/heycarsten/email-veracity/blob/master/lib/email_veracity/config.rb

So (this is untested), something like

```<code>EmailVeracity::Config[:skip_lookup] = true
</code>```

should be what you're looking for.

Body:
I'm using EmailVeracity today as follows:

email = EmailVeracity::Address.new(params[:user][:email])

I would like to know how to disable the domain_check and/or lower the timeout. I tried:

email = EmailVeracity::Address.new(params[:user][:email], :domain_check => false, :timeout => 5, :message => "is not valid")

But get an ArgumentError, any ideas?

Body:
Ok, look here: https://github.com/heycarsten/email-veracity/blob/master/lib/email_veracity/config.rb

So (this is untested), something like

EmailVeracity::Config[:skip_lookup] = true

should be what you're looking for.


问:
Spring Boot Program cannot find main class
I have a program which runs as a Spring boot App in eclipse. The program was running fine. Then i did the following:

Right click on project ->  Run As -> Maven Test .

This was accidental. When i then tried to run the program as a spring boot app again, it threw the following error below.

Error: Could not find or load main class com.bt.collab.alu.api.webapp.Application

How do i point the application back to my main class?
Thanks

答:
I am new in spring boot and using STS with maven build. I did all the things mentioned above but won't work for me. I noticed two problems in problem window of STS. There was a missing jar file on the path (C:\Users\UserName.m2\repository\com\jayway\jsonpath\json-path\2.2.0). I did following, the way is not strongly suggested but worked for me.

1) I deleted .m2 folder from the path location

2) Restarted STS

3) Right Click on project folder -> maven -> update project -> checked "Force update of snapshots/releases" -> Click Ok.

Maven updated its dependencies and the problem is solved.


问:
Rails Active Model Json serializer: returning has_many record as has_one
I have a Active Model JSON Serializer for a model, which has a has_many relation, that I want to include in the JSON response.

I would like the record to be included as has_one instead of has_many record - to only include the first record:

```<code>class PersonSerializer < ActiveModel::Serializer
  attributes :name, :symbol
  has_many :stats
  has_many :body_parts
end
</code>```

Here, body_parts should be returned as has one :body_part. What is the best way to do that?

答:
If you want to return only the first body_part and do that only in your serializer response, then better to define it as a method in PersonSerializer.

```<code>class PersonSerializer < ActiveModel::Serializer
  attributes :name, :symbol
  has_one :body_part, serializer: BodyPartSerializer
  ...
  def body_part
    self.object.body_parts.first
  end
end
</code>```

It assumes that you have a separate serialiser for BodyPart model.

Body:
I have a Active Model JSON Serializer for a model, which has a has_many relation, that I want to include in the JSON response.

I would like the record to be included as has_one instead of has_many record - to only include the first record:

class PersonSerializer < ActiveModel::Serializer
  attributes :name, :symbol
  has_many :stats
  has_many :body_parts
end

Here, body_parts should be returned as has one :body_part. What is the best way to do that?

Body:
If you want to return only the first body_part and do that only in your serializer response, then better to define it as a method in PersonSerializer.

class PersonSerializer < ActiveModel::Serializer
  attributes :name, :symbol
  has_one :body_part, serializer: BodyPartSerializer
  ...
  def body_part
    self.object.body_parts.first
  end
end

It assumes that you have a separate serialiser for BodyPart model.


问:
What are some good sql databases for home Vista computer?
I have been trying for a long time to get SQL Server Express on my computer to practice my C#/SQL with and I still haven't gotten it to work.

Are there other programs I can use to setup an SQL database to practice with?  If so, which are the best ones for Vista?

EDIT:
To be clear I am not new to SQL programming, I just haven't done any in a while and want to stay fresh.  So I would like something that has most of the features of forms of SQL I would use professionally.

答: Vista DB is quite a nice lightweight managed flatfile database (not related to Windows Vista).</p>

OwnerDisplayName: GordonG

LastEditorDisplayName: GordonG

OwnerDisplayName: RSlaughter


问:
Can the Echo dot 'talk' to local devices or does everything go via the cloud?
I'm looking at developing a plugin (probably an echo specific word for them) that will allow me to control a number of local hardware devices. The devices have a simple HTTP interface so very little plumbing should be required, however all the reading I've done so far (I'm new to the Echo API, so thats not that much yet) suggests that your code gets executed on remotely in the 'the cloud'. That being the case its going to struggle to access local resources without making them web facing (which isn't possible).

So as an example I want to write something that when you say "turn the kitchen light on". The echo box makes a http call to a local controller i.e. http://192.168.0.4/Light?room=kitchen&state=on

Is this possible, if so are there any simple examples about that I work from.

Thanks

答:
Yes it is possible. See https://www.npmjs.com/package/node-red-contrib-alexa-local for a node-red plugin that allows Alexa to control local devices by emulating a Philips Hue.

No cloud skills required!!

My local setup has lights, a heater and my front door lock all controlled by Alexa. The key is that Alexa already has a built in HA skill which understands, for example Philips Hue. So provided you have something which emulates a Philips Hue, you're all set. The node red skill I linked to does just that.

So, my setup is:-

Alexa ---> Node-Red (using the module I linked to) ---> MQTT Broker ---> My devices

Node-Red and MQTT (Mosquitto) are both running on a Pi, and that is my "hub". My devices vary, so some are Sonoff running Tasmoto, others use custom NodeMCU boards that I have built. Once you have Node-red running, you can make it talk to just about any device using just about any interface. However, for HA, MQTT is far and away the best route to take rather than HTTP.

For remote access, I use the Telegram module in node-red to listen for commands coming from a Telegram bot that I created. This means I can sit on the train and type "heater on".


问:
connection timed out error in online mode and could not open file in offline mode - android studio
```<code>repositories {
    maven { url "https://jitpack.io" }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.github.PhilJay:MPAndroidChart:v2.2.2'
}
</code>```

I am getting the Error:Connection timed out: connect in online mode whereas while changing the gradle setting to offline, I could not open the library.

答: Please connect to "Internet" and make it sync again.</p>

Body:
repositories {
    maven { url "https://jitpack.io" }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.github.PhilJay:MPAndroidChart:v2.2.2'
}

I am getting the Error:Connection timed out: connect in online mode whereas while changing the gradle setting to offline, I could not open the library.


答:
you have to build a relation and then you can use the following </p>

```<code>$query = Category::query();
$query->whereDoesntHave('child');
$query->get();
</code>```

<p>or simplest is </p>

```<code>Category::whereNull('parent_id')->get();
</code>```

Title: Laravel: Query childless elements in a table

Body:
I have this simple table containing all categories:

Category:
id|name|parentid

Using Eloquent, how can I query all the categories that have no childs?

Body:
you have to build a relation and then you can use the following

$query = Category::query();
$query->whereDoesntHave('child');
$query->get();

or simplest is

Category::whereNull('parent_id')->get();


问:
Disassemble, modify, and reassemble executable
How can I disassemble an executable on my mac using ndisasm and reassemble and link it using nasm and ld?
This is what I tried (I'm running MacOS X btw):

```<code> *ndisasm a.out | cut -c 29- > main.asm*
</code>```

this generated clean assembler code with all the processor instructions in main.asm

```<code> *nasm -f macho main.asm*
</code>```

this generated an object file main.o which I then tried to link

```<code> *ld main.o*
</code>```

... this is where I'm stuck. I don't know why it generates the following error:

ld: in section __TEXT,__text reloc 0: R_ABS reloc but no absolute symbol at target adress file 'main.o' for inferred architecture i386.

I also tried specifying the architecture (ld -arch x86_64 main.o) but that didn't work either.

My goal is to disassemble any executable, modify it and then reassemble it again.

What am I doing wrong?

答:
There is no reliable way to do this with normal assembler syntax.  See  How to disassemble, modify and then reassemble a Linux executable?.  Section info is typically not faithfully disassembled, so you'd need a special format designed for modify and reassembling + relinking.

Also, instruction-lengths are a problem when code only works when padded by using longer encodings.  (e.g. in a table of jump targets for a computed goto).  See Where are GNU assembler instruction suffixes like ".s" in x86 "mov.s" documented?, but note that disassemblers don't support disassembling into that format.

ndisasm doesn't understand object file formats, so it disassembles headers as machine code!

For this to have any hope of working, use a disassembler like Agner Fog's objconv which will output asm source (NASM, MASM, or GAS AT&T) which does assemble.  It might not actually work if any of the code depended on a specific longer-than-default encoding.

I'm not sure how faithful objconv is with respect to emitting section .bss, section .rodata and other directives like that to place data where it found it in the object file, but that's what you need.

Re: absolute relocations: make sure you put DEFAULT REL at the top of your file.  I forget if objconv does this by default.  x86-64 Mach-o only supports PC-relative relocations, so you have to create position-independent code (e.g. using RIP-relative addressing modes).

ndisasm doesn't read the symbol table, so all its operands use absolute addressing.  objconv makes up label names for jump targets and static data that doesn't appear in the symbol table.

Body:
How can I disassemble an executable on my mac using ndisasm and reassemble and link it using nasm and ld?
This is what I tried (I'm running MacOS X btw):

 *ndisasm a.out | cut -c 29- > main.asm*

this generated clean assembler code with all the processor instructions in main.asm

 *nasm -f macho main.asm*

this generated an object file main.o which I then tried to link

 *ld main.o*

... this is where I'm stuck. I don't know why it generates the following error:

ld: in section __TEXT,__text reloc 0: R_ABS reloc but no absolute symbol at target adress file 'main.o' for inferred architecture i386.

I also tried specifying the architecture (ld -arch x86_64 main.o) but that didn't work either.

My goal is to disassemble any executable, modify it and then reassemble it again.

What am I doing wrong?


问:
Take the sum of 3 adc data for 3 sampling

Hi everyone,

I am a newbie in programming FPGA by verilog language. At the present, I am trying to design the firmware to calculate the sum of adc data at 3 sampling. Firstly, I will explain about one adc at one sampling in my code. When you look at the code, you can see that with rising-edge of clkr clock and adcIfEnb == 1, the adc_data will get the value from adcIfData and this is the data for one sampling. In the next rising-edge of clkr clock and adcIfEnb == 1, this data is stored in iradcTrg. Finally, I will have the 3 data of adc_data for 3 sampling which are stored in iradcTrg and then I summarize 3 these data.

```<code>wire adcIfData[79:0];
reg
always @(posedge clkr) begin
if(adcIfEnb) begin
adc_data[9:0] <= adcIfData[9:0];
end
end
reg [29:0] iradcTrg;
reg [9:0]  adcTrg;
always @(posedge clkr) begin
if (adcIfEnb) begin
iradcTrg[29:0] <= {adc_trg[19:10],adc_trg[9:0],adc_data[9:0]};
adcTrg[9:0] <= adc_trg[29:20] + adc_trg[19:10] + adc_trg[9:0];
end
end
</code>```

However, there are 2 problems which I do not know how to solve.

Firstly, at the beginning time, when the first data of adc_data is stored at iradcTrg and adcTrg also take the sum. It means that adcTrg = 0 + 0 + first_adc_data but this sum need to be avoided.

Secondly, according to my design, I see that adc_data is serialized into iradcTrg. It means that the adc_data will be stored like this:

[1 2 3] 4 5 6 => 1 [2 3 4] 5 6=> 1 2 [3 4 5] 6

But in my case, I would like that the adc_data will be stored like this to get the sum

[1 2 3] 4 5 6 => 1 2 3 [4 5 6]

Therefore, how should I repair my code to get the result that I expected or are there any documents can help me in this case ?

答:
Few comments first:

1) I don't know why do you introduce so many variables with strange names. You only need a adc_buffer and adc_sum. Is iradcTrg the same as adc_trg? Why is there an empty reg statement? Why adcIfData has 80 bits and you only use 8 LSB bits? I'm confused.

2) Since adc_sum will be a sum of 3 (adcTrg in your case), think about possible overflow. What should be the width of adc_sum if you want to add 3 10-bit numbers?

3) Shouldn't you reset your design to a known state using asynchronous or synchronous reset first?

You can use a 2 bit counter with async reset and a logic for wrapping back to 0:

```<code>    reg [1:0] adc_buffer_counter_reg;
    always @(posedge clkr or negedge rst_n) begin
      if (!rst_n)
        adc_buffer_counter_reg <= 2'd0;
      else if (adcIfEnb) begin
        if (adc_buffer_counter_reg == 2'd2) //trigger calc of the sum here
          adc_buffer_counter_reg <= 2'd0;
        else
          adc_buffer_counter_reg <= adc_buffer_counter_reg + 2'd1;
    end
</code>```

You can use this counter to trigger a calculation of the sum every 3rd valid data.

Body:
Hi everyone,

I am a newbie in programming FPGA by verilog language. At the present, I am trying to design the firmware to calculate the sum of adc data at 3 sampling. Firstly, I will explain about one adc at one sampling in my code. When you look at the code, you can see that with rising-edge of clkr clock and adcIfEnb == 1, the adc_data will get the value from adcIfData and this is the data for one sampling. In the next rising-edge of clkr clock and adcIfEnb == 1, this data is stored in iradcTrg. Finally, I will have the 3 data of adc_data for 3 sampling which are stored in iradcTrg and then I summarize 3 these data.

wire adcIfData[79:0];
reg
always @(posedge clkr) begin
if(adcIfEnb) begin
adc_data[9:0] <= adcIfData[9:0];
end
end
reg [29:0] iradcTrg;
reg [9:0]  adcTrg;
always @(posedge clkr) begin
if (adcIfEnb) begin
iradcTrg[29:0] <= {adc_trg[19:10],adc_trg[9:0],adc_data[9:0]};
adcTrg[9:0] <= adc_trg[29:20] + adc_trg[19:10] + adc_trg[9:0];
end
end

However, there are 2 problems which I do not know how to solve.

Firstly, at the beginning time, when the first data of adc_data is stored at iradcTrg and adcTrg also take the sum. It means that adcTrg = 0 + 0 + first_adc_data but this sum need to be avoided.

Secondly, according to my design, I see that adc_data is serialized into iradcTrg. It means that the adc_data will be stored like this:

[1 2 3] 4 5 6 => 1 [2 3 4] 5 6=> 1 2 [3 4 5] 6

But in my case, I would like that the adc_data will be stored like this to get the sum

[1 2 3] 4 5 6 => 1 2 3 [4 5 6]

Therefore, how should I repair my code to get the result that I expected or are there any documents can help me in this case ?

Body:
Few comments first:

1) I don't know why do you introduce so many variables with strange names. You only need a adc_buffer and adc_sum. Is iradcTrg the same as adc_trg? Why is there an empty reg statement? Why adcIfData has 80 bits and you only use 8 LSB bits? I'm confused.

2) Since adc_sum will be a sum of 3 (adcTrg in your case), think about possible overflow. What should be the width of adc_sum if you want to add 3 10-bit numbers?

3) Shouldn't you reset your design to a known state using asynchronous or synchronous reset first?

You can use a 2 bit counter with async reset and a logic for wrapping back to 0:

    reg [1:0] adc_buffer_counter_reg;
    always @(posedge clkr or negedge rst_n) begin
      if (!rst_n)
        adc_buffer_counter_reg <= 2'd0;
      else if (adcIfEnb) begin
        if (adc_buffer_counter_reg == 2'd2) //trigger calc of the sum here
          adc_buffer_counter_reg <= 2'd0;
        else
          adc_buffer_counter_reg <= adc_buffer_counter_reg + 2'd1;
    end

You can use this counter to trigger a calculation of the sum every 3rd valid data.