问:
CSS - border not going over elements that float left
I have this code here:

```<code><div style="border:3px solid #808080;">
    <h1 style="text-transform: uppercase;font-size: 38px;color: #808080;text-align: center;">Lowell</h1>
    <div class="column-1">
         <img src="images/ruler-icon.png">
    </div>
    <div class="column-2">
         <img src="images/bed-icon.png">
    </div>
    <div class="column-3">
         <img src="images/bath-icon.png">
    </div>
</div>
</code>```

my problem is that the border does not go over the column-1, column-2, column-3...those elements are floating left, how do I get them to be included in the border?

Here is the CSS

```<code>.column-1, .column-2, .column-3
{
    float:left;
    width: 33%;
    border-right: 3px solid #808080;
    height: 52px;
    padding: 10px;
}
</code>```

答: Add a div with style clear:both after the floated divs inside parent div. This will hopefully fix this issue.</p>

Body:
I have this code here:

Lowell

my problem is that the border does not go over the column-1, column-2, column-3...those elements are floating left, how do I get them to be included in the border?

Here is the CSS

.column-1, .column-2, .column-3
{
    float:left;
    width: 33%;
    border-right: 3px solid #808080;
    height: 52px;
    padding: 10px;
}


来源: stackexchange

问:
Aggregation of an annotation in GROUP BY in Django
UPDATE

Thanks to the posted answer, I found a much simpler way to formulate the problem. The original question can be seen in the revision history.

The problem

I am trying to translate an SQL query into Django, but am getting an error that I don't understand.

Here is the Django model I have:

```<code>class Title(models.Model):
  title_id = models.CharField(primary_key=True, max_length=12)
  title = models.CharField(max_length=80)
  publisher = models.CharField(max_length=100)
  price = models.DecimalField(decimal_places=2, blank=True, null=True)
</code>```

I have the following data:

```<code>publisher                    title_id      price  title
---------------------------  ----------  -------  -----------------------------------
New Age Books                PS2106         7     Life Without Fear
New Age Books                PS2091        10.95  Is Anger the Enemy?
New Age Books                BU2075         2.99  You Can Combat    Computer Stress!
New Age Books                TC7777        14.99  Sushi, Anyone?
Binnet & Hardley             MC3021         2.99  The Gourmet Microwave
Binnet & Hardley             MC2222        19.99  Silicon Valley   Gastronomic Treats
Algodata Infosystems         PC1035        22.95  But Is It User Friendly?
Algodata Infosystems         BU1032        19.99  The Busy Executive's   Database Guide
Algodata Infosystems         PC8888        20     Secrets of Silicon Valley
</code>```

Here is what I want to do: introduce an annotated field dbl_price which is twice the price, then group the resulting queryset by publisher, and for each publisher, compute the total of all dbl_price values for all titles published by that publisher.

The SQL query that does this is as follows:

```<code>SELECT SUM(dbl_price) AS total_dbl_price, publisher
FROM (
  SELECT price * 2 AS dbl_price, publisher
  FROM title
) AS A
GROUP BY publisher
</code>```

The desired output would be:

```<code>publisher                    tot_dbl_prices
---------------------------  --------------
Algodata Infosystems                 125.88
Binnet & Hardley                      45.96
New Age Books                         71.86
</code>```

Django query

The query would look like:

```<code>Title.objects
 .annotate(dbl_price=2*F('price'))
 .values('publisher')
 .annotate(tot_dbl_prices=Sum('dbl_price'))
</code>```

but gives an error:

```<code>KeyError: 'dbl_price'.
</code>```

which indicates that it can't find the field dbl_price in the queryset.

The reason for the error

Here is why this error happens: the documentation says

You should also note that average_rating has been explicitly included
       in the list of values to be returned. This is required because of the    ordering of the values() and annotate() clause.

If the values() clause precedes the annotate() clause, any annotations
       will be automatically added to the result set. However, if the
       values() clause is applied after the annotate() clause, you need to explicitly include the aggregate column.

So, the dbl_price could not be found in aggregation, because it was created by a prior annotate, but wasn't included in values().

However, I can't include it in values either, because I want to use values (followed by another annotate) as a grouping device, since

If the values() clause precedes the annotate(), the annotation will be computed using the grouping described by the values() clause.

which is the basis of how Django implements SQL GROUP BY. This means that I can't include dbl_price inside values(), because then the grouping will be based on unique combinations of both fields publisher and dbl_price, whereas I need to group by publisher only.

So, the following query, which only differs from the above in that I aggregate over model's price field rather than annotated dbl_price field, actually works:

```<code>Title.objects
 .annotate(dbl_price=2*F('price'))
 .values('publisher')
 .annotate(sum_of_prices=Count('price'))
</code>```

because the price field is in the model rather than being an annotated field, and so we don't need to include it in values to keep it in the queryset.

The question

So, here we have it: I need to include annotated property into values to keep it in the queryset, but I can't do that because values is also used for grouping (which will be wrong with an extra field). The problem essentially is due to the two very different ways that values is used in Django, depending on the context (whether or not values is followed by annotate) - which is (1) value extraction (SQL plain SELECT list) and (2) grouping + aggregation over the groups (SQL GROUP BY) - and in this case these two ways seem to conflict.

My question is: is there any way to solve this problem (without things like falling back to raw sql)?

Please note: the specific example in question can be solved by moving all annotate statements after values, which was noted by several answers. However, I am more interested in solutions (or discussion) which would keep the annotate statement(s) before values(), for three reasons: 1. There are also more complex examples, where the suggested workaround would not work. 2. I can imagine situations, where the annotated queryset has been passed to another function, which actually does GROUP BY, so that the only thing we know is the set of names of annotated fields, and their types. 3. The situation seems to be pretty straightforward, and it would surprise me if this clash of two distinct uses of values() has not been noticed and discussed before.

答:
This is expected from the way group_by works in Django. All annotated fields are added in GROUP BY clause. However, I am unable to comment on why it was written this way.

You can get your query to work like this:

```<code>Title.objects
  .values('publisher')
  .annotate(total_dbl_price=Sum(2*F('price'))
</code>```

which produces following SQL:

```<code>SELECT publisher, SUM((2 * price)) AS total_dbl_price
FROM title
GROUP BY publisher
</code>```

which just happens to work in your case.

I understand this might not be the complete solution you were looking for, but some even complex annotations can also be accommodated in this solution by using CombinedExpressions(I hope!).

ContentLicense: CC BY-SA 3.0

Body:
UPDATE

Thanks to the posted answer, I found a much simpler way to formulate the problem. The original question can be seen in the revision history.

The problem

I am trying to translate an SQL query into Django, but am getting an error that I don't understand.

Here is the Django model I have:

class Title(models.Model):
  title_id = models.CharField(primary_key=True, max_length=12)
  title = models.CharField(max_length=80)
  publisher = models.CharField(max_length=100)
  price = models.DecimalField(decimal_places=2, blank=True, null=True)

I have the following data:

publisher                    title_id      price  title
---------------------------  ----------  -------  -----------------------------------
New Age Books                PS2106         7     Life Without Fear
New Age Books                PS2091        10.95  Is Anger the Enemy?
New Age Books                BU2075         2.99  You Can Combat    Computer Stress!
New Age Books                TC7777        14.99  Sushi, Anyone?
Binnet & Hardley             MC3021         2.99  The Gourmet Microwave
Binnet & Hardley             MC2222        19.99  Silicon Valley   Gastronomic Treats
Algodata Infosystems         PC1035        22.95  But Is It User Friendly?
Algodata Infosystems         BU1032        19.99  The Busy Executive's   Database Guide
Algodata Infosystems         PC8888        20     Secrets of Silicon Valley

Here is what I want to do: introduce an annotated field dbl_price which is twice the price, then group the resulting queryset by publisher, and for each publisher, compute the total of all dbl_price values for all titles published by that publisher.

The SQL query that does this is as follows:

SELECT SUM(dbl_price) AS total_dbl_price, publisher
FROM (
  SELECT price * 2 AS dbl_price, publisher
  FROM title
) AS A
GROUP BY publisher

The desired output would be:

publisher                    tot_dbl_prices
---------------------------  --------------
Algodata Infosystems                 125.88
Binnet & Hardley                      45.96
New Age Books                         71.86

Django query

The query would look like:

Title.objects
 .annotate(dbl_price=2*F('price'))
 .values('publisher')
 .annotate(tot_dbl_prices=Sum('dbl_price'))

but gives an error:

KeyError: 'dbl_price'.

which indicates that it can't find the field dbl_price in the queryset.

The reason for the error

Here is why this error happens: the documentation says

You should also note that average_rating has been explicitly included
       in the list of values to be returned. This is required because of the    ordering of the values() and annotate() clause.

If the values() clause precedes the annotate() clause, any annotations
       will be automatically added to the result set. However, if the
       values() clause is applied after the annotate() clause, you need to explicitly include the aggregate column.

So, the dbl_price could not be found in aggregation, because it was created by a prior annotate, but wasn't included in values().

However, I can't include it in values either, because I want to use values (followed by another annotate) as a grouping device, since

If the values() clause precedes the annotate(), the annotation will be computed using the grouping described by the values() clause.

which is the basis of how Django implements SQL GROUP BY. This means that I can't include dbl_price inside values(), because then the grouping will be based on unique combinations of both fields publisher and dbl_price, whereas I need to group by publisher only.

So, the following query, which only differs from the above in that I aggregate over model's price field rather than annotated dbl_price field, actually works:

Title.objects
 .annotate(dbl_price=2*F('price'))
 .values('publisher')
 .annotate(sum_of_prices=Count('price'))

because the price field is in the model rather than being an annotated field, and so we don't need to include it in values to keep it in the queryset.

The question

So, here we have it: I need to include annotated property into values to keep it in the queryset, but I can't do that because values is also used for grouping (which will be wrong with an extra field). The problem essentially is due to the two very different ways that values is used in Django, depending on the context (whether or not values is followed by annotate) - which is (1) value extraction (SQL plain SELECT list) and (2) grouping + aggregation over the groups (SQL GROUP BY) - and in this case these two ways seem to conflict.

My question is: is there any way to solve this problem (without things like falling back to raw sql)?

Please note: the specific example in question can be solved by moving all annotate statements after values, which was noted by several answers. However, I am more interested in solutions (or discussion) which would keep the annotate statement(s) before values(), for three reasons: 1. There are also more complex examples, where the suggested workaround would not work. 2. I can imagine situations, where the annotated queryset has been passed to another function, which actually does GROUP BY, so that the only thing we know is the set of names of annotated fields, and their types. 3. The situation seems to be pretty straightforward, and it would surprise me if this clash of two distinct uses of values() has not been noticed and discussed before.

Body:
This is expected from the way group_by works in Django. All annotated fields are added in GROUP BY clause. However, I am unable to comment on why it was written this way.

You can get your query to work like this:

Title.objects
  .values('publisher')
  .annotate(total_dbl_price=Sum(2*F('price'))

which produces following SQL:

SELECT publisher, SUM((2 * price)) AS total_dbl_price
FROM title
GROUP BY publisher

which just happens to work in your case.

I understand this might not be the complete solution you were looking for, but some even complex annotations can also be accommodated in this solution by using CombinedExpressions(I hope!).


问:
ClassNotFoundException when trying to execute a jar file in serenity-jbehave
I'm getting the error below:</p>

```<code>Exception in thread "main"java.lang.NoClassDefFoundError:net/serenitybdd/jbehave/SerenityStories

Caused by: java.lang.ClassNotFoundException: net.serenitybdd.jbehave.SerenityStories
</code>```

答: That's a dependency conflict. Check that you are using the latest versions for all of the serenity jars.</p>

Body:
I'm getting the error below:

Exception in thread "main"java.lang.NoClassDefFoundError:net/serenitybdd/jbehave/SerenityStories

Caused by: java.lang.ClassNotFoundException: net.serenitybdd.jbehave.SerenityStories


问:
Couchbase N1QL SELECT query using ORDER BY is very slow
The following query is very slow:

```<code>select meta(d).id, timestamp_utc, d.headline, d.text from data_01 d where type="news" and topic="some_news" and timestamp_utc is not null order by timestamp_utc asc limit 1;
</code>```

I created the following indices / indexes:

```<code> CREATE INDEX `idx_timestamp_utc` ON `data_01`((-str_to_millis(`timestamp_utc`)))
 CREATE INDEX `idx_timestamp_utc_some_news` ON `data_01`(`timestamp_utc`) WHERE ((`type` = "news") and (`topic` = "some_news"))
 CREATE INDEX `idx_topic_and_timestamp_utc` ON `data_01`(`topic`,(-str_to_millis(`timestamp_utc`)))
 CREATE INDEX `idx_type_news_topic_some_news_timestamp_utc` ON `data_01`((-`timestamp_utc`)) WHERE ((`type` = "news") and (`topic` = "some_news"))
</code>```

None of this gives me a better performance than 1 minute.

There are 3million documents in the bucket topic="some_news" has 300k
docs.

type="news" has around 2 million docs.

field timestamp_utc has this format: "2017-01-01T00:00:00+00:00".

field headline has an average length of ~100 characters.

field text has an average of length ~2000 characters.

I found similar problems but non of the given fixes and suggestions do work.

Thank you for a response to solve this issue!

I'm running Couchbase 4.5.1 Enterprise Edition (build-2844)

答:
In CB 4.5.0 and above Try one of the following indexes and modified query below.
    The index can be used for any topic
    The query predicate on topic is equality changing order by to include topic will not change results and that matches query order same as index keys order and query will avoid sort.</p>

```<code>CREATE INDEX `idx_some_news_timestamp_utc` ON `data_01`(`topic`,`timestamp_utc`) WHERE type = "news";
CREATE INDEX `idx_some_news_timestamp_utc_headline_text` ON `data_01`(`topic`,`timestamp_utc`,headline, text) WHERE type = "news";

SELECT meta(d).id, d.timestamp_utc, d.headline, d.text FROM data_01 d
WHERE type="news" AND topic="some_news" AND timestamp_utc IS NOT NULL
ORDER BY topic, timestamp_utc ASC LIMIT 1;
</code>```

Body:
The following query is very slow:

select meta(d).id, timestamp_utc, d.headline, d.text from data_01 d where type="news" and topic="some_news" and timestamp_utc is not null order by timestamp_utc asc limit 1;

I created the following indices / indexes:

 CREATE INDEX `idx_timestamp_utc` ON `data_01`((-str_to_millis(`timestamp_utc`)))
 CREATE INDEX `idx_timestamp_utc_some_news` ON `data_01`(`timestamp_utc`) WHERE ((`type` = "news") and (`topic` = "some_news"))
 CREATE INDEX `idx_topic_and_timestamp_utc` ON `data_01`(`topic`,(-str_to_millis(`timestamp_utc`)))
 CREATE INDEX `idx_type_news_topic_some_news_timestamp_utc` ON `data_01`((-`timestamp_utc`)) WHERE ((`type` = "news") and (`topic` = "some_news"))

None of this gives me a better performance than 1 minute.

There are 3million documents in the bucket topic="some_news" has 300k
docs.

type="news" has around 2 million docs.

field timestamp_utc has this format: "2017-01-01T00:00:00+00:00".

field headline has an average length of ~100 characters.

field text has an average of length ~2000 characters.

I found similar problems but non of the given fixes and suggestions do work.

Thank you for a response to solve this issue!

I'm running Couchbase 4.5.1 Enterprise Edition (build-2844)

Body:
In CB 4.5.0 and above Try one of the following indexes and modified query below.
    The index can be used for any topic
    The query predicate on topic is equality changing order by to include topic will not change results and that matches query order same as index keys order and query will avoid sort.

CREATE INDEX `idx_some_news_timestamp_utc` ON `data_01`(`topic`,`timestamp_utc`) WHERE type = "news";
CREATE INDEX `idx_some_news_timestamp_utc_headline_text` ON `data_01`(`topic`,`timestamp_utc`,headline, text) WHERE type = "news";

SELECT meta(d).id, d.timestamp_utc, d.headline, d.text FROM data_01 d
WHERE type="news" AND topic="some_news" AND timestamp_utc IS NOT NULL
ORDER BY topic, timestamp_utc ASC LIMIT 1;


问:
c struct relationships
```<code>//CHILD
typedef struct Child{
    int id;
}Child;
Child* newChild(){
    Child *aChild = malloc(sizeof(Child));
    aChild->id = 0;
    return aChild;
}

//PARENT
typedef struct Parent{
    int id;
    Child **children;
}Parent;

Parent* newParent(){
    Parent *aParent = malloc(sizeof(Parent));
    aParent->id = 0;
    aParent->children = malloc(sizeof(Child*) * 5);//ARRAY OF 5 CHILDREN?
    for(i=0; i<5; i++){
        aParent->children[i] = newChild();
    }
    return aParent;
}
</code>```

Is the newParent() function a correct way to create a struct with an array children? My main concern is the line:

```<code>aParent->children = malloc(sizeof(Child*) * 5);
</code>```

答: You should check if malloc actually succeeded, but other than that, the code is OK.

ContentLicense: CC BY-SA 2.5

Title: c struct relationships

Body:
//CHILD
typedef struct Child{
    int id;
}Child;
Child* newChild(){
    Child *aChild = malloc(sizeof(Child));
    aChild->id = 0;
    return aChild;
}

//PARENT
typedef struct Parent{
    int id;
    Child **children;
}Parent;

Parent* newParent(){
    Parent *aParent = malloc(sizeof(Parent));
    aParent->id = 0;
    aParent->children = malloc(sizeof(Child*) * 5);//ARRAY OF 5 CHILDREN?
    for(i=0; i<5; i++){
        aParent->children[i] = newChild();
    }
    return aParent;
}

Is the newParent() function a correct way to create a struct with an array children? My main concern is the line:

aParent->children = malloc(sizeof(Child*) * 5);


问:
How to address a workbook in vba for Mac?
I´m trying to run a macro that works perfectly on a PC, but when trying to run the same macro on Mac I get the error "1004"; which says that the file can´t be found.
I´m writing the address like this way:

```<code>Workbooks.Open("\Macintosh HD\Usuarios\carlosstephan\Dropbox\SCEN Const.\GastosyPagosSCEN.xlsm")
</code>```

Does someone knows how to write it correct?.

I already tried with "/" instead of "\", and it doesn´t works either.

The same error pops-up with this "with":

```<code>With Sheets("Gastos")

    .Range(“A8”, .Cells(.Rows.Count, .Columns.Count)).Clear

End With
</code>```

Where is the mistake?.

答:
With the following VBA code you will know which is your separator:

```<code>Separator = Application.PathSeparator
</code>```

or if you use the Inmediate window:

```<code>Debug.Print application.PathSeparator
</code>```

Once you know the separator, substitute it in the Workbook path string and do not remove the spaces

Body:
I´m trying to run a macro that works perfectly on a PC, but when trying to run the same macro on Mac I get the error "1004"; which says that the file can´t be found.
I´m writing the address like this way:

Workbooks.Open("\Macintosh HD\Usuarios\carlosstephan\Dropbox\SCEN Const.\GastosyPagosSCEN.xlsm")

Does someone knows how to write it correct?.

I already tried with "/" instead of "\", and it doesn´t works either.

The same error pops-up with this "with":

With Sheets("Gastos")

    .Range(“A8”, .Cells(.Rows.Count, .Columns.Count)).Clear

End With

Where is the mistake?.

Body:
With the following VBA code you will know which is your separator:

Separator = Application.PathSeparator

or if you use the Inmediate window:

Debug.Print application.PathSeparator

Once you know the separator, substitute it in the Workbook path string and do not remove the spaces


问:
python multiprocessing: write to same excel file
I am new to Python and I am trying to save the results of five different processes to one excel file (each process write to a different sheet). I have read different posts here, but still can't get it done as I'm very confused about pool.map, queues, and locks, and I'm not sure what is required here to fulfill this task.
This is my code so far:

```<code>list_of_days = ["2017.03.20", "2017.03.21", "2017.03.22", "2017.03.23", "2017.03.24"]
results = pd.DataFrame()

if __name__ == '__main__':
    global list_of_days
    writer = pd.ExcelWriter('myfile.xlsx', engine='xlsxwriter')
    nr_of_cores = multiprocessing.cpu_count()
    l = multiprocessing.Lock()
    pool = multiprocessing.Pool(processes=nr_of_cores, initializer=init, initargs=(l,))
    pool.map(f, range(len(list_of_days)))
    pool.close()
    pool.join()

def init(l):
    global lock
    lock = l

def f(k):
    global results

    *** DO SOME STUFF HERE***

    results = results[ *** finished pandas dataframe *** ]

    lock.acquire()
    results.to_excel(writer, sheet_name=list_of_days[k])
    writer.save()
    lock.release()
</code>```

The result is that only one sheet gets created in excel (I assume it is the process finishing last). Some questions about this code:

How to avoid defining global variables?

Is it even possible to pass around dataframes?

Should I move the locking to main instead?

Really appreciate some input here, as I consider mastering multiprocessing as instrumental. Thanks

答:
1) Why did you implement time.sleep in several places in your 2nd method?

In __main__, time.sleep(0.1), to give the started process a timeslice to startup.

   In f2(fq, q), to give the queue a timeslice to flushed all buffered data to the pipe and
   as q.get_nowait() are used.

   In w(q), are only for testing simulating long run of writer.to_excel(...),
   i removed this one.

2) What is the difference between pool.map and pool = [mp.Process( . )]?

Using pool.map needs no Queue, no parameter passed, shorter code.
    The worker_process have to return immediately the result and terminates.
    pool.map starts a new process as long as all iteration are done.
The results have to be processed after that.

Using pool = [mp.Process( . )],  starts n processes.
 A process terminates on queue.Empty

Can you think of a situation where you would prefer one method over the other?

Methode 1: Quick setup, serialized, only interested in the result to continue.

    Methode 2: If you want to do all workload parallel.

You could't use global writer in processes.

The writer instance has to belong to one process.

Usage of  mp.Pool, for instance:

```<code>def f1(k):
  # *** DO SOME STUFF HERE***
  results = pd.DataFrame(df_)
  return results

if __name__ == '__main__':
    pool = mp.Pool()
    results = pool.map(f1, range(len(list_of_days)))

    writer = pd.ExcelWriter('../test/myfile.xlsx', engine='xlsxwriter')
    for k, result in enumerate(results):
        result.to_excel(writer, sheet_name=list_of_days[k])

    writer.save()
    pool.close()
</code>```

This leads to .to_excel(...) are called in sequence in the __main__ process.

If you want parallel .to_excel(...) you have to use mp.Queue().

For instance:

The worker process:

```<code># mp.Queue exeptions have to load from
try:
    # Python3
    import queue
except:
    # Python 2
    import Queue as queue

def f2(fq, q):
    while True:
        try:
            k = fq.get_nowait()
        except queue.Empty:
            exit(0)

        # *** DO SOME STUFF HERE***

        results = pd.DataFrame(df_)
        q.put( (list_of_days[k], results) )
        time.sleep(0.1)
</code>```

The writer process:

```<code>def w(q):
    writer = pd.ExcelWriter('myfile.xlsx', engine='xlsxwriter')
    while True:
        try:
            titel, result = q.get()
        except ValueError:
            writer.save()
            exit(0)

        result.to_excel(writer, sheet_name=titel)
</code>```

The __main__ process:

```<code>if __name__ == '__main__':
    w_q = mp.Queue()
    w_p = mp.Process(target=w, args=(w_q,))
    w_p.start()
    time.sleep(0.1)

    f_q = mp.Queue()
    for i in range(len(list_of_days)):
        f_q.put(i)

    pool = [mp.Process(target=f2, args=(f_q, w_q,)) for p in range(os.cpu_count())]
    for p in pool:
        p.start()
        time.sleep(0.1)

    for p in pool:
        p.join()

    w_q.put('STOP')
    w_p.join()
</code>```

Tested with Python:3.4.2 - pandas:0.19.2 - xlsxwriter:0.9.6

Body:
I am new to Python and I am trying to save the results of five different processes to one excel file (each process write to a different sheet). I have read different posts here, but still can't get it done as I'm very confused about pool.map, queues, and locks, and I'm not sure what is required here to fulfill this task.
This is my code so far:

list_of_days = ["2017.03.20", "2017.03.21", "2017.03.22", "2017.03.23", "2017.03.24"]
results = pd.DataFrame()

if __name__ == '__main__':
    global list_of_days
    writer = pd.ExcelWriter('myfile.xlsx', engine='xlsxwriter')
    nr_of_cores = multiprocessing.cpu_count()
    l = multiprocessing.Lock()
    pool = multiprocessing.Pool(processes=nr_of_cores, initializer=init, initargs=(l,))
    pool.map(f, range(len(list_of_days)))
    pool.close()
    pool.join()

def init(l):
    global lock
    lock = l

def f(k):
    global results

    *** DO SOME STUFF HERE***

    results = results[ *** finished pandas dataframe *** ]

    lock.acquire()
    results.to_excel(writer, sheet_name=list_of_days[k])
    writer.save()
    lock.release()

The result is that only one sheet gets created in excel (I assume it is the process finishing last). Some questions about this code:

How to avoid defining global variables?

Is it even possible to pass around dataframes?

Should I move the locking to main instead?

Really appreciate some input here, as I consider mastering multiprocessing as instrumental. Thanks

Body:
1) Why did you implement time.sleep in several places in your 2nd method?

In __main__, time.sleep(0.1), to give the started process a timeslice to startup.

   In f2(fq, q), to give the queue a timeslice to flushed all buffered data to the pipe and
   as q.get_nowait() are used.

   In w(q), are only for testing simulating long run of writer.to_excel(...),
   i removed this one.

2) What is the difference between pool.map and pool = [mp.Process( . )]?

Using pool.map needs no Queue, no parameter passed, shorter code.
    The worker_process have to return immediately the result and terminates.
    pool.map starts a new process as long as all iteration are done.
The results have to be processed after that.

Using pool = [mp.Process( . )],  starts n processes.
 A process terminates on queue.Empty

Can you think of a situation where you would prefer one method over the other?

Methode 1: Quick setup, serialized, only interested in the result to continue.

    Methode 2: If you want to do all workload parallel.

You could't use global writer in processes.

The writer instance has to belong to one process.

Usage of  mp.Pool, for instance:

def f1(k):
  # *** DO SOME STUFF HERE***
  results = pd.DataFrame(df_)
  return results

if __name__ == '__main__':
    pool = mp.Pool()
    results = pool.map(f1, range(len(list_of_days)))

    writer = pd.ExcelWriter('../test/myfile.xlsx', engine='xlsxwriter')
    for k, result in enumerate(results):
        result.to_excel(writer, sheet_name=list_of_days[k])

    writer.save()
    pool.close()

This leads to .to_excel(...) are called in sequence in the __main__ process.

If you want parallel .to_excel(...) you have to use mp.Queue().

For instance:

The worker process:

# mp.Queue exeptions have to load from
try:
    # Python3
    import queue
except:
    # Python 2
    import Queue as queue

def f2(fq, q):
    while True:
        try:
            k = fq.get_nowait()
        except queue.Empty:
            exit(0)

        # *** DO SOME STUFF HERE***

        results = pd.DataFrame(df_)
        q.put( (list_of_days[k], results) )
        time.sleep(0.1)

The writer process:

def w(q):
    writer = pd.ExcelWriter('myfile.xlsx', engine='xlsxwriter')
    while True:
        try:
            titel, result = q.get()
        except ValueError:
            writer.save()
            exit(0)

        result.to_excel(writer, sheet_name=titel)

The __main__ process:

if __name__ == '__main__':
    w_q = mp.Queue()
    w_p = mp.Process(target=w, args=(w_q,))
    w_p.start()
    time.sleep(0.1)

    f_q = mp.Queue()
    for i in range(len(list_of_days)):
        f_q.put(i)

    pool = [mp.Process(target=f2, args=(f_q, w_q,)) for p in range(os.cpu_count())]
    for p in pool:
        p.start()
        time.sleep(0.1)

    for p in pool:
        p.join()

    w_q.put('STOP')
    w_p.join()

Tested with Python:3.4.2 - pandas:0.19.2 - xlsxwriter:0.9.6

ContentLicense: CC BY-SA 4.0


问:
rails dispatch event?
First off, I am totally new with gems and engines (eh. ruby);
I am writing a handy engine which is going to filter requests based on the rules the user(developer) defines, currently my approach is the following:

```<code>class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action { Acu::Monitor.new request }
end
</code>```

And it works like a charm, but I want the engine to be plug-n-play with minimum configuration by the user, is there anyway I can achive this?

Can I get anywhere between dispatch and controller, where I can validate the request? Is there something like pre-dispatch-event in rails?

I would really appreciate if anyone help me on this, I got tired of google this, kind of ran out of query to write! :D

update:

requests has to be processed, i.e the target controller/action need to be determined by rails then I am processing the request.

答:
I found the answer, it is the instrumentation that I was looking for

```<code>ActiveSupport::Notifications.subscribe "start_processing.action_controller" do |**args|
  # your own custom stuff
end
</code>```

This way # your own custom stuff will start to fire before the before_action!

Title: rails dispatch event?

Body:
First off, I am totally new with gems and engines (eh. ruby);
I am writing a handy engine which is going to filter requests based on the rules the user(developer) defines, currently my approach is the following:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action { Acu::Monitor.new request }
end

And it works like a charm, but I want the engine to be plug-n-play with minimum configuration by the user, is there anyway I can achive this?

Can I get anywhere between dispatch and controller, where I can validate the request? Is there something like pre-dispatch-event in rails?

I would really appreciate if anyone help me on this, I got tired of google this, kind of ran out of query to write! :D

update:

requests has to be processed, i.e the target controller/action need to be determined by rails then I am processing the request.

Body:
I found the answer, it is the instrumentation that I was looking for

ActiveSupport::Notifications.subscribe "start_processing.action_controller" do |**args|
  # your own custom stuff
end

This way # your own custom stuff will start to fire before the before_action!


问:
Make this code non blocking
I'm using the VSphere API, here are the lines that I'm dealing with:

```<code>    task = vm.PowerOff()
    while task.info.state not in [vim.TaskInfo.State.success, vim.TaskInfo.State.error]:
        time.sleep(1)
        log.info("task {} is running".format(task))
    log.ingo("task {} is done".format(task))
</code>```

The problem here is that this blocks the execution completely whilst the task is not finished. I would like the logging part to be ran "in parallel", so I can start other tasks.

I thought about creating a function that would accept a task as parameter, and poll the info.state attribute just like now, but how do I make this non blocking ?

EDIT: I'm using Python 2.7

答:
Here is an example of using the threading module:

```<code>import threading

class VMShutdownThread(threading.Thread):
    def __init__(self, vm):
        self.vm = vm
    def run(self):
        task = vm.PowerOff()
        while task.info.state not in [vim.TaskInfo.State.success, vim.TaskInfo.State.error]:
            time.sleep(1)
            log.info("task {} is running".format(task))
        log.info("task {} is done".format(task))

vm_shutdown_thread = VMShutdownThread(vm)

vm_shutdown_thread.start()
</code>```

If you create a logger, you can configure it to print the thread name.

Title: Make this code non blocking

Body:
I'm using the VSphere API, here are the lines that I'm dealing with:

    task = vm.PowerOff()
    while task.info.state not in [vim.TaskInfo.State.success, vim.TaskInfo.State.error]:
        time.sleep(1)
        log.info("task {} is running".format(task))
    log.ingo("task {} is done".format(task))

The problem here is that this blocks the execution completely whilst the task is not finished. I would like the logging part to be ran "in parallel", so I can start other tasks.

I thought about creating a function that would accept a task as parameter, and poll the info.state attribute just like now, but how do I make this non blocking ?

EDIT: I'm using Python 2.7

Body:
Here is an example of using the threading module:

import threading

class VMShutdownThread(threading.Thread):
    def __init__(self, vm):
        self.vm = vm
    def run(self):
        task = vm.PowerOff()
        while task.info.state not in [vim.TaskInfo.State.success, vim.TaskInfo.State.error]:
            time.sleep(1)
            log.info("task {} is running".format(task))
        log.info("task {} is done".format(task))

vm_shutdown_thread = VMShutdownThread(vm)

vm_shutdown_thread.start()

If you create a logger, you can configure it to print the thread name.


问:
Why a NSTimer can be delayed in background mode?
My app run in background and uses NSTimer to launch audio after a certain amount of time. Me and my testers have no problems with this, and audio can be launched event after several hours in the background (>10h).

My issue is that some users reports that the audio is often delayed, sometimes by a few minutes, sometimes by an hour.

I do something like that:

```<code>UIApplication * app = [UIApplication sharedApplication];
  bgTask = [app beginBackgroundTaskWithExpirationHandler:nil];

dispatch_async(dispatch_get_main_queue(), ^{
    theTimer = [NSTimer scheduledTimerWithTimeInterval:[theDateIWant timeIntervalSinceNow] target:self selector:@selector(playAudio) userInfo:nil repeats:NO];
    });
</code>```

My questions are :

-Does a NSTimer can be delayed that much by the system ? if so how to go around this problem ?
-How to reproduce this kind of issues ?
- Is it safer to use the following ?

```<code>theTimer = [[NSTimer alloc] initWithFireDate:theDateIWant interval:0.0 target:self selector:@selector(playAudio) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:theTimer
                          forMode:NSDefaultRunLoopMode];
</code>```

Thanks for any help !

答:
It seems to me that you understand background tasks a little bit wrong.

When the first snippet is performed (I assume that you place it in the applicationDidEnterBackground method), it says the system

I have a small task to perform, please wait for a while till i finish
  it!

and the system will wait for about 5-10 minutes before suspend the application.

If you need kind of alarm, you can use LocalNotification to playback specific sound at specified time.

Body:
My app run in background and uses NSTimer to launch audio after a certain amount of time. Me and my testers have no problems with this, and audio can be launched event after several hours in the background (>10h).

My issue is that some users reports that the audio is often delayed, sometimes by a few minutes, sometimes by an hour.

I do something like that:

UIApplication * app = [UIApplication sharedApplication];
  bgTask = [app beginBackgroundTaskWithExpirationHandler:nil];

dispatch_async(dispatch_get_main_queue(), ^{
    theTimer = [NSTimer scheduledTimerWithTimeInterval:[theDateIWant timeIntervalSinceNow] target:self selector:@selector(playAudio) userInfo:nil repeats:NO];
    });

My questions are :

-Does a NSTimer can be delayed that much by the system ? if so how to go around this problem ?
-How to reproduce this kind of issues ?
- Is it safer to use the following ?

theTimer = [[NSTimer alloc] initWithFireDate:theDateIWant interval:0.0 target:self selector:@selector(playAudio) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:theTimer
                          forMode:NSDefaultRunLoopMode];

Thanks for any help !


问:
Can I embed a markdown file in a markdown file with Jekyll?
I am using Jekyll to generate a website.  Is it possible for a markdown file to include another markdown file?  This could be useful if, say, I want the same markdown text at the beginning of several pages.</p>

答:
Simply using include works:

```<code>{% include markdown_file.md %}
</code>```

Body:
Simply using include works:

{% include markdown_file.md %}


问:
is hadoop necessary for using Giraph
I want to use Giraph as a graph processing tool for my work. I am familiar with Mahout and I know I can use some parts of Mahout such as Recommender System without using Hadoop. However, I don't know if this is the same for Giraph and whether I can use it without using Hadoop. </p>

答:
You need the Hadoop dependency, but you do not need a Hadoop cluster, not even a pseudo-distributed one. Chapter 5 of the book Practical Graph Analytics with Apache Giraph shows an example for this - the source code is available on GitHub.

The following dependencies are required:

org.apache.giraph:giraph-core:1.1.0

org.apache.hadoop:hadoop-core:1.2.1

Implement your computation as a subclass of BasicComputation an run it as follows:

```<code>String[] graphSeed = new String[] { "seed\t0" }

GiraphConfiguration conf = new GiraphConfiguration();
conf.setComputationClass(GenerateTwitterParallel.class);
conf.setVertexInputFormatClass(
    TextDoubleDoubleAdjacencyListVertexInputFormat.class);
conf.setVertexOutputFormatClass(
    AdjacencyListTextVertexOutputFormat.class);
Iterable<String> results =
    InternalVertexRunner.run(conf, graphSeed);
</code>```

Title: is hadoop necessary for using Giraph

Body:
You need the Hadoop dependency, but you do not need a Hadoop cluster, not even a pseudo-distributed one. Chapter 5 of the book Practical Graph Analytics with Apache Giraph shows an example for this - the source code is available on GitHub.

The following dependencies are required:

org.apache.giraph:giraph-core:1.1.0

org.apache.hadoop:hadoop-core:1.2.1

Implement your computation as a subclass of BasicComputation an run it as follows:

String[] graphSeed = new String[] { "seed\t0" }

GiraphConfiguration conf = new GiraphConfiguration();
conf.setComputationClass(GenerateTwitterParallel.class);
conf.setVertexInputFormatClass(
    TextDoubleDoubleAdjacencyListVertexInputFormat.class);
conf.setVertexOutputFormatClass(
    AdjacencyListTextVertexOutputFormat.class);
Iterable<String> results =
    InternalVertexRunner.run(conf, graphSeed);


问:
Iterate over query for use in Charts.js using Coldfusion
I am trying to figure out how to loop over a query for use with Charts.JS.

The query:

```<code><cfquery name="bymonth" datasource="#application.dsn#">
SELECT DISTINCT r_vehicle, r_month, COUNT(*)
FROM rsvs
GROUP BY r_vehicle, r_month
ORDER BY r_vehicle, r_month;
</cfquery>
</code>```

That gives me data like this:

```<code>    r_vehicle   r_month COUNT(*)
1   Limo        01      2
2   Limo        02      1
3   Limo        05      1
4   Limo        07      3
5   Limo        08      3
6   Limo        09      3
7   Limo        11      2
8   Charter Bus 01      3
9   Charter Bus 02      2
10  Charter Bus 03      2
</code>```

The main excerpt from Chart.JS where I need to loop over this query:

```<code>            labels: ["January", "February", "March", "April", "May",
            "June", "July", "August", "September", "October", "November", "December"],
              {
                label: "r_vehicle",
                backgroundColor: window.chartColors.red,
                borderColor: window.chartColors.red,

                data: [

                (Number of times this vehicle was used per month -
                Displayed as:   3,6,5,2,3,7,9,2,3,8,3,2)

                ],
                fill: false,
            }
</code>```

For any months where r_vehicle was not used I need to insert a 'zero' (since they do not appear in the query results).

I have tried this a number of ways but its just a few notches over my paygrade!  Much appreciate any help.

UPDATE:  This should add the '0' when no vehicle was used in a given month:

```<code><cfquery name="bymonth2" datasource="#application.dsn#">
SELECT DISTINCT r_vehicle, r_month, IFNULL(count(r_vehicle),0) AS vehCount
FROM rsvs
GROUP BY r_vehicle, r_month
ORDER BY r_vehicle, r_month;
</cfquery>
</code>```

So, at this point I think I just need to know how to loop over the output data like this:

LIMO (r_vehicle)
2,1,0,0,1,0,3,3,3,0,2,0 (vehCount)

2nd Update:
I have the following code -

```<code><cfquery name="bymonthLimos" datasource="#application.dsn#">
SELECT DISTINCT r_vehicle, r_month, IFNULL(count(r_vehicle),0) AS vehCount
FROM rsvs
WHERE r_vehicle = 'Limo'
GROUP BY r_vehicle, r_month
ORDER BY r_vehicle, r_month
</cfquery>

<cfset MonthList = "01,02,03,04,05,06,07,08,09,10,11,12">
<cfset MonthValues = structNew()>
<cfloop list="#MonthList#" index="index" delimiters=",">
<cfset structInsert(MonthValues,"Month#index#", "0")>
</cfloop>

<cfoutput query="bymonthLimos">
<cfset MonthCount = ValueList(bymonth2.vehCount, ",")>
#r_vehicle# - #MonthCount#<br>
</cfoutput>
</code>```

I must be doing the output query wrong, this is what I'm getting:

Limo - 3,2,2,2,1,1,3,4,3,5,5,7,1,5,13,17,16,12,17,7,16,7,9,13,1,3,8,7,7,7,13,9,5,6,7,12,3,3,8,10,3,7,7,5,8,1,3,7,1,1,3,4,7,7,2,1,2,1,1,3,3,3,2,1,1,3,1,2,3,5,5,1,2,1,1,2,1,1,5,3,6,7,8,6,11,8,7,3

3rd Update    Changed code to this:

```<code><cfquery name="bymonthLimos" datasource="#application.dsn#">
SELECT DISTINCT r_vehicle, r_month, COUNT(*) as count
FROM rsvs
WHERE r_vehicle = 'Sedan'
GROUP BY r_vehicle, r_month
ORDER BY r_vehicle, r_month
</cfquery>

<cfset MonthList = "01,02,03,04,05,06,07,08,09,10,11,12">
<cfset MonthValues = structNew()>
<cfloop list="#MonthList#" index="index" delimiters=",">
<cfset structInsert(MonthValues,"Month#index#", "0")>
</cfloop>

<cfoutput query="bymonthLimos">
<cfset StructUpdate(MonthValues, "Month#r_month#", #count#)>
#r_vehicle# - #count#<br>
</cfoutput>
</code>```

Please note, i changed it from Limo to Sedan because Sedan is missing some months.  I am now getting:

Sedan - 1
Sedan - 1
Sedan - 3
Sedan - 1
Sedan - 2
Sedan - 3
Sedan - 5
Sedan - 5
Sedan - 1
Sedan - 2

Thank you TRose!!!

So, the two issues I see remaining:

1) I only need 'sedan' to be written once.
2) I need to fill in the missing months with a 'zero'

Update 4:

Thank you again so much TRose!

So, I now have the following code:

```<code><cfquery name="bymonthLimos" datasource="#application.dsn#">
SELECT DISTINCT r_vehicle, r_month, COUNT(*) as count
FROM rsvs
WHERE r_vehicle = 'Sedan'
GROUP BY r_vehicle, r_month
ORDER BY r_vehicle, r_month
</cfquery>

<cfset MonthList = "01,02,03,04,05,06,07,08,09,10,11,12">
<cfset MonthValues = createObject("java", "java.util.LinkedHashMap").init() />
<cfloop list="#MonthList#" index="index" delimiters=",">
<cfset structInsert(MonthValues,"Month#index#", "0")>
</cfloop>

OUTPUT:
<cfoutput>
<cfloop collection="#MonthValues#" item="key">
 #key#: #MonthValues[key]# <br />
</cfloop>
</cfoutput>
<br>

OUTPUT2:
<cfoutput>
<cfset step = 0>
<cfloop collection="#MonthValues#" item="key">
<cfset step++>#MonthValues[key]#<cfif step lt 12>,</cfif>
</cfloop>
</cfoutput>
<br>

OUTPUT3:
<cfoutput query="bymonthLimos">#r_vehicle# -
<cfset StructUpdate(MonthValues, "Month#r_month#", #count#)>
 #count#<br>
</cfoutput>
</code>```

RESULTS:

OUTPUT:  Month01: 0  Month02: 0  Month03: 0  Month04: 0  Month05: 0
  Month06: 0  Month07: 0  Month08: 0  Month09: 0  Month10: 0  Month11: 0
  Month12: 0

OUTPUT2: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

OUTPUT3:  Sedan - 1 Sedan - 1 Sedan - 3 Sedan - 1 Sedan - 2 Sedan - 3
  Sedan - 5 Sedan - 5 Sedan - 1 Sedan - 2

Obviously I'm missing something.  I'm playing around with it to see what i can do.

Update 5

This seems to be working, not sure what it was!

```<code> OUTPUT4:
<cfoutput>
#bymonthLimos.r_vehicle#
<cfset step = 0>
<cfloop collection="#MonthValues#" item="key">
<cfset step++>#MonthValues[key]#<cfif step lt 12>,</cfif>
</cfloop>
</cfoutput>
</code>```

RESULTS:

OUTPUT4: Sedan 1, 1, 3, 0, 0, 1, 2, 3, 5, 5, 1, 2

Yahoo!!!  Thank you again!!

Works great with the Chart.js script now!

```<code>data: [
<cfoutput>
<cfset step = 0>
<cfloop collection="#MonthValues#" item="key">
<cfset step++>#MonthValues[key]#<cfif step lt 12>,</cfif>
</cfloop>
</cfoutput>
                ],
</code>```

Just wanted to point out some things:

1) The CFOUTPUT stuff (not the ones in the Charts.JS tag) I had to put in CFSILENT tags or the data shows up in HTML.

2) The DB must have the month formatted as MM and not just M.

答:
Using your existing table, another approach is to use a "numbers table" to generate the missing months. There are different ways to implement it: as a physical table, derived table, or CTE. (MySQL does not yet support CTE's, but you could easily do something similar using a VIEW). Then use the numbers table with an OUTER JOIN to fill in any missing month numbers:

NB: Assuming the table contains a "Year" column, you may want to filter the derived query on year number as well.

```<code>SELECT mo.Num AS MonthNum, COALESCE(res.ReservationCount, 0) AS ReservationCount
FROM  YourNumbersTable mo LEFT JOIN
      (
          SELECT r_month, COUNT(*) as ReservationCount
          FROM   rsvs
          WHERE  r_vehicle = <cfqueryparam value="Limos" cfsqltype="cf_sql_varchar">
          GROUP BY r_month
      )
      res ON res.r_month = mo.Num
WHERE  mo.Num BETWEEN 1 AND 12
ORDER BY mo.Num
</code>```

Then a simple ValueList() generates the list of values to use in your chart:

```<code>  <cfoutput>
   datasets: [{
          label: 'Limos',
          data: [ #ValueList(yourLimoQuery.ReservationCount)# ]
   ]
   ...
  </cfoutput>
</code>```

As an aside, you might also consider normalizing the table to help ensure data integrity and improve performance. Create a separate table for unique vehicle types:

```<code>CREATE TABLE Vehicle (
  VehicleID INT NOT NULL,
  VehicleName VARCHAR(100) NULL,
  PRIMARY KEY (VehicleID)
);
</code>```

Then store the vehicle "ID" (not "name") in the reservations table. For greater flexibility in reporting/charting queries, store a full "date", rather than just month/year number.

```<code>CREATE TABLE VehicleReservation (
  VehicleReservationID INT AUTO_INCREMENT,
  VehicleID INT NULL,
  ReservationDate DATETIME NULL,
   PRIMARY KEY (VehicleReservationID),
   KEY VehicleID (VehicleID),
  CONSTRAINT fKVehicleReservation_VehicleID FOREIGN KEY (VehicleID) REFERENCES vehicle (VehicleID)
);
</code>```

Body:
I am trying to figure out how to loop over a query for use with Charts.JS.

The query:

<cfquery name="bymonth" datasource="#application.dsn#">
SELECT DISTINCT r_vehicle, r_month, COUNT(*)
FROM rsvs
GROUP BY r_vehicle, r_month
ORDER BY r_vehicle, r_month;
</cfquery>

That gives me data like this:

    r_vehicle   r_month COUNT(*)
1   Limo        01      2
2   Limo        02      1
3   Limo        05      1
4   Limo        07      3
5   Limo        08      3
6   Limo        09      3
7   Limo        11      2
8   Charter Bus 01      3
9   Charter Bus 02      2
10  Charter Bus 03      2

The main excerpt from Chart.JS where I need to loop over this query:

            labels: ["January", "February", "March", "April", "May",
            "June", "July", "August", "September", "October", "November", "December"],
              {
                label: "r_vehicle",
                backgroundColor: window.chartColors.red,
                borderColor: window.chartColors.red,

                data: [

                (Number of times this vehicle was used per month -
                Displayed as:   3,6,5,2,3,7,9,2,3,8,3,2)

                ],
                fill: false,
            }

For any months where r_vehicle was not used I need to insert a 'zero' (since they do not appear in the query results).

I have tried this a number of ways but its just a few notches over my paygrade!  Much appreciate any help.

UPDATE:  This should add the '0' when no vehicle was used in a given month:

<cfquery name="bymonth2" datasource="#application.dsn#">
SELECT DISTINCT r_vehicle, r_month, IFNULL(count(r_vehicle),0) AS vehCount
FROM rsvs
GROUP BY r_vehicle, r_month
ORDER BY r_vehicle, r_month;
</cfquery>

So, at this point I think I just need to know how to loop over the output data like this:

LIMO (r_vehicle)
2,1,0,0,1,0,3,3,3,0,2,0 (vehCount)

2nd Update:
I have the following code -

<cfquery name="bymonthLimos" datasource="#application.dsn#">
SELECT DISTINCT r_vehicle, r_month, IFNULL(count(r_vehicle),0) AS vehCount
FROM rsvs
WHERE r_vehicle = 'Limo'
GROUP BY r_vehicle, r_month
ORDER BY r_vehicle, r_month
</cfquery>

<cfset MonthList = "01,02,03,04,05,06,07,08,09,10,11,12">
<cfset MonthValues = structNew()>
<cfloop list="#MonthList#" index="index" delimiters=",">
<cfset structInsert(MonthValues,"Month#index#", "0")>
</cfloop>

<cfoutput query="bymonthLimos">
<cfset MonthCount = ValueList(bymonth2.vehCount, ",")>
#r_vehicle# - #MonthCount#

</cfoutput>

I must be doing the output query wrong, this is what I'm getting:

Limo - 3,2,2,2,1,1,3,4,3,5,5,7,1,5,13,17,16,12,17,7,16,7,9,13,1,3,8,7,7,7,13,9,5,6,7,12,3,3,8,10,3,7,7,5,8,1,3,7,1,1,3,4,7,7,2,1,2,1,1,3,3,3,2,1,1,3,1,2,3,5,5,1,2,1,1,2,1,1,5,3,6,7,8,6,11,8,7,3

3rd Update    Changed code to this:

<cfquery name="bymonthLimos" datasource="#application.dsn#">
SELECT DISTINCT r_vehicle, r_month, COUNT(*) as count
FROM rsvs
WHERE r_vehicle = 'Sedan'
GROUP BY r_vehicle, r_month
ORDER BY r_vehicle, r_month
</cfquery>

<cfset MonthList = "01,02,03,04,05,06,07,08,09,10,11,12">
<cfset MonthValues = structNew()>
<cfloop list="#MonthList#" index="index" delimiters=",">
<cfset structInsert(MonthValues,"Month#index#", "0")>
</cfloop>

<cfoutput query="bymonthLimos">
<cfset StructUpdate(MonthValues, "Month#r_month#", #count#)>
#r_vehicle# - #count#

</cfoutput>

Please note, i changed it from Limo to Sedan because Sedan is missing some months.  I am now getting:

Sedan - 1
Sedan - 1
Sedan - 3
Sedan - 1
Sedan - 2
Sedan - 3
Sedan - 5
Sedan - 5
Sedan - 1
Sedan - 2

Thank you TRose!!!

So, the two issues I see remaining:

1) I only need 'sedan' to be written once.
2) I need to fill in the missing months with a 'zero'

Update 4:

Thank you again so much TRose!

So, I now have the following code:

<cfquery name="bymonthLimos" datasource="#application.dsn#">
SELECT DISTINCT r_vehicle, r_month, COUNT(*) as count
FROM rsvs
WHERE r_vehicle = 'Sedan'
GROUP BY r_vehicle, r_month
ORDER BY r_vehicle, r_month
</cfquery>

<cfset MonthList = "01,02,03,04,05,06,07,08,09,10,11,12">
<cfset MonthValues = createObject("java", "java.util.LinkedHashMap").init() />
<cfloop list="#MonthList#" index="index" delimiters=",">
<cfset structInsert(MonthValues,"Month#index#", "0")>
</cfloop>

OUTPUT:
<cfoutput>
<cfloop collection="#MonthValues#" item="key">
 #key#: #MonthValues[key]#

</cfloop>
</cfoutput>

OUTPUT2:
<cfoutput>
<cfset step = 0>
<cfloop collection="#MonthValues#" item="key">
<cfset step++>#MonthValues[key]#<cfif step lt 12>,</cfif>
</cfloop>
</cfoutput>

OUTPUT3:
<cfoutput query="bymonthLimos">#r_vehicle# -
<cfset StructUpdate(MonthValues, "Month#r_month#", #count#)>
 #count#

</cfoutput>

RESULTS:

OUTPUT:  Month01: 0  Month02: 0  Month03: 0  Month04: 0  Month05: 0
  Month06: 0  Month07: 0  Month08: 0  Month09: 0  Month10: 0  Month11: 0
  Month12: 0

OUTPUT2: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

OUTPUT3:  Sedan - 1 Sedan - 1 Sedan - 3 Sedan - 1 Sedan - 2 Sedan - 3
  Sedan - 5 Sedan - 5 Sedan - 1 Sedan - 2

Obviously I'm missing something.  I'm playing around with it to see what i can do.

Update 5

This seems to be working, not sure what it was!

 OUTPUT4:
<cfoutput>
#bymonthLimos.r_vehicle#
<cfset step = 0>
<cfloop collection="#MonthValues#" item="key">
<cfset step++>#MonthValues[key]#<cfif step lt 12>,</cfif>
</cfloop>
</cfoutput>

RESULTS:

OUTPUT4: Sedan 1, 1, 3, 0, 0, 1, 2, 3, 5, 5, 1, 2

Yahoo!!!  Thank you again!!

Works great with the Chart.js script now!

data: [
<cfoutput>
<cfset step = 0>
<cfloop collection="#MonthValues#" item="key">
<cfset step++>#MonthValues[key]#<cfif step lt 12>,</cfif>
</cfloop>
</cfoutput>
                ],

Just wanted to point out some things:

1) The CFOUTPUT stuff (not the ones in the Charts.JS tag) I had to put in CFSILENT tags or the data shows up in HTML.

2) The DB must have the month formatted as MM and not just M.

Body:
Using your existing table, another approach is to use a "numbers table" to generate the missing months. There are different ways to implement it: as a physical table, derived table, or CTE. (MySQL does not yet support CTE's, but you could easily do something similar using a VIEW). Then use the numbers table with an OUTER JOIN to fill in any missing month numbers:

NB: Assuming the table contains a "Year" column, you may want to filter the derived query on year number as well.

SELECT mo.Num AS MonthNum, COALESCE(res.ReservationCount, 0) AS ReservationCount
FROM  YourNumbersTable mo LEFT JOIN
      (
          SELECT r_month, COUNT(*) as ReservationCount
          FROM   rsvs
          WHERE  r_vehicle = <cfqueryparam value="Limos" cfsqltype="cf_sql_varchar">
          GROUP BY r_month
      )
      res ON res.r_month = mo.Num
WHERE  mo.Num BETWEEN 1 AND 12
ORDER BY mo.Num

Then a simple ValueList() generates the list of values to use in your chart:

  <cfoutput>
   datasets: [{
          label: 'Limos',
          data: [ #ValueList(yourLimoQuery.ReservationCount)# ]
   ]
   ...
  </cfoutput>

As an aside, you might also consider normalizing the table to help ensure data integrity and improve performance. Create a separate table for unique vehicle types:

CREATE TABLE Vehicle (
  VehicleID INT NOT NULL,
  VehicleName VARCHAR(100) NULL,
  PRIMARY KEY (VehicleID)
);

Then store the vehicle "ID" (not "name") in the reservations table. For greater flexibility in reporting/charting queries, store a full "date", rather than just month/year number.

CREATE TABLE VehicleReservation (
  VehicleReservationID INT AUTO_INCREMENT,
  VehicleID INT NULL,
  ReservationDate DATETIME NULL,
   PRIMARY KEY (VehicleReservationID),
   KEY VehicleID (VehicleID),
  CONSTRAINT fKVehicleReservation_VehicleID FOREIGN KEY (VehicleID) REFERENCES vehicle (VehicleID)
);


问:
How to make a shopify API request inside webhook callback script
I am writing my first Shopify app that will unpublish a product once its inventory level goes below threshold.

For that I register a webhook with callback URL http://example.com/script.php that will be called by Shopify once product update event occurs.

In script.php how do I obtain Shopify API token to make PUT request to products/update to unpublish it?

Here is my script.php so far (I know I am missing hmac validation but that is not the point):

```<code><?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
  session_start();
  require 'shopify.php';
  $api_key = 'api_key';
  $secret = 'secret';
  $sc = new ShopifyClient($_SERVER['HTTP_X_SHOPIFY_SHOP_DOMAIN'], $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'], $api_key, $secret);
  $inventory = $_POST['inventory_quantity'];
  $old_inventory = $_POST['old_inventory_quantity'];
  if($inventory <= 0){
    $args = array("product" => array("id" => $_SERVER['HTTP_X_SHOPIFY_PRODUCT_ID'], "published" => false));
    $sc->call("PUT","/admin/products/".$_SERVER['HTTP_X_SHOPIFY_PRODUCT_ID'].".json",$args);
  }
}
</code>```

I am trying to use $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'] but obviously that is wrong.

答:
Shopify sends you the name of the shop in the header of every webhook. So your webhook can now authenticate the incoming call, and with the shop name, you simply query your persistence layer for the matching shop credentials. If you find the shop, you can open up an API session very easily, since you have the two things you need:

shopify domain name of the store

shopify access token

Note that a better way to hide products is to consider listening to the orders webhooks, which provide orders and products, and then query the inventory level of the product sold. Working off of product/update webhooks could be super obnoxious in terms of the number of calls you might have to process in comparison to orders.

Body:
I am writing my first Shopify app that will unpublish a product once its inventory level goes below threshold.

For that I register a webhook with callback URL http://example.com/script.php that will be called by Shopify once product update event occurs.

In script.php how do I obtain Shopify API token to make PUT request to products/update to unpublish it?

Here is my script.php so far (I know I am missing hmac validation but that is not the point):

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
  session_start();
  require 'shopify.php';
  $api_key = 'api_key';
  $secret = 'secret';
  $sc = new ShopifyClient($_SERVER['HTTP_X_SHOPIFY_SHOP_DOMAIN'], $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'], $api_key, $secret);
  $inventory = $_POST['inventory_quantity'];
  $old_inventory = $_POST['old_inventory_quantity'];
  if($inventory <= 0){
    $args = array("product" => array("id" => $_SERVER['HTTP_X_SHOPIFY_PRODUCT_ID'], "published" => false));
    $sc->call("PUT","/admin/products/".$_SERVER['HTTP_X_SHOPIFY_PRODUCT_ID'].".json",$args);
  }
}

I am trying to use $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'] but obviously that is wrong.


问:
Android ADT Plugin doesn't show up in Eclipse
I'm using Windows 7 and installed the 64 bit version of Eclipse 3.5.2.  I then installed the Android ADT plugin, but when I try to configure it in the Windows > Preferences dialog, the Android Plugin doesn't show up in the left pane.  Instead I see DDMS.  This prevents me from specifying the location of the Android SDK (unless there is another way) to give me the appropriate templates and such.

Someone posted a fix to this that includes setting the permissions of Eclipse, but that didn't work for me.  I tried installing the Android Plugin from both online installation (thru the URL install) and the offline Archive method.

答: If you're running Windows Vista or 7, make sure you right-click Eclipse and RUN AS ADMINISTRATOR. I literally spent six hours figuring this out, and this was what fixed it.</p>


问:
iOS - Map a root JSON array with ObjectMapper in swift
I use the library ObjectMapper to map json with my objects but I have some issues to map a root json Array.

This is the received json :

```<code>[
   {
       CustomerId = "A000015",
       ...
   },
   {
       CustomerId = "A000016",
       ...
   },
   {
       CustomerId = "A000017",
       ...
   }
]
</code>```

This is my object

```<code>class Customer : Mappable
{
    var CustomerId : String? = nil

    class func newInstance(map: Map) -> Mappable? {
        return Customer()
    }

    func mapping(map: Map) {
        CustomerId   <- map["CustomerId"]
    }
}
</code>```

I map the json in my controller with

```<code>let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSArray

if (error != nil) {
    return completionHandler(nil, error)
} else {
    var customers = Mapper<Customer>().map(json)
}
</code>```

But it doesn't work, I tried Mapper<[Customer]>().map(json) but it doesn't work too.
Finally I tried to create a new swift object CustomerList containing a Customer array but it doesn't work.

Do you have an idea of how to map json of a root array ?

Thanks.

答:
In the same situation in my recent Swift 3, able to solve to get object mapper present in Array as root.

First convert json string into a Object Using serialization.

```<code>let parsedMapperString = Mapper<Customer>.parseJSONString(JSONString: result) //result is string from json serializer
</code>```

Then you can get Customer DTO from the MapSet of JSON dictionary to an array of Mappable objects.

```<code>let customerDto = Mapper<Customer>().mapSet(JSONArray: jsonParsed as! [[String : Any]])
</code>```

Hope it helps. Thanks to @Nicolas who pushed me close to get solution.

Body:
I use the library ObjectMapper to map json with my objects but I have some issues to map a root json Array.

This is the received json :

[
   {
       CustomerId = "A000015",
       ...
   },
   {
       CustomerId = "A000016",
       ...
   },
   {
       CustomerId = "A000017",
       ...
   }
]

This is my object

class Customer : Mappable
{
    var CustomerId : String? = nil

    class func newInstance(map: Map) -> Mappable? {
        return Customer()
    }

    func mapping(map: Map) {
        CustomerId   <- map["CustomerId"]
    }
}

I map the json in my controller with

let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSArray

if (error != nil) {
    return completionHandler(nil, error)
} else {
    var customers = Mapper<Customer>().map(json)
}

But it doesn't work, I tried Mapper<[Customer]>().map(json) but it doesn't work too.
Finally I tried to create a new swift object CustomerList containing a Customer array but it doesn't work.

Do you have an idea of how to map json of a root array ?

Thanks.

Body:
In the same situation in my recent Swift 3, able to solve to get object mapper present in Array as root.

First convert json string into a Object Using serialization.

let parsedMapperString = Mapper<Customer>.parseJSONString(JSONString: result) //result is string from json serializer

Then you can get Customer DTO from the MapSet of JSON dictionary to an array of Mappable objects.

let customerDto = Mapper<Customer>().mapSet(JSONArray: jsonParsed as! [[String : Any]])

Hope it helps. Thanks to @Nicolas who pushed me close to get solution.


问:
Ruby - converting a string into hash with each character as key and index as value?
I am trying to transform a given string into a hash with each its character = key and index = value.

For example, if I have str = "hello", I would like it to transform into {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}.

I created a method as such:

```<code>def map_indices(arr)
  arr.map.with_index {|el, index| [el, index]}.to_h
end
#=> map_indices('hello'.split(''))
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}
</code>```

The problem is it skips the first l. If I reverse the order of el and index:   arr.map.with_index {|el, index| [index, el]}.to_h, I get all the letters spelled out: {0=>"h", 1=>"e", 2=>"l", 3=>"l", 4=>"o"}

But when I invert it, I get the same hash that skips one of the l's.

```<code>map_indices('hello'.split('')).invert
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}
</code>```

Why is this behaving like such? How can I get it to print {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}?

答:
Any of the following could be used. For

```<code>str = "hello"
</code>```

all return

```<code>{"h"=>[0], "e"=>[1], "l"=>[2, 3], "o"=>[4]}
</code>```

```<code>str.each_char
   .with_index
   .with_object({}) { |(c,i),h| (h[c] ||= []) << i }
</code>```

See String#each_char, Enumerator#with_index and Enumerator#with_object. The block variables have been written to exploit array decomposition.

```<code>str.each_char
   .with_index
   .with_object(Hash.new { |h,k| h[k] = [] }) { |(c,i),h| h[c] << i }
</code>```

See the form of Hash::new that takes a block and no argument. If a hash has been defined

```<code>h = Hash.new { |h,k| h[k] = [] }
</code>```

and later

```<code>h[c] << i
</code>```

is executed, h[c] is first set equal to an empty array if h does not have a key c.

```<code>str.size
   .times
   .with_object(Hash.new { |h,k| h[k] = [] }) { |i,h| h[str[i]] << i }
</code>```

```<code>str.each_char
   .with_index
   .group_by(&:first)
   .transform_values { |a| a.flat_map(&:last) }
</code>```

See Enumerable#group_by, Hash#transform_values (introduced in Ruby v2.5) and Enumerable#flat_map.

Note that

```<code>str.each_char
   .with_index
   .group_by(&:first)
  #=> {"h"=>[["h", 0]], "e"=>[["e", 1]], "l"=>[["l", 2], ["l", 3]],
  #    "o"=>[["o", 4]]}
</code>```

Body:
I am trying to transform a given string into a hash with each its character = key and index = value.

For example, if I have str = "hello", I would like it to transform into {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}.

I created a method as such:

def map_indices(arr)
  arr.map.with_index {|el, index| [el, index]}.to_h
end
#=> map_indices('hello'.split(''))
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}

The problem is it skips the first l. If I reverse the order of el and index:   arr.map.with_index {|el, index| [index, el]}.to_h, I get all the letters spelled out: {0=>"h", 1=>"e", 2=>"l", 3=>"l", 4=>"o"}

But when I invert it, I get the same hash that skips one of the l's.

map_indices('hello'.split('')).invert
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}

Why is this behaving like such? How can I get it to print {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}?

Body:
Any of the following could be used. For

str = "hello"

all return

{"h"=>[0], "e"=>[1], "l"=>[2, 3], "o"=>[4]}

str.each_char
   .with_index
   .with_object({}) { |(c,i),h| (h[c] ||= []) << i }

See String#each_char, Enumerator#with_index and Enumerator#with_object. The block variables have been written to exploit array decomposition.

str.each_char
   .with_index
   .with_object(Hash.new { |h,k| h[k] = [] }) { |(c,i),h| h[c] << i }

See the form of Hash::new that takes a block and no argument. If a hash has been defined

h = Hash.new { |h,k| h[k] = [] }

and later

h[c] << i

is executed, h[c] is first set equal to an empty array if h does not have a key c.

str.size
   .times
   .with_object(Hash.new { |h,k| h[k] = [] }) { |i,h| h[str[i]] << i }

str.each_char
   .with_index
   .group_by(&:first)
   .transform_values { |a| a.flat_map(&:last) }

See Enumerable#group_by, Hash#transform_values (introduced in Ruby v2.5) and Enumerable#flat_map.

Note that

str.each_char
   .with_index
   .group_by(&:first)
  #=> {"h"=>[["h", 0]], "e"=>[["e", 1]], "l"=>[["l", 2], ["l", 3]],
  #    "o"=>[["o", 4]]}


问:
App slow down when I click on options menu
I am working on and Android app, the main page has map fragment and some animations, when I click on options menu everything gets slow and paused for a second before the menu show up, and when I select an item from the menu same thing happens for a second until changes committed.
I use the menu to change Map type (standard, Satellite, Terrain)
Can I add a loading or progress bar before and after calling the menu options method everytime onOptionsItemSelected?</p>

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.first:
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            break;
        case R.id.second:
            mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            break;
    }
    return super.onOptionsItemSelected(item);
}
</code>```

答:
Try:
1. Remove MapStyleOptions styleOptions;
2. Clear map before changing type</p>

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    //Add menu handling code
    switch (id) {
        case R.id.first:
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            break;
        case R.id.second:
            mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            break;
    }
    return super.onOptionsItemSelected(item);
}
</code>```

Body:
I am working on and Android app, the main page has map fragment and some animations, when I click on options menu everything gets slow and paused for a second before the menu show up, and when I select an item from the menu same thing happens for a second until changes committed.
I use the menu to change Map type (standard, Satellite, Terrain)
Can I add a loading or progress bar before and after calling the menu options method everytime onOptionsItemSelected?

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.first:
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            break;
        case R.id.second:
            mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            break;
    }
    return super.onOptionsItemSelected(item);
}

Body:
Try:
1. Remove MapStyleOptions styleOptions;
2. Clear map before changing type

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    //Add menu handling code
    switch (id) {
        case R.id.first:
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            break;
        case R.id.second:
            mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            break;
    }
    return super.onOptionsItemSelected(item);
}


问:
JSDoc generated online
Is there a way to generate html from jsdocs online or with a standalone tool? I have created an internal JS library and documented it with JSDoc specifications and would now like to generate documentation to share with my team. I can't, for reasons I won't get into, install the jsdoc npm package like I would at home.

So is there a way to generate the html documentation (or similar) without installing JSDoc?

答:
If you need JSDoc documentation, you need to install or copy over JSDoc package. As the package is JavaScript based, you need to have node.js installed on your computer prior, as JS runtime environment. If you have node.js installed on your work computer you may install the package

```<code>npm install -g jsdoc
</code>```

or just copy (from your home computer) "node_modules/.bin" and "node_modules/jsdoc" folders to anywhere on your work computer. After generate your documentation by using command line

```<code>.bin/jsdoc path/to/file.js
</code>```

More information on the topic is over here: How do I use JSDoc on Windows?.

Note: I am not aware any online service to generate JS Documentation, but even if I would, I wouldn't advise you to use it. The script which you wrote is ypur (or your company) intellectual property and send it to any 3rd party service, even to generate documentation sounds weird. I would generate documentation at home and bring it to work in your case.

Title: JSDoc generated online

Body:
If you need JSDoc documentation, you need to install or copy over JSDoc package. As the package is JavaScript based, you need to have node.js installed on your computer prior, as JS runtime environment. If you have node.js installed on your work computer you may install the package

npm install -g jsdoc

or just copy (from your home computer) "node_modules/.bin" and "node_modules/jsdoc" folders to anywhere on your work computer. After generate your documentation by using command line

.bin/jsdoc path/to/file.js

More information on the topic is over here: How do I use JSDoc on Windows?.

Note: I am not aware any online service to generate JS Documentation, but even if I would, I wouldn't advise you to use it. The script which you wrote is ypur (or your company) intellectual property and send it to any 3rd party service, even to generate documentation sounds weird. I would generate documentation at home and bring it to work in your case.


问:
How to add and remove class from a matched element?
This is the basic html structure:

```<code><div class="modern">
  <button type="button">Modern</button>
</div>
<div class="recent">
  <button type="button"><Recent</button>
</div>

<svg>
  <path class="modern">A</path>
  <path class="recent">B</path>
  <path class="recent">C</path>
  <path class="modern">D</path>
  <path class="recent">E</path>
</svg>
</code>```

Then on js once I click I check if any path has the same class as per the .parent of the clicked element, and if so add a class fadeIn to each matched element and fade it in sequentially. If not, add a class FadeOut and fade out the paths sequentially.

```<code>$("button").on("click", function() {
  $(this).addClass("active");
  var periodClass = $(this).parent().attr("class");
  var gapBetweenEach = 200;
  var speedOfFade = 400;
  $("svg path").each(function(i, path) {
    var cl = $(this).attr('class');
    $(this).attr('class', cl.includes(periodClass) ? cl + ' fadeIn' : cl.replace(/fadeIn/g, 'fadeOut'))
    $(".fadeIn").delay(gapBetweenEach * i).fadeIn(speedOfFade);
    $(".fadeOut").delay(gapBetweenEach * i).fadeOut(speedOfFade);
  });
});
</code>```

The above works but when I start clicking on the different buttons the classes keeps been added and the whole logic of fadeIn and fadeOut sequentially gets broken.

These are the classes I get after a few clicks

```<code>fadeOut fadeOut fadeIn
</code>```

答:
You can jQuery .hasClass(), .addClass() and .removeClass() methods

```<code>$("svg path").each(function(i, path) {
    var elem = $(this);
    if (elem.hasClass(periodClass)) {
        elem.removeClass('fadeOut').addClass('fadeIn');
    } else {
        elem.removeClass('fadeIn').addClass('fadeOut');
    }

    //Rest of your code ...
    $(".fadeIn").delay(gapBetweenEach * i).fadeIn(speedOfFade);
    $(".fadeOut").delay(gapBetweenEach * i).fadeOut(speedOfFade);
});
</code>```

Body:
This is the basic html structure:

  <button type="button">Modern</button>

  <button type="button"><Recent</button>

<svg>
  <path class="modern">A</path>
  <path class="recent">B</path>
  <path class="recent">C</path>
  <path class="modern">D</path>
  <path class="recent">E</path>
</svg>

Then on js once I click I check if any path has the same class as per the .parent of the clicked element, and if so add a class fadeIn to each matched element and fade it in sequentially. If not, add a class FadeOut and fade out the paths sequentially.

$("button").on("click", function() {
  $(this).addClass("active");
  var periodClass = $(this).parent().attr("class");
  var gapBetweenEach = 200;
  var speedOfFade = 400;
  $("svg path").each(function(i, path) {
    var cl = $(this).attr('class');
    $(this).attr('class', cl.includes(periodClass) ? cl + ' fadeIn' : cl.replace(/fadeIn/g, 'fadeOut'))
    $(".fadeIn").delay(gapBetweenEach * i).fadeIn(speedOfFade);
    $(".fadeOut").delay(gapBetweenEach * i).fadeOut(speedOfFade);
  });
});

The above works but when I start clicking on the different buttons the classes keeps been added and the whole logic of fadeIn and fadeOut sequentially gets broken.

These are the classes I get after a few clicks

fadeOut fadeOut fadeIn

Body:
You can jQuery .hasClass(), .addClass() and .removeClass() methods

$("svg path").each(function(i, path) {
    var elem = $(this);
    if (elem.hasClass(periodClass)) {
        elem.removeClass('fadeOut').addClass('fadeIn');
    } else {
        elem.removeClass('fadeIn').addClass('fadeOut');
    }

    //Rest of your code ...
    $(".fadeIn").delay(gapBetweenEach * i).fadeIn(speedOfFade);
    $(".fadeOut").delay(gapBetweenEach * i).fadeOut(speedOfFade);
});


问:
Force Scrollbars Images CSS
How would I accomplish the following without the use of tables?

If I don't wrap the imgs in tds the scroll bars aren't forced.

The imgs are pushed down like regular text with out the tds.

I have tried setting the imgs to display:block, inline-block and a couple other ideas but I'm clueless.

http://jsfiddle.net/zjews/

Edit: I could apply inline-table to the wrapped "a" links but unfortunately internet explorer doesn't support this property.  Does anyone know of a way to emulate inline-table in internet explorer.

答: Wrap the images in container elements such as divs. Apply overflow: auto; width: 200px; height: 200px; to those containers, for example.

Title: Force Scrollbars Images CSS


问:
How to set a default value for a Google places API auto complete textbox
I'm working on a page close enough to the one in google samples https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform and it works fine.

However I need to add one more feature is to set the value of the autocomplete by default to be the current user city.

I'm using the following code to get the city and the country of the logged in user using geolocation API in HTML5. However the challenge is to make the autocomplete accept this value as it's default value. When I try to put the value in the textbox directly the autocomplete consider it as a wrong value.

```<code>navigator.geolocation.getCurrentPosition(function(pos) {
   var currentLocation = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
   var geocoder = new google.maps.Geocoder();
   var city = "";
   var country = "";
   geocoder.geocode({'latLng': currentLocation}, function(results, status, from) {
      if (status == google.maps.GeocoderStatus.OK) {
         if (results[1]) {
            for (var i = 0; i < results[0].address_components.length; i++) {
               for (var b = 0; b < results[0].address_components[i].types.length; b++) {
                  if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                     city = results[0].address_components[i];
                     break;
                  }
                  if (results[0].address_components[i].types[b] == "country") {
                     country = results[0].address_components[i];
                     break;
                  }
               }
            }
            var fromDefault = city.long_name + " - " + country.long_name;
            $('#address-from').val(fromDefault);
         }
      }
   });
},
function(error) {
   alert('Unable to get location: ' + error.message);
}, options);
</code>```

Any idea how to manually fill in the default value for the autocomplete places textbox?

答:
I had the same requirement of setting the initial location when the Map initally loads.

This is how I did it:

As Jon Hannah mentioned, I used the Autocomplete Service to get the prediction, then used the first prediction to get the Place (using place_id). Populated the Autocompelete input with my default location string.
Finally triggered the place_change event.

```<code>  this.input.nativeElement.value = this.testLocationStr;

  let autocompleteService = new google.maps.places.AutocompleteService();
  let request = {input: this.testLocationStr};
  autocompleteService.getPlacePredictions(request, (predictionsArr, placesServiceStatus) => {
    console.log('getting place predictions :: predictionsArr = ', predictionsArr, '\n',
      'placesServiceStatus = ', placesServiceStatus);

    let placeRequest = {placeId: predictionsArr[0].place_id};
    let placeService = new google.maps.places.PlacesService(this.mapObj);
    placeService.getDetails(placeRequest, (placeResult, placeServiceStatus) => {
      console.log('placeService :: placeResult = ', placeResult, '\n',
        'placeServiceStatus = ', placeServiceStatus);

      this._handlePlaceChange(placeResult);

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

Plunker: https://plnkr.co/edit/9oN6Kg?p=preview

Body:
I'm working on a page close enough to the one in google samples https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform and it works fine.

However I need to add one more feature is to set the value of the autocomplete by default to be the current user city.

I'm using the following code to get the city and the country of the logged in user using geolocation API in HTML5. However the challenge is to make the autocomplete accept this value as it's default value. When I try to put the value in the textbox directly the autocomplete consider it as a wrong value.

navigator.geolocation.getCurrentPosition(function(pos) {
   var currentLocation = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
   var geocoder = new google.maps.Geocoder();
   var city = "";
   var country = "";
   geocoder.geocode({'latLng': currentLocation}, function(results, status, from) {
      if (status == google.maps.GeocoderStatus.OK) {
         if (results[1]) {
            for (var i = 0; i < results[0].address_components.length; i++) {
               for (var b = 0; b < results[0].address_components[i].types.length; b++) {
                  if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                     city = results[0].address_components[i];
                     break;
                  }
                  if (results[0].address_components[i].types[b] == "country") {
                     country = results[0].address_components[i];
                     break;
                  }
               }
            }
            var fromDefault = city.long_name + " - " + country.long_name;
            $('#address-from').val(fromDefault);
         }
      }
   });
},
function(error) {
   alert('Unable to get location: ' + error.message);
}, options);

Any idea how to manually fill in the default value for the autocomplete places textbox?

Body:
I had the same requirement of setting the initial location when the Map initally loads.

This is how I did it:

As Jon Hannah mentioned, I used the Autocomplete Service to get the prediction, then used the first prediction to get the Place (using place_id). Populated the Autocompelete input with my default location string.
Finally triggered the place_change event.

  this.input.nativeElement.value = this.testLocationStr;

  let autocompleteService = new google.maps.places.AutocompleteService();
  let request = {input: this.testLocationStr};
  autocompleteService.getPlacePredictions(request, (predictionsArr, placesServiceStatus) => {
    console.log('getting place predictions :: predictionsArr = ', predictionsArr, '\n',
      'placesServiceStatus = ', placesServiceStatus);

    let placeRequest = {placeId: predictionsArr[0].place_id};
    let placeService = new google.maps.places.PlacesService(this.mapObj);
    placeService.getDetails(placeRequest, (placeResult, placeServiceStatus) => {
      console.log('placeService :: placeResult = ', placeResult, '\n',
        'placeServiceStatus = ', placeServiceStatus);

      this._handlePlaceChange(placeResult);

    });
  });

Plunker: https://plnkr.co/edit/9oN6Kg?p=preview


问:
Removed header menu but space remains?
I have a centralised logoo with the menu underneath, I 'hid' the menu links but now the space remains where they where, leaving an awkward 20/25px space underneath my logo.

I could put padding-top on my logo to even it out but I don't think that's a very future-proof way to do it (mess with different screen sizes).

Can anyone offer a simple solution? Thanks

答:
How are you hiding the menu links?

Try setting "display:none" to hide and set "display:block" to show.

If you are trying to hide the links using "visibility:hidden" it means the tag would not be visible, but space will be allocated for it on the page.

Please post your code for more details if this doesn't help.

Title: Removed header menu but space remains?


问:
Video Download in Apple tvOS
I am a newbie to swift and tvOS.I want to download a video  from the url and display it in the ViewController. while i try with the ios Devices the video is downloaded and works fine.But with the tvOS the Video is not downloaded.

why is it so..?

How can i download and play the video in the Apple TV.

Here is my Code

let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "backgroundSession")

```<code>    backgroundSession = Foundation.URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)

    let url = URL(string: "myURl")!
    downloadTask = backgroundSession.downloadTask(with: url)
    downloadTask.resume()
</code>```

func urlSession(_ session: URLSession,
                    downloadTask: URLSessionDownloadTask,
                    didFinishDownloadingTo location: URL){

```<code>    let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    let documentDirectoryPath:String = path[0]
    let fileManager = FileManager()

    let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/file.mp4"))

    if fileManager.fileExists(atPath: destinationURLForFile.path){
        showFileWithPath(path: destinationURLForFile.path)
    }
    else{
        do {
            try fileManager.moveItem(at: location, to: destinationURLForFile)
            // show file
            showFileWithPath(path: destinationURLForFile.path)
        }catch{
            print("An error occurred while moving file to destination url")
        }
    }
}
</code>```

答:
There are some restrictions in tvOS regarding Local storage

Your app can only access 500 KB of persistent storage that is local to the device (using the NSUserDefaults class). Outside of this limited local storage, all other data must be purgeable by the operating system when space is low...

You can take a look to this documentation for further details:
https://developer.apple.com/library/content/documentation/General/Conceptual/AppleTV_PG/

Title: Video Download in Apple tvOS

Body:
I am a newbie to swift and tvOS.I want to download a video  from the url and display it in the ViewController. while i try with the ios Devices the video is downloaded and works fine.But with the tvOS the Video is not downloaded.

why is it so..?

How can i download and play the video in the Apple TV.

Here is my Code

let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "backgroundSession")

    backgroundSession = Foundation.URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)

    let url = URL(string: "myURl")!
    downloadTask = backgroundSession.downloadTask(with: url)
    downloadTask.resume()

func urlSession(_ session: URLSession,
                    downloadTask: URLSessionDownloadTask,
                    didFinishDownloadingTo location: URL){

    let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    let documentDirectoryPath:String = path[0]
    let fileManager = FileManager()

    let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/file.mp4"))

    if fileManager.fileExists(atPath: destinationURLForFile.path){
        showFileWithPath(path: destinationURLForFile.path)
    }
    else{
        do {
            try fileManager.moveItem(at: location, to: destinationURLForFile)
            // show file
            showFileWithPath(path: destinationURLForFile.path)
        }catch{
            print("An error occurred while moving file to destination url")
        }
    }
}


问:
How use enum from other class in method?
I need to use this enum

```<code>final class PermissionsManager {

  enum `Type`: String {
    case notifications, calendar, reminders, camera, photosLibrary
  }
</code>```

in other class in method.

```<code>private func requireAccess(from viewController: UIViewController, to type: PermissionsManager.Type, with action: Action?) {
    PermissionsManager.requireAccess(from: viewController, to: type, completion: action)
  }
</code>```

But in this case I have error:

Cannot convert value of type to expected argument type

Please help! How I can convey my enum to this method??

答: Even if you used backticks, there is still a conflict at core. Replace Type with something else (e.g. AccessType) and this should do.

Body:
I need to use this enum

final class PermissionsManager {

  enum `Type`: String {
    case notifications, calendar, reminders, camera, photosLibrary
  }

in other class in method.

private func requireAccess(from viewController: UIViewController, to type: PermissionsManager.Type, with action: Action?) {
    PermissionsManager.requireAccess(from: viewController, to: type, completion: action)
  }

But in this case I have error:

Cannot convert value of type to expected argument type

Please help! How I can convey my enum to this method??


问:
Why my simple chat in nodejs using websockets won't send messages
The chat is programmed in nodejs using websockets from socket.io library and i have a client that also uses websockets from socket.io but I don't manage to make the two work together. For some reason the client doesn't send the message to the server (I have a console.log function that should write to console when it receives a message but it doesn't write anything).

The code for the server is:

```<code>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
       console.log('message: ' + msg);
    io.emit('chat message', msg);
  });
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});
</code>```

And for the client is :

```<code><!DOCTYPE html>
<html>
<head>
    <style>
        * { margin:0; padding:0; font-size:11px; font-family:arial; color:#444; }
        body { padding:20px; }
        #message-list { list-style-type:none; width:300px; height:300px; overflow:auto; border:1px solid #999; padding:20px; }
        #message-list li { border-bottom:1px solid #ccc; padding-bottom:2px; margin-bottom:5px; }
        code { font-family:courier; background:#eee; padding:2px 4px; }
    </style>
    <script src="http://cdn.socket.io/stable/socket.io.js"></script>
    <script>

        // Sends a message to the server via sockets
        function sendMessageToServer(message) {
            socket.send(message);
            log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
        }

        // Outputs to console and list
        function log(message) {
            var li = document.createElement('li');
            li.innerHTML = message;
            document.getElementById('message-list').appendChild(li);
        }

        // Create a socket instance
        socket = new WebSocket('ws://localhost:8080');

        // Open the socket
        socket.onopen = function(event) {
            console.log('Socket opened on client side',event);

            // Listen for messages
            socket.onmessage = function(event) {
                console.log('Client received a message',event);
            };

            // Listen for socket closes
            socket.onclose = function(event) {
                console.log('Client notified socket has closed',event);
            };

        };

    </script>
</head>
<body>

    <p>Messages will appear below (and in the console).</p><br />
    <ul id="message-list"></ul>
    <ul style="margin:20px 0 0 20px;">
        <li>Type <code>socket.disconnect()</code> to disconnect</li>
        <li>Type <code>socket.connect()</code> to reconnect</li>
        <li>Type <code>sendMessageToServer('Your Message')</code> to send a message to the server</li>
    </ul>

</body>
</html>
</code>```

Do you have any idea what is wrong here?
Thanks in advance!

答:
You have a couple issues based on my knowledge. If they are all fixed, it should work.

The connection socket.io.js file should be your own one. In your case, I am guessing it is  I am not 100 percent sure because your port could vary.

You didn't define socket properly on your client side. Define it as this: var socket = io();. The way you did it is socket = new WebSocket('ws://localhost:8080'); Where WebSocket is not defined. And, the code will create a new websocket server, which you already did in your server code. What you need to do at client side is only connect to the server.

You must use the same channel to let the client and server to communicate. So in your client code, you should send message like this socket.emit('chat message', 'content you want to send'.

I don't know why you emit the message at server side again BTW. I am assuming you are sending message from client to server. So you shouldn't have emit command in your server code.

If all the four things been fixed, it will work.

In case my expression is not clear, I wrote a super simple example for you:

Server side:

```<code>let io = socketio(server.listener);
io.on("connection", function(socket) {
    console.log("A user connected");

    // auto messages when a user is connected
    setTimeout(function() {
        socket.send("message at 4 seconds");
    }, 4000);
    setTimeout(function() {
        socket.send("message at 8 seconds");
    }, 8000);

    // callback when a user disconnected
    socket.on("disconnect", function(){
        console.log("A user disconnected");
    });

    // receive message from client
    socket.on("client-server", function(msg) {
        console.log(msg);
    });
});

// you put this code anywhere when you need to send message from server to client
io.emit("server-client", "server to client message");
</code>```

Client side:

```<code><!DOCTYPE html>
<html>
  <head><title>Hello world</title></head>
  <script src="http://localhost:3000/socket.io/socket.io.js"></script>
  <script>
    var socket = io();
    socket.on('server-client', function(data) {document.write(data)});
    socket.emit('client-server', 'test message');
  </script>
  <body>Hello world</body>
</html>
</code>```

My server code is written in typescript so never mind the let key word, double quote and so on.

Body:
The chat is programmed in nodejs using websockets from socket.io library and i have a client that also uses websockets from socket.io but I don't manage to make the two work together. For some reason the client doesn't send the message to the server (I have a console.log function that should write to console when it receives a message but it doesn't write anything).

The code for the server is:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
       console.log('message: ' + msg);
    io.emit('chat message', msg);
  });
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});

And for the client is :

<!DOCTYPE html>

Messages will appear below (and in the console).

Type socket.disconnect() to disconnect

Type socket.connect() to reconnect

Type sendMessageToServer('Your Message') to send a message to the server

Do you have any idea what is wrong here?
Thanks in advance!

Body:
You have a couple issues based on my knowledge. If they are all fixed, it should work.

The connection socket.io.js file should be your own one. In your case, I am guessing it is <script src="http://localhost:3000/socket/socket.io.js"></script> I am not 100 percent sure because your port could vary.

You didn't define socket properly on your client side. Define it as this: var socket = io();. The way you did it is socket = new WebSocket('ws://localhost:8080'); Where WebSocket is not defined. And, the code will create a new websocket server, which you already did in your server code. What you need to do at client side is only connect to the server.

You must use the same channel to let the client and server to communicate. So in your client code, you should send message like this socket.emit('chat message', 'content you want to send'.

I don't know why you emit the message at server side again BTW. I am assuming you are sending message from client to server. So you shouldn't have emit command in your server code.

If all the four things been fixed, it will work.

In case my expression is not clear, I wrote a super simple example for you:

Server side:

let io = socketio(server.listener);
io.on("connection", function(socket) {
    console.log("A user connected");

    // auto messages when a user is connected
    setTimeout(function() {
        socket.send("message at 4 seconds");
    }, 4000);
    setTimeout(function() {
        socket.send("message at 8 seconds");
    }, 8000);

    // callback when a user disconnected
    socket.on("disconnect", function(){
        console.log("A user disconnected");
    });

    // receive message from client
    socket.on("client-server", function(msg) {
        console.log(msg);
    });
});

// you put this code anywhere when you need to send message from server to client
io.emit("server-client", "server to client message");

Client side:

<!DOCTYPE html>
<html>
  <head><title>Hello world</title></head>
  <script src="http://localhost:3000/socket.io/socket.io.js"></script>
  <script>
    var socket = io();
    socket.on('server-client', function(data) {document.write(data)});
    socket.emit('client-server', 'test message');
  </script>
  <body>Hello world</body>
</html>

My server code is written in typescript so never mind the let key word, double quote and so on.