问:
Django: queryset.count() is significantly slower on chained filters than single filters regardless of returned query size--is there a solution?
EDIT: Best solution thanks to Hakan--

```<code>queriedForms.filter(pk__in=list(formtype.form_set.all().filter(formrecordattributevalue__record_value__contains=constraint['TVAL'], formrecordattributevalue__record_attribute_type__pk=rtypePK).values_list('pk', flat=True))).count()
</code>```

I tried more of his suggestions but I can't avoid an INNER JOIN--this seems to be a a stable solution that does get me small, but predictable speed increases across the board. Look through his answer for more details!

I've been struggling with a problem I haven't seen an answer to online.

When chaining two filters in Django e.g.

```<code>masterQuery = bigmodel.relatedmodel_set.all()
masterQuery = masterQuery.filter(name__contains="test")
masterQuery.count()
#returns 100,000 results in < 1 second
#test filter--all 100,000+ names have "test x" where x is 0-9
storedCount = masterQuery.filter(name__contains="9").count()
#returns ~50,000 results but takes 5-6 seconds
</code>```

Trying a slightly different way:

```<code>masterQuery = masterQuery.filter(name__contains="9")
masterQuery.count()
#also returns ~50,000 results in 5-6 seconds
</code>```

performing an & merge seems to ever so slightly improve performance, e.g

```<code>masterQuery = bigmodel.relatedmodel_set.all()
masterQuery = masterQuery.filter(name__contains="test")
(masterQuery & masterQuery.filter(name__contains="9")).count()
</code>```

It seems as if count takes a significantly longer time beyond a single filter in a queryset.

I assume it may have something to do with mySQL, which apparently doesn't like nested statements--and I assume that two filters are creating a nested query that slows mySQL down, regardless of the  SELECT COUNT(*) django uses

So my question is: Is there anyway to speed this up? I'm getting ready to do a lot of regular nested querying only using queryset counts (I don't need the actual model values) without database hits to load the models. e.g. I don't need to load 100,000 models from the database, I just need to know there are 100,000 there. It's obviously much faster to do this through querysets than len() but even at 5 secs a count when I'm running 40 counts for an entire complex query is 3+ minutes--I'd prefer it be under a minute. Am I just fantasizing or does someone have a suggestion as to how this could be accomplished outside of increasing the server's processor speed?

EDIT: If it's helpful--the time.clock() speed is .3 secs for the chained filter() count--the actual time to console and django view output is 5-6s

EDIT2: To answer any questions about indexing, the filters use both an indexed and non indexed value for each link in the chain:

```<code>mainQuery = masterQuery = bigmodel.relatedmodel_set.all()
mainQuery = mainQuery.filter(reverseforeignkeytestmodel__record_value__contains="test", reverseforeignkeytestmodel__record_attribute_type__pk=1)
#Where "record_attribute_type" is another foreign key being used as a filter
mainQuery.count() #produces 100,000 results in < 1sec
mainQuery.filter(reverseforeignkeytestmodel__record_value__contains="9", reverseforeignkeytestmodel__record_attribute_type__pk=5).count()
#produces ~50,000 results in 5-6 secs
</code>```

So each filter in the chain is functionally similar, it is an AND filter(condition,condition) where one condition is indexed, and the other is not. I can't index both conditions.

Edit 3:
Similar queries that result in smaller results, e.g. < 10,000 are much faster, regardless of the nesting--e.g. the first filter in the chain produces 10,000 results in ~<1sec but the second filter in the chain will produce 5,000 results in ~<1sec

Edit 4:
Still not working based on @Hakan's solution

```<code>mainQuery = bigmodel.relatedmodel_set.all()
#Setup the first filter as normal
mainQuery = mainQuery.filter(reverseforeignkeytestmodel__record_value__contains="test", reverseforeignkeytestmodel__record_attribute_type__pk=1)

#Grab a values list for the second chained filter instead of chaining it
values = bigmodel.relatedmodel_set.all().filter(reverseforeignkeytestmodel__record_value__contains="test", reverseforeignkeytestmodel__record_attribute_type__pk=8).values_list('pk', flat=True)
#filter the first query based on the values_list rather than a second filter
mainQuery = mainQuery.filter(pk__in=values)
mainQuery.count()
#Still takes on average the same amount of time after enough test runs--seems to be slightly faster than average--similar to the (quersetA & querysetB) merge solution I tried.
</code>```

It's possible I did this wrong--but the count results are consistent between the new value_list filter technique, e.g. I'm getting the same # of results. So it's definitely working--but seemingly taking the same amount of time

EDIT 5:
Also based on @Hakan's solution with some slight tweaks

```<code>mainQuery.filter(pk__in=list(formtype.form_set.all().filter(formrecordattributevalue__record_value__contains=constraint['TVAL'], formrecordattributevalue__record_attribute_type__pk=rtypePK).values_list('pk', flat=True))).count()
</code>```

This seems to operate faster for larger results in a queryset, e.g. > 50,000, but is actually much slower on smaller queryset results, e.g. < 50,000--where they used to be <1sec--sometimes 2-3 running in 1 second for chain filtering, they now all take 1 second individually. Essentially the speed gains in the larger queryset have been nullified by the speed loss in the smaller querysets.

I'm still going to try and break up the queries as per his suggestion further--but I'm not sure I'm able to. I'll update again(possibly on Monday) when I figure that out and let everyone interested know the progress.

答:
Not sure if this helps, since I don't have a mysql project to test with.

The QuerySet API reference contains a section about the performance of nested queries.

Performance considerations

Be cautious about using nested queries and understand your database
  server’s performance characteristics (if in doubt, benchmark!). Some
  database backends, most notably MySQL, don’t optimize nested queries
  very well. It is more efficient, in those cases, to extract a list of
  values and then pass that into the second query. That is, execute two
  queries instead of one:

```<code>values = Blog.objects.filter(
    name__contains='Cheddar').values_list('pk', flat=True)
entries = Entry.objects.filter(blog__in=list(values))
</code>```

Note the list() call around the Blog QuerySet to force execution of the first query.
  Without it, a nested query would be executed, because QuerySets are
  lazy.

So, maybe you can improve the performance by trying something like this:

```<code>masterQuery = bigmodel.relatedmodel_set.all()
pks = list(masterQuery.filter(name__contains="test").values_list('pk', flat=True))
count = masterQuery.filter(pk__in=pks, name__contains="9")
</code>```

Since your initial MySQL performance is so slow, it might even be faster to do the second step in Python instead of in the database.

```<code>names = masterQuery.filter(name__contains='test').values_list('name')
count = sum('9' in n for n in names)
</code>```

Edit:
From your updates, I see that you are querying fields in related models, which result in multiple sql JOIN operations. That's likely a big reason why the query is slow.

To avoid joins, you could try something like this. The goal is to avoid doing deeply chained lookups across relations.

```<code># query only RelatedModel, avoid JOIN
related_pks = RelatedModel.objects.filter(
     record_value__contains=constraint['TVAL'],
     record_attribute_type=rtypePK,
).values_list('pk', flat=True)

# list(queryset) will do a database query, resulting in a list of integers.
pks_list = list(related_pks)

# use that result to filter your main model.
count = MainModel.objects.filter(
     formrecordattributevalue__in=pks_list
).count()
</code>```

I'm assuming that the relation is defined as a foreign key from MainModel to RelatedModel.

Body:
EDIT: Best solution thanks to Hakan--

queriedForms.filter(pk__in=list(formtype.form_set.all().filter(formrecordattributevalue__record_value__contains=constraint['TVAL'], formrecordattributevalue__record_attribute_type__pk=rtypePK).values_list('pk', flat=True))).count()

I tried more of his suggestions but I can't avoid an INNER JOIN--this seems to be a a stable solution that does get me small, but predictable speed increases across the board. Look through his answer for more details!

I've been struggling with a problem I haven't seen an answer to online.

When chaining two filters in Django e.g.

masterQuery = bigmodel.relatedmodel_set.all()
masterQuery = masterQuery.filter(name__contains="test")
masterQuery.count()
#returns 100,000 results in < 1 second
#test filter--all 100,000+ names have "test x" where x is 0-9
storedCount = masterQuery.filter(name__contains="9").count()
#returns ~50,000 results but takes 5-6 seconds

Trying a slightly different way:

masterQuery = masterQuery.filter(name__contains="9")
masterQuery.count()
#also returns ~50,000 results in 5-6 seconds

performing an & merge seems to ever so slightly improve performance, e.g

masterQuery = bigmodel.relatedmodel_set.all()
masterQuery = masterQuery.filter(name__contains="test")
(masterQuery & masterQuery.filter(name__contains="9")).count()

It seems as if count takes a significantly longer time beyond a single filter in a queryset.

I assume it may have something to do with mySQL, which apparently doesn't like nested statements--and I assume that two filters are creating a nested query that slows mySQL down, regardless of the  SELECT COUNT(*) django uses

So my question is: Is there anyway to speed this up? I'm getting ready to do a lot of regular nested querying only using queryset counts (I don't need the actual model values) without database hits to load the models. e.g. I don't need to load 100,000 models from the database, I just need to know there are 100,000 there. It's obviously much faster to do this through querysets than len() but even at 5 secs a count when I'm running 40 counts for an entire complex query is 3+ minutes--I'd prefer it be under a minute. Am I just fantasizing or does someone have a suggestion as to how this could be accomplished outside of increasing the server's processor speed?

EDIT: If it's helpful--the time.clock() speed is .3 secs for the chained filter() count--the actual time to console and django view output is 5-6s

EDIT2: To answer any questions about indexing, the filters use both an indexed and non indexed value for each link in the chain:

mainQuery = masterQuery = bigmodel.relatedmodel_set.all()
mainQuery = mainQuery.filter(reverseforeignkeytestmodel__record_value__contains="test", reverseforeignkeytestmodel__record_attribute_type__pk=1)
#Where "record_attribute_type" is another foreign key being used as a filter
mainQuery.count() #produces 100,000 results in < 1sec
mainQuery.filter(reverseforeignkeytestmodel__record_value__contains="9", reverseforeignkeytestmodel__record_attribute_type__pk=5).count()
#produces ~50,000 results in 5-6 secs

So each filter in the chain is functionally similar, it is an AND filter(condition,condition) where one condition is indexed, and the other is not. I can't index both conditions.

Edit 3:
Similar queries that result in smaller results, e.g. < 10,000 are much faster, regardless of the nesting--e.g. the first filter in the chain produces 10,000 results in ~<1sec but the second filter in the chain will produce 5,000 results in ~<1sec

Edit 4:
Still not working based on @Hakan's solution

mainQuery = bigmodel.relatedmodel_set.all()
#Setup the first filter as normal
mainQuery = mainQuery.filter(reverseforeignkeytestmodel__record_value__contains="test", reverseforeignkeytestmodel__record_attribute_type__pk=1)

#Grab a values list for the second chained filter instead of chaining it
values = bigmodel.relatedmodel_set.all().filter(reverseforeignkeytestmodel__record_value__contains="test", reverseforeignkeytestmodel__record_attribute_type__pk=8).values_list('pk', flat=True)
#filter the first query based on the values_list rather than a second filter
mainQuery = mainQuery.filter(pk__in=values)
mainQuery.count()
#Still takes on average the same amount of time after enough test runs--seems to be slightly faster than average--similar to the (quersetA & querysetB) merge solution I tried.

It's possible I did this wrong--but the count results are consistent between the new value_list filter technique, e.g. I'm getting the same # of results. So it's definitely working--but seemingly taking the same amount of time

EDIT 5:
Also based on @Hakan's solution with some slight tweaks

mainQuery.filter(pk__in=list(formtype.form_set.all().filter(formrecordattributevalue__record_value__contains=constraint['TVAL'], formrecordattributevalue__record_attribute_type__pk=rtypePK).values_list('pk', flat=True))).count()

This seems to operate faster for larger results in a queryset, e.g. > 50,000, but is actually much slower on smaller queryset results, e.g. < 50,000--where they used to be <1sec--sometimes 2-3 running in 1 second for chain filtering, they now all take 1 second individually. Essentially the speed gains in the larger queryset have been nullified by the speed loss in the smaller querysets.

I'm still going to try and break up the queries as per his suggestion further--but I'm not sure I'm able to. I'll update again(possibly on Monday) when I figure that out and let everyone interested know the progress.

Body:
Not sure if this helps, since I don't have a mysql project to test with.

The QuerySet API reference contains a section about the performance of nested queries.

Performance considerations

Be cautious about using nested queries and understand your database
  server’s performance characteristics (if in doubt, benchmark!). Some
  database backends, most notably MySQL, don’t optimize nested queries
  very well. It is more efficient, in those cases, to extract a list of
  values and then pass that into the second query. That is, execute two
  queries instead of one:

values = Blog.objects.filter(
    name__contains='Cheddar').values_list('pk', flat=True)
entries = Entry.objects.filter(blog__in=list(values))

Note the list() call around the Blog QuerySet to force execution of the first query.
  Without it, a nested query would be executed, because QuerySets are
  lazy.

So, maybe you can improve the performance by trying something like this:

masterQuery = bigmodel.relatedmodel_set.all()
pks = list(masterQuery.filter(name__contains="test").values_list('pk', flat=True))
count = masterQuery.filter(pk__in=pks, name__contains="9")

Since your initial MySQL performance is so slow, it might even be faster to do the second step in Python instead of in the database.

names = masterQuery.filter(name__contains='test').values_list('name')
count = sum('9' in n for n in names)

Edit:
From your updates, I see that you are querying fields in related models, which result in multiple sql JOIN operations. That's likely a big reason why the query is slow.

To avoid joins, you could try something like this. The goal is to avoid doing deeply chained lookups across relations.

# query only RelatedModel, avoid JOIN
related_pks = RelatedModel.objects.filter(
     record_value__contains=constraint['TVAL'],
     record_attribute_type=rtypePK,
).values_list('pk', flat=True)

# list(queryset) will do a database query, resulting in a list of integers.
pks_list = list(related_pks)

# use that result to filter your main model.
count = MainModel.objects.filter(
     formrecordattributevalue__in=pks_list
).count()

I'm assuming that the relation is defined as a foreign key from MainModel to RelatedModel.


来源: stackexchange

问:
Python Stroke Width Transform
I'm trying to implement the Stroke Width Transform in Python. I have gone through numerous stack overflow questions and answers and other resources on the internet but have not found an implementation for it. So I decided to try on my own.

After performing Canny edge detection, my first step is to calculate the x and y derivatives of the image

```<code>sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)
</code>```

How do I then combine these to get the gradient at each point in the image? Also, how do I then calculate the width of the stroke?

I'm using the steps given in the original IEEE Paper (freely accessible paper direct from Microsoft here) for reference. The description of the steps is on the bottom of the right hand side on page 3.

答:
There's a python implementation of the SWT here.
And unlike many SWT implementations I've seen, this one clusters text regions into groups that likely represent words.</p>

ContentLicense: CC BY-SA 3.0

Title: Python Stroke Width Transform

Body:
I'm trying to implement the Stroke Width Transform in Python. I have gone through numerous stack overflow questions and answers and other resources on the internet but have not found an implementation for it. So I decided to try on my own.

After performing Canny edge detection, my first step is to calculate the x and y derivatives of the image

sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)

How do I then combine these to get the gradient at each point in the image? Also, how do I then calculate the width of the stroke?

I'm using the steps given in the original IEEE Paper (freely accessible paper direct from Microsoft here) for reference. The description of the steps is on the bottom of the right hand side on page 3.


问:
Getting error "ORA-54033" when calling a procedure
I'm currently getting the following Oracle error when calling a procedure:

ORA-54033: column to be modified is used in a virtual column
expression

How can I track down the root cause of this error?

答:
I got the same error and fixed it by doing as below.

Get the hidden columns with its dependent columns using the below.

```<code>SELECT COLUMN_NAME, DATA_DEFAULT, HIDDEN_COLUMN
FROM   USER_TAB_COLS
WHERE  TABLE_NAME = 'YOUR_TABLE_NAME';
</code>```

You should see something like this below:

SYS_STUMF_$2WEF286CDZ1WPC4V_F5    |SYS_OP_COMBINED_HASH("ID","FIRST_NAME","ANOTHER_COLUMN_NAME") | YES
```
<p>Drop this <em>hidden column</em> by using the above column names used by it.</p>
```exec dbms_stats.drop_extended_stats(user, 'YOUR_TABLE_NAME', '("ID","FIRST_NAME","ANOTHER_COLUMN_NAME") ');
```
<p>Now run your procedure or alter your columns.</p>
```alter table YOUR_TABLE_NAME modify (ID VARCHAR2(10));
```
<p>Create the hidden column again:</p>
```exec dbms_stats.create_extended_stats(user, 'YOUR_TABLE_NAME', '("ID","FIRST_NAME","ANOTHER_COLUMN_NAME")');
```

ContentLicense: CC BY-SA 4.0

Body:
I got the same error and fixed it by doing as below.

Get the hidden columns with its dependent columns using the below.

SELECT COLUMN_NAME, DATA_DEFAULT, HIDDEN_COLUMN
FROM   USER_TAB_COLS
WHERE  TABLE_NAME = 'YOUR_TABLE_NAME';

You should see something like this below:

SYS_STUMF_$2WEF286CDZ1WPC4V_F5    |SYS_OP_COMBINED_HASH("ID","FIRST_NAME","ANOTHER_COLUMN_NAME") | YES

Drop this hidden column by using the above column names used by it.

exec dbms_stats.drop_extended_stats(user, 'YOUR_TABLE_NAME', '("ID","FIRST_NAME","ANOTHER_COLUMN_NAME") ');

Now run your procedure or alter your columns.

alter table YOUR_TABLE_NAME modify (ID VARCHAR2(10));

Create the hidden column again:

exec dbms_stats.create_extended_stats(user, 'YOUR_TABLE_NAME', '("ID","FIRST_NAME","ANOTHER_COLUMN_NAME")');


问:
How to get base enum name in Dynamics AX?
I would like get in code name of base enum not value or label.
With this code I get label not name:</p>

```<code>info(enum2str(KPAssetGroup::PWNiP));
</code>```

答:
Simply use enum2Symbol()

For example:

```<code>enum2Symbol(enumNum(KPAssetGroup), KPAssetGroup::PWNiP);
</code>```

Body:
I would like get in code name of base enum not value or label.
With this code I get label not name:

info(enum2str(KPAssetGroup::PWNiP));

Body:
Simply use enum2Symbol()

For example:

enum2Symbol(enumNum(KPAssetGroup), KPAssetGroup::PWNiP);


问:
Ember: Should I call transition from a controller or component
I was wondering what the best practices around transition to another route in Ember. Currently in my controller, I call the ember data store then transition to another route using transitionToRoute function but with the new focus components these days I saw you an inject the router as a service inside your component. Is this where I should be moving this logic or controller is still right place for this?</p>

答:
The best practice is to use Route for loading and mutating data as well as for transitions.  Remember: data down, actions up.

https://guides.emberjs.com/v2.14.0/routing/


问:
Post-build commits: good or bad?
Is it a good policy to automate source control commits following successful builds?

Edit: I'm asking because I want more frequent, incremental commits between versions that make it easier to find the point where a bug was introduced than rolling back 2K+ new lines of code between v1.0 and v1.1.

答: No. A successful build does not imply a successful code change. Do you never test your code? IF you had some sort of automated unit testing, I could understand the question (although I would still recommend against it - I would not consider a code change tested until you verified its functionality yourself). But an automated commit after a successful build - not if you like your team mates, or if they have access to weapons.</p>

ContentLicense: CC BY-SA 2.5

Title: Post-build commits: good or bad?


问:
Is Log a compressed table engine in Clickhouse
I have a Log table and also a MergeTree table. In the system.columns table, it has a column, data_compressed_bytes, showing bytes compressed for each column for each table. I can see that the MergeTree table showing values under the column but for the Log table, the column shows all zeros.

Log

```<code>┌─database─┬─table──┬─name───────────┬─type─────┬─data_compressed_bytes─┬─data_uncompressed_bytes─┬─marks_bytes─┐
│ default  │ logs   │ log_time       │ DateTime │                     0 │                       0 │           0 │
│ default  │ logs   │ start_time     │ DateTime │                     0 │                       0 │           0 │
</code>```

MergeTree

```<code>┌─database─┬─table─────┬─name────────┬─type─────┬─data_compressed_bytes─┬─data_uncompressed_bytes─┬─marks_bytes─┐
│ default  │ logs_m │ log_date    │ Date     │               1221802 │                20000000 │       19536 │
│ default  │ logs_m │ log_time    │ DateTime │              25181624 │                40000000 │       19536 │
</code>```

So, I am wondering if it means that columns in engine type Log are actually compressed or not.

ClickHouse documentation states that TinyLog is compressed but not sure about Log and I don't see that in the system.columns table.

答:
Log engine compresses column data as well as TinyLog.

Quotes from the doc:

TinyLog The simplest table engine, which stores data on a disk. Each
  column is stored in a separate compressed file.

Log differs from TinyLog in that a small file of “marks” resides with
  the column files.

The information about compressed and decompressed sizes of a column is not reflected into system.columns table because Log is a quite simple engine (unlike MergeTree) and doesn't store a lot of metainformation about own column files (it only maintains sizes.json file with compressed column sizes).

So, it is possible to set system.columns.data_compressed_bytes for Log's columns, but at the same time system.columns.data_uncompressed_bytes will be zero and it may look questionable.

Body:
I have a Log table and also a MergeTree table. In the system.columns table, it has a column, data_compressed_bytes, showing bytes compressed for each column for each table. I can see that the MergeTree table showing values under the column but for the Log table, the column shows all zeros.

Log

┌─database─┬─table──┬─name───────────┬─type─────┬─data_compressed_bytes─┬─data_uncompressed_bytes─┬─marks_bytes─┐
│ default  │ logs   │ log_time       │ DateTime │                     0 │                       0 │           0 │
│ default  │ logs   │ start_time     │ DateTime │                     0 │                       0 │           0 │

MergeTree

┌─database─┬─table─────┬─name────────┬─type─────┬─data_compressed_bytes─┬─data_uncompressed_bytes─┬─marks_bytes─┐
│ default  │ logs_m │ log_date    │ Date     │               1221802 │                20000000 │       19536 │
│ default  │ logs_m │ log_time    │ DateTime │              25181624 │                40000000 │       19536 │

So, I am wondering if it means that columns in engine type Log are actually compressed or not.

ClickHouse documentation states that TinyLog is compressed but not sure about Log and I don't see that in the system.columns table.


问:
Wordpress: Is there a way to adjust the Column Width for the Post table?
None of the suggested topics about width concern WordPress. What I need is a way to adjust the width of the Posts table which comes up when Posts is selected (Title Author Categories, etc.) I've looked in Appearance/Edit at every .php Template and can't find anything relating to this. I'm sure I've missed something. Also, I have no immediate need for the "Date" and "Tags" columns. Can I either delete these or least hide them?

Thanks,
Mike Carter

答:
If you want to do this for only a custom post type's post table, you can add the following action into your functions.php file (or create a small plugin like in pp19dd's answer):</p>

```<code>add_action('admin_head', 'mytheme_admin_head');
function mytheme_admin_head() {
    global $post_type;
    if ( 'my_custom_post_type' == $post_type ) {
        ?><style type="text/css"> .column-date { width: 20%; } </style><?php
    }
}
</code>```

Body:
If you want to do this for only a custom post type's post table, you can add the following action into your functions.php file (or create a small plugin like in pp19dd's answer):

add_action('admin_head', 'mytheme_admin_head');
function mytheme_admin_head() {
    global $post_type;
    if ( 'my_custom_post_type' == $post_type ) {
        ?><style type="text/css"> .column-date { width: 20%; } </style><?php
    }
}


问:
Read last line from website without saving file on disk
I have a website with many large CSV files (up to 100,000 lines each). From each CSV file, I need to read the last line in the file. I know how to solve the problem when I save the file on disk before reading its content:

```<code>                var url = "http://data.cocorahs.org/cocorahs/export/exportreports.aspx?ReportType=Daily&Format=csv&Date=1/1/2000&Station=UT-UT-24"
            var client = new System.Net.WebClient();
            var tempFile = System.IO.Path.GetTempFileName();
            client.DownloadFile(url, tempFile);
            var lastLine = System.IO.File.ReadLines(tempFile).Last();
</code>```

Is there any way to get the last line without saving a temporary file on disk?
I tried:

```<code>using (var stream = client.OpenRead(seriesUrl))
{
    using (var reader = new StreamReader(stream))
    {
        var lastLine = reader.ReadLines("file.txt").Last();
    }
}
</code>```

but the StreamReader class does not have a ReadLines method ...

答:
This worked for me, though the service did not return data (Headers of CSV only):</p>

```<code>public void TestMethod1()
{
    var url = "http://data.cocorahs.org/cocorahs/export/exportreports.aspx?ReportType=Daily&Format=csv&Date=1/1/2000&Station=UT-UT-24";
    var client = new System.Net.WebClient();

    using (var stream = client.OpenRead(url))
    {
        using (var reader = new StreamReader(stream))
        {
            var str = reader.ReadToEnd().Split('\n').Where(x => !string.IsNullOrEmpty(x)).LastOrDefault();

            Debug.WriteLine(str);
            Assert.IsNotEmpty(str);
        }
    }

}
</code>```

Body:
I have a website with many large CSV files (up to 100,000 lines each). From each CSV file, I need to read the last line in the file. I know how to solve the problem when I save the file on disk before reading its content:

                var url = "http://data.cocorahs.org/cocorahs/export/exportreports.aspx?ReportType=Daily&Format=csv&Date=1/1/2000&Station=UT-UT-24"
            var client = new System.Net.WebClient();
            var tempFile = System.IO.Path.GetTempFileName();
            client.DownloadFile(url, tempFile);
            var lastLine = System.IO.File.ReadLines(tempFile).Last();

Is there any way to get the last line without saving a temporary file on disk?
I tried:

using (var stream = client.OpenRead(seriesUrl))
{
    using (var reader = new StreamReader(stream))
    {
        var lastLine = reader.ReadLines("file.txt").Last();
    }
}

but the StreamReader class does not have a ReadLines method ...

Body:
This worked for me, though the service did not return data (Headers of CSV only):

public void TestMethod1()
{
    var url = "http://data.cocorahs.org/cocorahs/export/exportreports.aspx?ReportType=Daily&Format=csv&Date=1/1/2000&Station=UT-UT-24";
    var client = new System.Net.WebClient();

    using (var stream = client.OpenRead(url))
    {
        using (var reader = new StreamReader(stream))
        {
            var str = reader.ReadToEnd().Split('\n').Where(x => !string.IsNullOrEmpty(x)).LastOrDefault();

            Debug.WriteLine(str);
            Assert.IsNotEmpty(str);
        }
    }

}


问:
What does `this` point at in the following js arrow functions in mocha tests?
What does this point here?

```<code>const expect = require('chai').expect;
const sinon = require('sinon');

describe('test', () => {
  describe('test()', () => {
    afterEach(function _test() {
      this.xxx = undefined; // What does `this` point here?
    });
  });

  describe('test2()', () => {
    afterEach(function _test2() {
      this.yyy = undefined; // What does `this` point here?
    });
  });
});
</code>```

By the way, it is good to use this in the above codes if both this(s) point at the same object?

UPDATE

Code

```<code>describe('test', () => {
  console.log(1, this);
  before(() => {
    console.log(2, this);
  });
  beforeEach( () => {
    console.log(3, this);
  });
  describe('going deeper', () => {
    console.log(4, this);
    beforeEach(() => {
      console.log(6, this);
    });
    return it('has increased someVal to 3', function() {
      assert.equal(1,1);
      //console.log(7, this);
    });
  });
});
</code>```

output:

```<code>1 {}
4 {}

  test
2 {}
    going deeper
3 {}
6 {}
      ✓ has increased someVal to 3

  1 passing (4ms)
</code>```

code (changed one arrow function to normal function):

```<code>describe('test', () => {
  console.log(1, this);
  before(() => {
    console.log(2, this);
  });
  beforeEach( () => {
    console.log(3, this);
  });
  describe('going deeper', () => {
    console.log(4, this);
    beforeEach(function() { // HERE
      console.log(6, this);
    });
    return it('has increased someVal to 3', function() {
      assert.equal(1,1);
      //console.log(7, this);
    });
  });
});
</code>```

output:

```<code>1 {}
4 {}

  test
2 {}
    going deeper
3 {}
      1) "before each" hook for "has increased someVal to 3"

  0 passing (6ms)
  1 failing

  1) test going deeper "before each" hook for "has increased someVal to 3":
     TypeError: Converting circular structure to JSON
      at Object.stringify (native)
      at formatValue (util.js:352:36)
      at inspect (util.js:186:10)
      at exports.format (util.js:72:24)
      at Console.log (console.js:43:37)
      at Context.<anonymous> (test3.js:32:15)
</code>```

答:
In both locations you inquire about, this is bound by Mocha to an internal Mocha object. One thing this object allows you to do, for instance, is change Mocha's configuration. Like changing the timeout of asynchronous function with this.timeout(newValue). It's not particularly useful in the example below, but Mocha will run it just fine. Eg:

```<code>describe('test', () => {
  describe('test()', () => {
    afterEach(function _test() {
      this.timeout(5000);
      this.xxx = undefined;
    });

    it("foo", () => {});
  });

  describe('test2()', () => {
    afterEach(function _test2() {
      this.timeout(5000);
      this.yyy = undefined;
    });

    it("foo", () => {});
  });
});
</code>```

Note that if you were to use an arrow function for your afterEach callbacks, you could not access the value of this that Mocha sets for the callback. (this will have a value set in an outer scope.)

By the way, it is good to use this in the above codes if both this(s) point at the same object?

I don't recommend setting arbitrary fields on this. There's no telling when the field you set is going to clash with a field introduced by a newer version of Mocha. I've always been able instead to set a variable in the enclosing describe and use that:

```<code>describe('test', () => {
    let something;

    beforeEach(function _test() {
        something = fetchATestFixtureFromSomewhere();
    });

    it("foo", () => {
        // use the variable something here.
    });
});
</code>```

Regarding your update. Everywhere you get {} on the console that's because all functions enclosing your console.log are arrow functions and as I've said above, if you use an arrow function then you cannot access the object that Mocha binds to this because in such case this is taken from an outer scope instead of being taken from the value bound to the function. If all enclosing functions are arrow functions then this comes from the outermost scope and it has the value {} in the outermost scope.

The error you get is because you cannot just dump the value Mocha assigns to this to the console, because as the error message indicates, it is a structure with a circular reference in it.

Body:
What does this point here?

const expect = require('chai').expect;
const sinon = require('sinon');

describe('test', () => {
  describe('test()', () => {
    afterEach(function _test() {
      this.xxx = undefined; // What does `this` point here?
    });
  });

  describe('test2()', () => {
    afterEach(function _test2() {
      this.yyy = undefined; // What does `this` point here?
    });
  });
});

By the way, it is good to use this in the above codes if both this(s) point at the same object?

UPDATE

Code

describe('test', () => {
  console.log(1, this);
  before(() => {
    console.log(2, this);
  });
  beforeEach( () => {
    console.log(3, this);
  });
  describe('going deeper', () => {
    console.log(4, this);
    beforeEach(() => {
      console.log(6, this);
    });
    return it('has increased someVal to 3', function() {
      assert.equal(1,1);
      //console.log(7, this);
    });
  });
});

output:

1 {}
4 {}

  test
2 {}
    going deeper
3 {}
6 {}
      ✓ has increased someVal to 3

  1 passing (4ms)

code (changed one arrow function to normal function):

describe('test', () => {
  console.log(1, this);
  before(() => {
    console.log(2, this);
  });
  beforeEach( () => {
    console.log(3, this);
  });
  describe('going deeper', () => {
    console.log(4, this);
    beforeEach(function() { // HERE
      console.log(6, this);
    });
    return it('has increased someVal to 3', function() {
      assert.equal(1,1);
      //console.log(7, this);
    });
  });
});

output:

1 {}
4 {}

  test
2 {}
    going deeper
3 {}
      1) "before each" hook for "has increased someVal to 3"

  0 passing (6ms)
  1 failing

  1) test going deeper "before each" hook for "has increased someVal to 3":
     TypeError: Converting circular structure to JSON
      at Object.stringify (native)
      at formatValue (util.js:352:36)
      at inspect (util.js:186:10)
      at exports.format (util.js:72:24)
      at Console.log (console.js:43:37)
      at Context.<anonymous> (test3.js:32:15)

Body:
In both locations you inquire about, this is bound by Mocha to an internal Mocha object. One thing this object allows you to do, for instance, is change Mocha's configuration. Like changing the timeout of asynchronous function with this.timeout(newValue). It's not particularly useful in the example below, but Mocha will run it just fine. Eg:

describe('test', () => {
  describe('test()', () => {
    afterEach(function _test() {
      this.timeout(5000);
      this.xxx = undefined;
    });

    it("foo", () => {});
  });

  describe('test2()', () => {
    afterEach(function _test2() {
      this.timeout(5000);
      this.yyy = undefined;
    });

    it("foo", () => {});
  });
});

Note that if you were to use an arrow function for your afterEach callbacks, you could not access the value of this that Mocha sets for the callback. (this will have a value set in an outer scope.)

By the way, it is good to use this in the above codes if both this(s) point at the same object?

I don't recommend setting arbitrary fields on this. There's no telling when the field you set is going to clash with a field introduced by a newer version of Mocha. I've always been able instead to set a variable in the enclosing describe and use that:

describe('test', () => {
    let something;

    beforeEach(function _test() {
        something = fetchATestFixtureFromSomewhere();
    });

    it("foo", () => {
        // use the variable something here.
    });
});

Regarding your update. Everywhere you get {} on the console that's because all functions enclosing your console.log are arrow functions and as I've said above, if you use an arrow function then you cannot access the object that Mocha binds to this because in such case this is taken from an outer scope instead of being taken from the value bound to the function. If all enclosing functions are arrow functions then this comes from the outermost scope and it has the value {} in the outermost scope.

The error you get is because you cannot just dump the value Mocha assigns to this to the console, because as the error message indicates, it is a structure with a circular reference in it.


问:
Whats wrong with my python program

tip and tax calculator

```<code>bill = price + tax + tip

price = raw_input("What is the price of the meal")

tax = price * .06

tip = price * 0.20
</code>```

what is wrong with my code
I have tried everything
please answer and get back to me

答:
First of all, you can't use variables that you haven't defined: in your code your are using bill = price + tax + tip but your program doesn't even know what price, tax and tip are yet, so that line should be at the end of the code, after you've asked the price and calculated tax and tip.

Then, you have raw_input, this function returns a string, if you want to convert it to a decimal number that you can multiply and add (float) you can use price = float(raw_input("what is the price of the meal"))

Correct that two things and it should work...

Title: Whats wrong with my python program

Body:
tip and tax calculator

bill = price + tax + tip

price = raw_input("What is the price of the meal")

tax = price * .06

tip = price * 0.20

what is wrong with my code
I have tried everything
please answer and get back to me


问:
Automate the generation of natural keys
I'm studying a way to serialize part of the data in database A and deserialize it in database B (a sort of save/restore between different installations) and I've had a look to Django natural keys to avoid problems due to duplicated IDs.

The only issue is that I should add a custom manager and a new method to all my models. Is there a way to make Django automatically generate natural keys by looking at unique=True or unique_togheter fields?

答:
Please note this answer has nothing to do with Django, but hopefully give you another alternative to think about.

You didn't mention your database, however, in SQL Server there is a BINARY_CHECKSUM() keyword you can use to give you a unique value for the data held in the row. Think of it as a hash against all the fields in the row.
This checksum method can be used to update a database from another by checking if local row checksum <> remote row checksum.

This SQL below will update a local database from a remote database. It won't insert new rows, for that you use insert ... where id > @MaxLocalID

```<code>SELECT  delivery_item_id, BINARY_CHECKSUM(*) AS bc
INTO    #DI
FROM    [REMOTE.NETWORK.LOCAL].YourDatabase.dbo.delivery_item di

SELECT  delivery_item_id, BINARY_CHECKSUM(*) AS bc
INTO    #DI_local
FROM    delivery_item di

-- Get rid of items that already match
DELETE  FROM #DI_local
WHERE   delivery_item_id IN (SELECT l.delivery_item_id
                             FROM   #DI x, #DI_local l
                             WHERE  l.delivery_item_id = x.delivery_item_id
                             AND l.bc = x.bc)

DROP TABLE #DI

UPDATE  DI
SET     engineer_id = X.engineer_id,
        ... -- Set other fields here
FROM    delivery_item DI,
        [REMOTE.NETWORK.LOCAL].YourDatabase.dbo.delivery_item x,
        #DI_local L
WHERE   x.delivery_item_id = L.delivery_item_id
        AND DI.delivery_item_id = L.delivery_item_id

DROP TABLE #DI_local
</code>```

For the above to work, you will need a linked server between your local database and the remote database:

```<code>-- Create linked server if you don't have one already
IF NOT EXISTS ( SELECT  srv.name
                FROM    sys.servers srv
                WHERE   srv.server_id != 0
                        AND srv.name = N'REMOTE.NETWORK.LOCAL' )
    BEGIN
        EXEC master.dbo.sp_addlinkedserver @server = N'REMOTE.NETWORK.LOCAL',
        @srvproduct = N'SQL Server'

        EXEC master.dbo.sp_addlinkedsrvlogin
        @rmtsrvname = N'REMOTE.NETWORK.LOCAL',
        @useself = N'False', @locallogin = NULL,
        @rmtuser = N'your user name',
        @rmtpassword = 'your password'
    END
GO
</code>```

Title: Automate the generation of natural keys

Body:
Please note this answer has nothing to do with Django, but hopefully give you another alternative to think about.

You didn't mention your database, however, in SQL Server there is a BINARY_CHECKSUM() keyword you can use to give you a unique value for the data held in the row. Think of it as a hash against all the fields in the row.
This checksum method can be used to update a database from another by checking if local row checksum <> remote row checksum.

This SQL below will update a local database from a remote database. It won't insert new rows, for that you use insert ... where id > @MaxLocalID

SELECT  delivery_item_id, BINARY_CHECKSUM(*) AS bc
INTO    #DI
FROM    [REMOTE.NETWORK.LOCAL].YourDatabase.dbo.delivery_item di

SELECT  delivery_item_id, BINARY_CHECKSUM(*) AS bc
INTO    #DI_local
FROM    delivery_item di

-- Get rid of items that already match
DELETE  FROM #DI_local
WHERE   delivery_item_id IN (SELECT l.delivery_item_id
                             FROM   #DI x, #DI_local l
                             WHERE  l.delivery_item_id = x.delivery_item_id
                             AND l.bc = x.bc)

DROP TABLE #DI

UPDATE  DI
SET     engineer_id = X.engineer_id,
        ... -- Set other fields here
FROM    delivery_item DI,
        [REMOTE.NETWORK.LOCAL].YourDatabase.dbo.delivery_item x,
        #DI_local L
WHERE   x.delivery_item_id = L.delivery_item_id
        AND DI.delivery_item_id = L.delivery_item_id

DROP TABLE #DI_local

For the above to work, you will need a linked server between your local database and the remote database:

-- Create linked server if you don't have one already
IF NOT EXISTS ( SELECT  srv.name
                FROM    sys.servers srv
                WHERE   srv.server_id != 0
                        AND srv.name = N'REMOTE.NETWORK.LOCAL' )
    BEGIN
        EXEC master.dbo.sp_addlinkedserver @server = N'REMOTE.NETWORK.LOCAL',
        @srvproduct = N'SQL Server'

        EXEC master.dbo.sp_addlinkedsrvlogin
        @rmtsrvname = N'REMOTE.NETWORK.LOCAL',
        @useself = N'False', @locallogin = NULL,
        @rmtuser = N'your user name',
        @rmtpassword = 'your password'
    END
GO


问:
Scrapy Spider Doesn't Return Any Information
I'm a student, and for a project I'm collecting information on brands. I found this website called Kit: Kit Page that I want to scrape for brands. It has almost 500 pages, and I wrote a Scrapy Spider in Python 3 that go through each of the pages and copies the list to a dictionary, but I can't figure out the xpath or css to actually get the list info. Here's my items.py:

```<code>import scrapy

class KitcreatorwebscraperItem(scrapy.Item):
    creator = scrapy.Field()
</code>```

and here's my spider:

```<code>import scrapy

class KitCreatorSpider(scrapy.Spider):
    name = "kitCreators"
    pageNumber = 1

    start_urls = [
        'https://kit.com/brands?page=1',
    ]

    while pageNumber <= 478:
        newUrl = "https://kit.com/brands?page=" + str(pageNumber)
        start_urls.append(newUrl)
        pageNumber += 1

    def parse(self, response):
        for li in response.xpath('//div[@class="section group"][0]'):
</code>```

It runs successfully, but I have been unable to write an xpath that gets the data I need. What path is necessary, and how do I implement that in the code?

答:
You can try below Xpath to extract brand names:

```<code>//a[@class="brandsView-list-item-link ng-binding"]/text()
</code>```

P.S. I would suggest you not to create the list of URLs. It seem to be redundant piece of code. Instead you might use for loop like:

```<code>for page_number in range(479):
    url = "https://kit.com/brands?page=%s" % page_number
    ...handle current page source...
</code>```

Update

You can try Selenium + PhantomJS to get required data from dynamic content:

```<code>from selenium import webdriver

driver = webdriver.PhantomJS()
brands_list = []

for page in range(1, 480):
    driver.get("https://kit.com/brands?page=%s" % page)
    [brands_list.append(brand.text) for brand in driver.find_elements_by_xpath('//a[@class="brandsView-list-item-link ng-binding"]')]

print(brands_list)
</code>```

Body:
I'm a student, and for a project I'm collecting information on brands. I found this website called Kit: Kit Page that I want to scrape for brands. It has almost 500 pages, and I wrote a Scrapy Spider in Python 3 that go through each of the pages and copies the list to a dictionary, but I can't figure out the xpath or css to actually get the list info. Here's my items.py:

import scrapy

class KitcreatorwebscraperItem(scrapy.Item):
    creator = scrapy.Field()

and here's my spider:

import scrapy

class KitCreatorSpider(scrapy.Spider):
    name = "kitCreators"
    pageNumber = 1

    start_urls = [
        'https://kit.com/brands?page=1',
    ]

    while pageNumber <= 478:
        newUrl = "https://kit.com/brands?page=" + str(pageNumber)
        start_urls.append(newUrl)
        pageNumber += 1

    def parse(self, response):
        for li in response.xpath('//div[@class="section group"][0]'):

It runs successfully, but I have been unable to write an xpath that gets the data I need. What path is necessary, and how do I implement that in the code?

Body:
You can try below Xpath to extract brand names:

//a[@class="brandsView-list-item-link ng-binding"]/text()

P.S. I would suggest you not to create the list of URLs. It seem to be redundant piece of code. Instead you might use for loop like:

for page_number in range(479):
    url = "https://kit.com/brands?page=%s" % page_number
    ...handle current page source...

Update

You can try Selenium + PhantomJS to get required data from dynamic content:

from selenium import webdriver

driver = webdriver.PhantomJS()
brands_list = []

for page in range(1, 480):
    driver.get("https://kit.com/brands?page=%s" % page)
    [brands_list.append(brand.text) for brand in driver.find_elements_by_xpath('//a[@class="brandsView-list-item-link ng-binding"]')]

print(brands_list)


问:
Task and Job Statisitics - WallClockTime and ExecutionInformation
I am trying to collect some statistics and performance metrics about the cloud tasks and jobs that I am submitting to the Azure Batch pool. For that, I am using the built-in TaskExecutionInformation and TaskStatisitics classes, but I am confused about how some metrics are calculated through these classes. Specifically, I want to know how long each of my tasks takes to execute, so I checked the wallclocktime built into task.statistics, and the difference between the start and end times built into task.ExecutionInformation and these two were different.

How is wall clock time calculated in task statistics? And why is it different from the timespan difference between the start and end times obtained through the task execution information?

Also, I noticed a large variance of the wall clock time of task execution (from 0.6 sec to 21 sec in my scenario) for the same task processing. What could be causing such a large variance?

Thanks!

答:
Wallclock time from statistics is the difference between the process end time and its creation time. These times are from the process created as specified by the task's commandline. The time difference that you can compute from executionInformation includes more than just the process execution time. This is the time from when the task is picked up by the node to when the task completes on the node with metadata and state updates that the Batch service requires. This time could include things like downloading resource files.

Since you are downloading the blob as part of your process itself, the variance can come from retrieving this data from Azure Storage (or any other noise source that your process involves). If you are able to move the blob as a resource file and your process does not contain any other variable execution portions, you should see more consistent wall clock times between verbatim tasks (as reported by the task statistics wall clock time).


问:
Is there a way to make mv create the directory to be moved to if it doesn't exist?
So, if I'm in my home directory and I want to move foo.c to ~/bar/baz/foo.c , but those directories don't exist, is there some way to have those directories automatically created, so that you would only have to type

```<code>mv foo.c ~/bar/baz/
</code>```

and everything would work out? It seems like you could alias mv to a simple bash script that would check if those directories existed and if not would call mkdir and then mv, but I thought I'd check to see if anyone had a better idea.

答:
The simpliest way to do that is:

```<code>mkdir [directory name] && mv [filename] $_
</code>```

Let's suppose I downloaded pdf files located in my download directory (~/download) and I want to move all of them into a directory that doesn't exist (let's say my_PDF).

I'll type the following command (making sure my current working directory is ~/download):

```<code>mkdir my_PDF && mv *.pdf $_
</code>```

You can add -p option to mkdir if you want to create subdirectories just like this: (supposed I want to create a subdirectory named python):

```<code>mkdir -p my_PDF/python && mv *.pdf $_
</code>```

OwnerDisplayName: Paul Wicks

Body:
So, if I'm in my home directory and I want to move foo.c to ~/bar/baz/foo.c , but those directories don't exist, is there some way to have those directories automatically created, so that you would only have to type

mv foo.c ~/bar/baz/

and everything would work out? It seems like you could alias mv to a simple bash script that would check if those directories existed and if not would call mkdir and then mv, but I thought I'd check to see if anyone had a better idea.

Body:
The simpliest way to do that is:

mkdir [directory name] && mv [filename] $_

Let's suppose I downloaded pdf files located in my download directory (~/download) and I want to move all of them into a directory that doesn't exist (let's say my_PDF).

I'll type the following command (making sure my current working directory is ~/download):

mkdir my_PDF && mv *.pdf $_

You can add -p option to mkdir if you want to create subdirectories just like this: (supposed I want to create a subdirectory named python):

mkdir -p my_PDF/python && mv *.pdf $_


问:
Is there any way to convert UWP App into windows Desktop WPF Application
We know that Desktop application can be converted into UWP apps.
But I want to Convert My UWP App into Desktop WPF Applictaion.
How to achieve this ? </p>

答:
There is no simple way how to achieve that. Even the conversion from desktop app to UWP app is not really a conversion - it just packs the desktop app in an APPX package so it can be published to Windows Store.

The only way is to rewrite your code.


问:
DB2 SQL Aggregation
I have a set of records in a DB2 database and I need to present a report in which all the fields for business done by users are provided for all users. All the different MGD_TYPE have been summarized for all users. How can I do this using SQL?</p>

```<code>USER_ID         MGD_TYPE                 MTHLY_AMT            EFF_DATE
1222            FX                       332.21              06/23/10
3333            REAL_ESTATE              2221.03             06/23/10
1222            MERGERS                 1882.43              02/03/12
3333            PORTFOLIO                721.44              01/22/15

USER            FX_AMT          REAL_EST_AMT         MERGERS_AMT         PORTFOLIO_AMT
1222            332.21           0.0                    1882.43          0.0
3333            0.0             2221.03                 0.0              721.44
</code>```

答:
This is a basic PIVOT query:</p>

```<code>SELECT USER_ID,
  SUM( CASE MGD_TYPE WHEN 'FX'          THEN MTHLY_AMT END ) As FX_AMT,
  SUM( CASE MGD_TYPE WHEN 'REAL_ESTATE' THEN MTHLY_AMT END ) As REAL_EST_AMT,
  SUM( CASE MGD_TYPE WHEN 'MERGERS'     THEN MTHLY_AMT END ) As MERGERS_AMT,
  SUM( CASE MGD_TYPE WHEN 'PORTFOLIO'   THEN MTHLY_AMT END ) As PORTFOLIO_AMT
FROM table
GROUP BY USER_ID
</code>```

Title: DB2 SQL Aggregation

Body:
I have a set of records in a DB2 database and I need to present a report in which all the fields for business done by users are provided for all users. All the different MGD_TYPE have been summarized for all users. How can I do this using SQL?

USER_ID         MGD_TYPE                 MTHLY_AMT            EFF_DATE
1222            FX                       332.21              06/23/10
3333            REAL_ESTATE              2221.03             06/23/10
1222            MERGERS                 1882.43              02/03/12
3333            PORTFOLIO                721.44              01/22/15

USER            FX_AMT          REAL_EST_AMT         MERGERS_AMT         PORTFOLIO_AMT
1222            332.21           0.0                    1882.43          0.0
3333            0.0             2221.03                 0.0              721.44

Body:
This is a basic PIVOT query:

SELECT USER_ID,
  SUM( CASE MGD_TYPE WHEN 'FX'          THEN MTHLY_AMT END ) As FX_AMT,
  SUM( CASE MGD_TYPE WHEN 'REAL_ESTATE' THEN MTHLY_AMT END ) As REAL_EST_AMT,
  SUM( CASE MGD_TYPE WHEN 'MERGERS'     THEN MTHLY_AMT END ) As MERGERS_AMT,
  SUM( CASE MGD_TYPE WHEN 'PORTFOLIO'   THEN MTHLY_AMT END ) As PORTFOLIO_AMT
FROM table
GROUP BY USER_ID


问:
Can gcc output C code after preprocessing?
I'm using an open source library which seems to have lots of preprocessing directives to support many languages other than C. So that I can study what the library is doing I'd like to see the C code that I'm compiling after preprocessing, more like what I'd write.

Can gcc (or any other tool commonly available in Linux) read this library but output C code that has the preprocessing converted to whatever and is also readable by a human?

答:
Run:

```<code>gcc -E <file>.c
</code>```

or

```<code>g++ -E <file>.cpp
</code>```

Body:
Run:

gcc -E <file>.c

or

g++ -E <file>.cpp


问:
Enable Thread Safety for php 7.1
I clone php 7.1:

```<code>apshenichnikov@IAS-WS-UX02:~/php-src$ git status
On branch PHP-7.1
</code>```

I make ./buildconf --force

I run:

```<code>./configure \
  --enable-hash \
  --prefix=/usr/local/php \
  --enable-maintainer-zts \
  --with-tsrm-pthreads \
  --with-pdo-oci=shared,instantclient,/opt/oracle/instantclient,12.1
</code>```

I successfully run make & make install:

```<code>apshenichnikov@IAS-WS-UX02:~/php-src$ sudo make install
Installing shared extensions:     /usr/local/php/lib/php/extensions/no-debug-zts-20151012/
Installing PHP CLI binary:        /usr/local/php/bin/
Installing PHP CLI man page:      /usr/local/php/php/man/man1/
Installing phpdbg binary:         /usr/local/php/bin/
Installing phpdbg man page:       /usr/local/php/php/man/man1/
Installing PHP CGI binary:        /usr/local/php/bin/
Installing PHP CGI man page:      /usr/local/php/php/man/man1/
Installing build environment:     /usr/local/php/lib/php/build/
Installing header files:           /usr/local/php/include/php/
Installing helper programs:       /usr/local/php/bin/
  program: phpize
  program: php-config
Installing man pages:             /usr/local/php/php/man/man1/
  page: phpize.1
  page: php-config.1
Installing PEAR environment:      /usr/local/php/lib/php/
[PEAR] Archive_Tar    - already installed: 1.4.0
[PEAR] Console_Getopt - already installed: 1.4.1
[PEAR] Structures_Graph- already installed: 1.1.1
[PEAR] XML_Util       - already installed: 1.3.0
[PEAR] PEAR           - already installed: 1.10.1
Warning! a PEAR user config file already exists from a previous PEAR installation at '/home/apshenichnikov/.pearrc'. You may probably want to remove it.
Wrote PEAR system config file at: /usr/local/php/etc/pear.conf
You may want to add: /usr/local/php/lib/php to your php.ini include_path
/home/apshenichnikov/php-src/build/shtool install -c ext/phar/phar.phar /usr/local/php/bin
ln -s -f phar.phar /usr/local/php/bin/phar
Installing PDO headers:           /usr/local/php/include/php/ext/pdo/
</code>```

When I run phpinfo I get: "Thread Safety    disabled"

When I try to install pthreads via pecl I get:

```<code>apshenichnikov@IAS-WS-UX02:~/php-src$ sudo pecl install pthreads
downloading pthreads-3.1.6.tgz ...
Starting to download pthreads-3.1.6.tgz (80,932 bytes)
...................done: 80,932 bytes
28 source files, building
running: phpize
Configuring for:
PHP Api Version:         20151012
Zend Module Api No:      20151012
Zend Extension Api No:   320151012
building in /tmp/pear/temp/pear-build-rootkhkb7n/pthreads-3.1.6
running: /tmp/pear/temp/pthreads/configure --with-php-config=/usr/bin/php-config
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for a sed that does not truncate output... /bin/sed
checking for cc... cc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether cc accepts -g... yes
checking for cc option to accept ISO C89... none needed
checking how to run the C preprocessor... cc -E
checking for icc... no
checking for suncc... no
checking whether cc understands -c and -o together... yes
checking for system library directory... lib
checking if compiler supports -R... no
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking target system type... x86_64-pc-linux-gnu
checking for PHP prefix... /usr
checking for PHP includes... -I/usr/include/php/20151012 -I/usr/include/php/20151012/main -I/usr/include/php/20151012/TSRM -I/usr/include/php/20151012/Zend -I/usr/include/php/20151012/ext -I/usr/include/php/20151012/ext/date/lib
checking for PHP extension directory... /usr/lib/php/20151012
checking for PHP installed headers prefix... /usr/include/php/20151012
checking if debug is enabled... no
checking if zts is enabled... no
checking for re2c... re2c
checking for re2c version... 0.16 (ok)
checking for gawk... gawk
checking whether to enable pthreads... yes, shared
checking whether to enable AddressSanitizer for pthreads... no
checking whether to enable dmalloc for pthreads... no
checking for ZTS... configure: error: pthreads requires ZTS, please re-compile PHP with ZTS enabled
ERROR: `/tmp/pear/temp/pthreads/configure --with-php-config=/usr/bin/php-config' failed
</code>```

I is sure that that pecl and apache2 uses php recently compiled.

I recomiled PHP using differend branches and make clean.

It is always same result.

答:
Whilst you have built a new copy of PHP, you aren't using it when building the pthreads extension. You can see this in the output from the ./configure command, where the include files are pointing to your (presumably old) PHP installation:

checking for PHP includes... -I/usr/include/php/20151012 -I/usr/include/php/20151012/main -I/usr/include/php/20151012/TSRM -I/usr/include/php/20151012/Zend -I/usr/include/php/20151012/ext -I/usr/include/php/20151012/ext/date/lib

You can fix this by specifying where the config binary is for your fresh build of PHP using the --with-php-config setting. According to your installation, it should be located at /usr/local/php/bin/php-config

Title: Enable Thread Safety for php 7.1

Body:
I clone php 7.1:

apshenichnikov@IAS-WS-UX02:~/php-src$ git status
On branch PHP-7.1

I make ./buildconf --force

I run:

./configure \
  --enable-hash \
  --prefix=/usr/local/php \
  --enable-maintainer-zts \
  --with-tsrm-pthreads \
  --with-pdo-oci=shared,instantclient,/opt/oracle/instantclient,12.1

I successfully run make & make install:

apshenichnikov@IAS-WS-UX02:~/php-src$ sudo make install
Installing shared extensions:     /usr/local/php/lib/php/extensions/no-debug-zts-20151012/
Installing PHP CLI binary:        /usr/local/php/bin/
Installing PHP CLI man page:      /usr/local/php/php/man/man1/
Installing phpdbg binary:         /usr/local/php/bin/
Installing phpdbg man page:       /usr/local/php/php/man/man1/
Installing PHP CGI binary:        /usr/local/php/bin/
Installing PHP CGI man page:      /usr/local/php/php/man/man1/
Installing build environment:     /usr/local/php/lib/php/build/
Installing header files:           /usr/local/php/include/php/
Installing helper programs:       /usr/local/php/bin/
  program: phpize
  program: php-config
Installing man pages:             /usr/local/php/php/man/man1/
  page: phpize.1
  page: php-config.1
Installing PEAR environment:      /usr/local/php/lib/php/
[PEAR] Archive_Tar    - already installed: 1.4.0
[PEAR] Console_Getopt - already installed: 1.4.1
[PEAR] Structures_Graph- already installed: 1.1.1
[PEAR] XML_Util       - already installed: 1.3.0
[PEAR] PEAR           - already installed: 1.10.1
Warning! a PEAR user config file already exists from a previous PEAR installation at '/home/apshenichnikov/.pearrc'. You may probably want to remove it.
Wrote PEAR system config file at: /usr/local/php/etc/pear.conf
You may want to add: /usr/local/php/lib/php to your php.ini include_path
/home/apshenichnikov/php-src/build/shtool install -c ext/phar/phar.phar /usr/local/php/bin
ln -s -f phar.phar /usr/local/php/bin/phar
Installing PDO headers:           /usr/local/php/include/php/ext/pdo/

When I run phpinfo I get: "Thread Safety    disabled"

When I try to install pthreads via pecl I get:

apshenichnikov@IAS-WS-UX02:~/php-src$ sudo pecl install pthreads
downloading pthreads-3.1.6.tgz ...
Starting to download pthreads-3.1.6.tgz (80,932 bytes)
...................done: 80,932 bytes
28 source files, building
running: phpize
Configuring for:
PHP Api Version:         20151012
Zend Module Api No:      20151012
Zend Extension Api No:   320151012
building in /tmp/pear/temp/pear-build-rootkhkb7n/pthreads-3.1.6
running: /tmp/pear/temp/pthreads/configure --with-php-config=/usr/bin/php-config
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for a sed that does not truncate output... /bin/sed
checking for cc... cc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether cc accepts -g... yes
checking for cc option to accept ISO C89... none needed
checking how to run the C preprocessor... cc -E
checking for icc... no
checking for suncc... no
checking whether cc understands -c and -o together... yes
checking for system library directory... lib
checking if compiler supports -R... no
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking target system type... x86_64-pc-linux-gnu
checking for PHP prefix... /usr
checking for PHP includes... -I/usr/include/php/20151012 -I/usr/include/php/20151012/main -I/usr/include/php/20151012/TSRM -I/usr/include/php/20151012/Zend -I/usr/include/php/20151012/ext -I/usr/include/php/20151012/ext/date/lib
checking for PHP extension directory... /usr/lib/php/20151012
checking for PHP installed headers prefix... /usr/include/php/20151012
checking if debug is enabled... no
checking if zts is enabled... no
checking for re2c... re2c
checking for re2c version... 0.16 (ok)
checking for gawk... gawk
checking whether to enable pthreads... yes, shared
checking whether to enable AddressSanitizer for pthreads... no
checking whether to enable dmalloc for pthreads... no
checking for ZTS... configure: error: pthreads requires ZTS, please re-compile PHP with ZTS enabled
ERROR: `/tmp/pear/temp/pthreads/configure --with-php-config=/usr/bin/php-config' failed

I is sure that that pecl and apache2 uses php recently compiled.

I recomiled PHP using differend branches and make clean.

It is always same result.


问:
Cordova how to use drawables
Got a html file that uses a background image.
I want to add the background-image according the the size of the phone.
I've learnt about the

```<code><platform name="android">
  <resource-file src="www/res/drawable-hdpi/yourImage.png" target="res/drawable-hdpi/yourImage.png" />
</platform>
</code>```

statement, that adds the drawable in the right folder.
My question is, what to put in the html/(css) file so that later, the right background should be used according to the phone's size.
Thanks in advance...

答:
Solved, here's the solution for the new commers:</p>

```<code>initBackground: function(){
    var value = "url(\"img/Sign-in-background/Sign-in-background-";
    if(screen.width <= 200 && screen.height <= 320)
        value += "ldpi-portrait.png\")";
    else if(screen.width <= 320 && screen.height <= 480)
        value += "mdpi-portrait.png\")";
    else if(screen.width <= 480 && screen.height <= 800)
        value += "hdpi-portrait.png\")";
    else
        value += "xhdpi-portrait.png\")";
    alert(value);
    var body = document.querySelector("#body");
        body.style.backgroundImage = value;
}
</code>```

Title: Cordova how to use drawables

Body:
Got a html file that uses a background image.
I want to add the background-image according the the size of the phone.
I've learnt about the

<platform name="android">
  <resource-file src="www/res/drawable-hdpi/yourImage.png" target="res/drawable-hdpi/yourImage.png" />
</platform>

statement, that adds the drawable in the right folder.
My question is, what to put in the html/(css) file so that later, the right background should be used according to the phone's size.
Thanks in advance...

Body:
Solved, here's the solution for the new commers:

initBackground: function(){
    var value = "url(\"img/Sign-in-background/Sign-in-background-";
    if(screen.width <= 200 && screen.height <= 320)
        value += "ldpi-portrait.png\")";
    else if(screen.width <= 320 && screen.height <= 480)
        value += "mdpi-portrait.png\")";
    else if(screen.width <= 480 && screen.height <= 800)
        value += "hdpi-portrait.png\")";
    else
        value += "xhdpi-portrait.png\")";
    alert(value);
    var body = document.querySelector("#body");
        body.style.backgroundImage = value;
}


问:
How can I select the first word of every line of a block of text?
I'm trying to select each first word, to wrap it in a specific span.

Lorem ipsum dolor sit amet,
  consectetur adipiscing elit. Cras
  sagittis nunc non nisi venenatis
  auctor. Aliquam consectetur pretium
  sapien, eget congue purus egestas nec.
  Maecenas sed purus ut turpis varius
  dictum. Praesent a nunc ipsum, id
  mattis odio. Donec rhoncus posuere
  bibendum. Fusce nulla elit, laoreet
  non posuere.

If this is the text, the script should select Lorem, Aliquam, varius and nulla.

答:
Try this:

$(function() {
  $('p').each(function() {
    var text_splited = $(this).text().split(" ");
    $(this).html(""+text_splited.shift()+" "+text_splited.join(" "));
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor.</p>
<p>Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum.</p>
<p>Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</p></code>```

Body:
Try this:

$(function() {
  $('p').each(function() {
    var text_splited = $(this).text().split(" ");
    $(this).html("<strong>"+text_splited.shift()+"</strong> "+text_splited.join(" "));
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor.</p>
<p>Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum.</p>
<p>Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</p>


问:
How to split string in ruby
I have a string:

```<code>"1 chocolate bar at 25"
</code>```

and I want to split this string into:

```<code> [1, "chocolate bar", 25]
</code>```

I don't know how to write a regex for this split. And I wanted to know whether there are any other functions to accomplish it.

答:
It is not necessary to use a regular expression.</p>

```<code>str = "1 chocolate bar, 3 donuts and a 7up at 25"

i1 = str.index(' ')
  #=> 1
i2 = str.rindex(' at ')
  #=> 35
[str[0,i1].to_i, str[i1+1..i2-1], str[i2+3..-1].to_i]
  #=> [1, "chocolate bar, 3 donuts and a 7up", 25]
</code>```

Title: How to split string in ruby

Body:
I have a string:

"1 chocolate bar at 25"

and I want to split this string into:

 [1, "chocolate bar", 25]

I don't know how to write a regex for this split. And I wanted to know whether there are any other functions to accomplish it.

Body:
It is not necessary to use a regular expression.

str = "1 chocolate bar, 3 donuts and a 7up at 25"

i1 = str.index(' ')
  #=> 1
i2 = str.rindex(' at ')
  #=> 35
[str[0,i1].to_i, str[i1+1..i2-1], str[i2+3..-1].to_i]
  #=> [1, "chocolate bar, 3 donuts and a 7up", 25]


问:
Using JS function to open Docusign in new tab
I am attempting to open a new docusign tab in my salesforce application. I understand I need to construct a url for this, but do not know what are the required parameters to be passed. So the url will look something like /apex/dsfs__DocuSign_CreateEnvelope?
Where can I see the list of parameters and what is minimum required and what is optional? I have envelope Id and Document Id. I need to open a new tab where it shows the envelope populated with all the fields like signers and documents attached.I need to open this page with attachments and everything in the envelope

答: I found a solution. I am not using javascript but using apex making a post request to get the embedded signing url.</p>


问:
VBA separate two double digit values by a slash in a single cell
I feel like this should be relatively straight forward, but I cannot seem to find something that works.

I want to be able to separate two values in a VBA macro that are previously defined as values after doing some preliminary calculations. I then want to be able to put both of these values in the same cell, separated by a slash ("/").

Here are two codes I have written by neither seem to get the job done:

```<code>Sub Macro3()

TotalK = 10
BB = 15

ActiveCell.Value = "=TotalK &""/""& BB"

End Sub
</code>```

The other way I have attempted this (which is extremely inefficient):

```<code>If TotalK > 9 Then
     wsNew.Range("E45").NumberFormat = "00""/""0": wsNew.Range("E45").Value = TotalK & BB
ElseIf BB > 9 Then
     wsNew.Range("E45").NumberFormat = "0""/""00": wsNew.Range("E45").Value = TotalK & BB
ElseIf TotalK > 9 And BB > 9 Then
     wsNew.Range("E45").NumberFormat = "00""/""00": wsNew.Range("E45").Value = TotalK & BB
Else
     wsNew.Range("E45").NumberFormat = "0""/""0": wsNew.Range("E45").Value = TotalK & BB
End If
</code>```

The second method words, except for when TotalK and BB both exceed 9. The output is 211/7, for example, when it should be 21/17.

答:
Was able to find a simple workaround:</p>

```<code>ActiveCell.NumberFormat = "@"
ActiveCell.Value = TotalK & "/" & BB
</code>```

Body:
I feel like this should be relatively straight forward, but I cannot seem to find something that works.

I want to be able to separate two values in a VBA macro that are previously defined as values after doing some preliminary calculations. I then want to be able to put both of these values in the same cell, separated by a slash ("/").

Here are two codes I have written by neither seem to get the job done:

Sub Macro3()

TotalK = 10
BB = 15

ActiveCell.Value = "=TotalK &""/""& BB"

End Sub

The other way I have attempted this (which is extremely inefficient):

If TotalK > 9 Then
     wsNew.Range("E45").NumberFormat = "00""/""0": wsNew.Range("E45").Value = TotalK & BB
ElseIf BB > 9 Then
     wsNew.Range("E45").NumberFormat = "0""/""00": wsNew.Range("E45").Value = TotalK & BB
ElseIf TotalK > 9 And BB > 9 Then
     wsNew.Range("E45").NumberFormat = "00""/""00": wsNew.Range("E45").Value = TotalK & BB
Else
     wsNew.Range("E45").NumberFormat = "0""/""0": wsNew.Range("E45").Value = TotalK & BB
End If

The second method words, except for when TotalK and BB both exceed 9. The output is 211/7, for example, when it should be 21/17.

Body:
Was able to find a simple workaround:

ActiveCell.NumberFormat = "@"
ActiveCell.Value = TotalK & "/" & BB


问:
Decrypt webpage cookies
I have a rails website, how do I write a program to decrypt a webpage's cookies in JAVA?

```<code>For example, I have the cookies from my rails webpage:
issp_session=BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJWVhODhhYmMyMjgwNDA2M2NkNjI2ZjE5MWM5ZjVkYzlkBjsAVEkiFmFjY291bnRfcmV0dXJuX3RvBjsARiIGL0kiEF9jc3JmX3Rva2VuBjsARkkiMTJpOUszQmFablpnSkJvYW5JaFk5dWdWWGFWV3M2K0dTNXVwcFhZbzkxWFU9BjsARg%3D%3D--7f3a5f578c9199ed11d44f0deb842dde9e267e8b
</code>```

I know
BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJWVhODhhYmMyMjgwNDA2M2NkNjI2ZjE5MWM5ZjVkYzlkBjsAVEkiFmFjY291bnRfcmV0dXJuX3RvBjsARiIGL0kiEF9jc3JmX3Rva2VuBjsARkkiMTJpOUszQmFablpnSkJvYW5JaFk5dWdWWGFWV3M2K0dTNXVwcFhZbzkxWFU9BjsARg%3D%3D--7f3a5f578c9199ed11d44f0deb842dde9e267e8b is the cookies that has been encoded and 7f3a5f578c9199ed11d44f0deb842dde9e267e8b is the key of this cookies.

So my question is how do I write a program to actually decrypt this cookies?

答:
You should find out the algorithm used to encrypt/decrypt the cookie that Rails uses and then translate that to Java.

A while back, I have provided the answer for How to decrypt a Rails 5 session cookie manually? and used my Ruby implementation to translate that to Lua (my gist), so I could decrypt Rails session cookie in Nginx.

Title: Decrypt webpage cookies

Body:
I have a rails website, how do I write a program to decrypt a webpage's cookies in JAVA?

For example, I have the cookies from my rails webpage:
issp_session=BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJWVhODhhYmMyMjgwNDA2M2NkNjI2ZjE5MWM5ZjVkYzlkBjsAVEkiFmFjY291bnRfcmV0dXJuX3RvBjsARiIGL0kiEF9jc3JmX3Rva2VuBjsARkkiMTJpOUszQmFablpnSkJvYW5JaFk5dWdWWGFWV3M2K0dTNXVwcFhZbzkxWFU9BjsARg%3D%3D--7f3a5f578c9199ed11d44f0deb842dde9e267e8b

I know
BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJWVhODhhYmMyMjgwNDA2M2NkNjI2ZjE5MWM5ZjVkYzlkBjsAVEkiFmFjY291bnRfcmV0dXJuX3RvBjsARiIGL0kiEF9jc3JmX3Rva2VuBjsARkkiMTJpOUszQmFablpnSkJvYW5JaFk5dWdWWGFWV3M2K0dTNXVwcFhZbzkxWFU9BjsARg%3D%3D--7f3a5f578c9199ed11d44f0deb842dde9e267e8b is the cookies that has been encoded and 7f3a5f578c9199ed11d44f0deb842dde9e267e8b is the key of this cookies.

So my question is how do I write a program to actually decrypt this cookies?


问:
How to convert API response parameters to snake case in Swagger?
I've changed my API response parameters to snake case by adding below line in WebApiConfig.cs

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver
        {
            NamingStrategy = new SnakeCaseNamingStrategy()
        };
    }
}
</code>```

Currently I'm generating API documentation by using Swagger and I'm looking for same setup in Swagger response? Is there any option in Swagger for this?

Current document Output:

Expected document Output:

答:
Try using an IDocumentFilter, you can do all kind of changes to your document output (aka SwaggerDocument)

Here are some examples on GitHub

Body:
I've changed my API response parameters to snake case by adding below line in WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver
        {
            NamingStrategy = new SnakeCaseNamingStrategy()
        };
    }
}

Currently I'm generating API documentation by using Swagger and I'm looking for same setup in Swagger response? Is there any option in Swagger for this?

Current document Output:

Expected document Output:


问:
Change the way the locale is displayed in url with Symfony3
Symfony3 displays by default local in url in that way : website.com/en_GB/ (or "en_gb").

How to change that to display it in that way: website.com/en-gb/ ?

With the below controller and calling to website.com/en-GB/ returns the homepage in French (default language is French). Calling to website.com/en_GB/ returns the page in English.

en_GB : english of UK

Controller:

```<code>/**
 * @Route("/{_locale}/", name="homepageLocale")
 * @Template("AppBundle:Default:homepage/homepage.html.twig")
 */
 public function homepageLocaleAction(Request $request) {
    return [];
 }
</code>```

It's seems that the code decoding the locale is that one:

```<code>   Symfony\Component\Intl\Locale.php

   public static function getFallback($locale)
    {
        if (false === $pos = strrpos($locale, '_')) {
            if (self::$defaultFallback === $locale) {
                return 'root';
            }

            // Don't return default fallback for "root", "meta" or others
            // Normal locales have two or three letters
            if (strlen($locale) < 4) {
                return self::$defaultFallback;
            }

            return;
        }

        return substr($locale, 0, $pos);
    }
</code>```

答:
To achieve that you might need decorate "completely" the HttpKernel LocaleListener to something like this:

```<code>// AppBundle\EventListener\LocaleListener

private function setLocale(Request $request)
{
    if ($locale = $request->attributes->get('_locale')) {
        if (false !== strpos($locale, '-')) {
            // translate en-gb to en_GB
            $localeParts = explode('-', $locale);
            $locale = $localeParts[0].'_'.strtoupper($localeParts[1]);
        }

        $request->setLocale($locale);
    }
}

private function setRouterContext(Request $request)
{
    if (null !== $this->router) {
        $locale = $request->getLocale();

        // translate en_GB to en-gb
        $locale = strtolower(strtr($locale, '_', '-'));

        $this->router->getContext()->setParameter('_locale', $locale);
    }
}
</code>```

Note: These two methods are private, it's why we need copy+paste the complete code of the original listener to change its behavior.

More about "How to Decorate Services" here, or creates you own compiler pass to exchange the service class of the locale_listener definition.

Body:
Symfony3 displays by default local in url in that way : website.com/en_GB/ (or "en_gb").

How to change that to display it in that way: website.com/en-gb/ ?

With the below controller and calling to website.com/en-GB/ returns the homepage in French (default language is French). Calling to website.com/en_GB/ returns the page in English.

en_GB : english of UK

Controller:

/**
 * @Route("/{_locale}/", name="homepageLocale")
 * @Template("AppBundle:Default:homepage/homepage.html.twig")
 */
 public function homepageLocaleAction(Request $request) {
    return [];
 }

It's seems that the code decoding the locale is that one:

   Symfony\Component\Intl\Locale.php

   public static function getFallback($locale)
    {
        if (false === $pos = strrpos($locale, '_')) {
            if (self::$defaultFallback === $locale) {
                return 'root';
            }

            // Don't return default fallback for "root", "meta" or others
            // Normal locales have two or three letters
            if (strlen($locale) < 4) {
                return self::$defaultFallback;
            }

            return;
        }

        return substr($locale, 0, $pos);
    }

Body:
To achieve that you might need decorate "completely" the HttpKernel LocaleListener to something like this:

// AppBundle\EventListener\LocaleListener

private function setLocale(Request $request)
{
    if ($locale = $request->attributes->get('_locale')) {
        if (false !== strpos($locale, '-')) {
            // translate en-gb to en_GB
            $localeParts = explode('-', $locale);
            $locale = $localeParts[0].'_'.strtoupper($localeParts[1]);
        }

        $request->setLocale($locale);
    }
}

private function setRouterContext(Request $request)
{
    if (null !== $this->router) {
        $locale = $request->getLocale();

        // translate en_GB to en-gb
        $locale = strtolower(strtr($locale, '_', '-'));

        $this->router->getContext()->setParameter('_locale', $locale);
    }
}

Note: These two methods are private, it's why we need copy+paste the complete code of the original listener to change its behavior.

More about "How to Decorate Services" here, or creates you own compiler pass to exchange the service class of the locale_listener definition.


问:
Convert array to string? in Swift
I am working with the ActionSheetPicker 3.0 (https://github.com/skywinder/ActionSheetPicker-3.0) picker and am having a newbie problem of working with the return values from the ActionSheetMultipleStringPicker.  I've got the control running and can return values from it, but I want to be able to put the return values from the picker into separate variables or into something that I can join together.  I've found numerous examples, but can't figure out how to get them to work.

What I think I've found through debugging is that ActionSheetMultipleStringPicker returns an array of Any?.

Debugging shows the following:

values  Any?    some
payload_data_0  Builtin.RawPointer  0x60800044fdb0  0x000060800044fdb0 -> 0x000000010dacddd8 (void *)0x000000010dacdf18: __NSArrayI
payload_data_1  Builtin.RawPointer  0x335392d30 0x0000000335392d30
payload_data_2  Builtin.RawPointer  0x10d28d798 0x000000010d28d798 libobjc.A.dylib`objc_retainAutoreleasedReturnValue + 35
instance_type   Builtin.RawPointer  0x60800005d5c8  0x000060800005d5c8

values is the return value from the picker.

A couple things that I've tried are:

```<code>let stringText: String? = String(describing: values)
print(stringText)
</code>```

This prints:

Optional("Optional(<__NSArrayI 0x60800044be20>(\nOne,\nMany,\naaa\n)\n)")

I've also tried:

```<code>print("\(values as! NSArray)")
</code>```

This is the closest I've gotten to the results I'm looking for which is:

(
    One,
    Many,
    aaa
)

Can anyone provide some assistance getting the value of 'values' into something that I can separate into three different string variables?

My code for the picker is:

```<code>    let a = ActionSheetMultipleStringPicker.init(title: "Fertilizer Setup", rows: [

        // TODO: Read values from database
        ["One", "Two", "A lot"],
        ["Many", "Many more", "Infinite"],
        ["aaa","sss","ccc","xxxx"]
        ], initialSelection: [0, 0, 0],
           doneBlock: {
               picker, indexes, values in

               let stringText: String? = String(describing: values)

               print(stringText)

               print("\(values as! NSArray)")
    },
           cancel: {ActionMultipleStringCancelBlock in return }, origin: sender)

    a?.setCancelButton(UIBarButtonItem(title: "My own title", style: UIBarButtonItemStyle.plain, target: self, action: nil))
    a?.show()
</code>```

答:
I was able to figure this out.  I changed my doneBlock code to be:

```<code>doneBlock: {
            picker, indexes, values in
                 let fertilzerPicker:  NSArray = values as! NSArray
                 self.row.value!.name = fertilzerPicker[0] as! String
                 self.row.value!.amount = fertilzerPicker[1] as! Int
                 self.row.value!.unitOfMeasurement = fertilzerPicker[2] as! String
}
</code>```

The key line being:

```<code>let fertilzerPicker:  NSArray = values as! NSArray
</code>```

Creating fertilzerPicker allowed me to get the individual elements of the array.

Title: Convert array to string? in Swift

Body:
I am working with the ActionSheetPicker 3.0 (https://github.com/skywinder/ActionSheetPicker-3.0) picker and am having a newbie problem of working with the return values from the ActionSheetMultipleStringPicker.  I've got the control running and can return values from it, but I want to be able to put the return values from the picker into separate variables or into something that I can join together.  I've found numerous examples, but can't figure out how to get them to work.

What I think I've found through debugging is that ActionSheetMultipleStringPicker returns an array of Any?.

Debugging shows the following:

values  Any?    some
payload_data_0  Builtin.RawPointer  0x60800044fdb0  0x000060800044fdb0 -> 0x000000010dacddd8 (void *)0x000000010dacdf18: __NSArrayI
payload_data_1  Builtin.RawPointer  0x335392d30 0x0000000335392d30
payload_data_2  Builtin.RawPointer  0x10d28d798 0x000000010d28d798 libobjc.A.dylib`objc_retainAutoreleasedReturnValue + 35
instance_type   Builtin.RawPointer  0x60800005d5c8  0x000060800005d5c8

values is the return value from the picker.

A couple things that I've tried are:

let stringText: String? = String(describing: values)
print(stringText)

This prints:

Optional("Optional(<__NSArrayI 0x60800044be20>(\nOne,\nMany,\naaa\n)\n)")

I've also tried:

print("\(values as! NSArray)")

This is the closest I've gotten to the results I'm looking for which is:

(
    One,
    Many,
    aaa
)

Can anyone provide some assistance getting the value of 'values' into something that I can separate into three different string variables?

My code for the picker is:

    let a = ActionSheetMultipleStringPicker.init(title: "Fertilizer Setup", rows: [

        // TODO: Read values from database
        ["One", "Two", "A lot"],
        ["Many", "Many more", "Infinite"],
        ["aaa","sss","ccc","xxxx"]
        ], initialSelection: [0, 0, 0],
           doneBlock: {
               picker, indexes, values in

               let stringText: String? = String(describing: values)

               print(stringText)

               print("\(values as! NSArray)")
    },
           cancel: {ActionMultipleStringCancelBlock in return }, origin: sender)

    a?.setCancelButton(UIBarButtonItem(title: "My own title", style: UIBarButtonItemStyle.plain, target: self, action: nil))
    a?.show()

Body:
I was able to figure this out.  I changed my doneBlock code to be:

doneBlock: {
            picker, indexes, values in
                 let fertilzerPicker:  NSArray = values as! NSArray
                 self.row.value!.name = fertilzerPicker[0] as! String
                 self.row.value!.amount = fertilzerPicker[1] as! Int
                 self.row.value!.unitOfMeasurement = fertilzerPicker[2] as! String
}

The key line being:

let fertilzerPicker:  NSArray = values as! NSArray

Creating fertilzerPicker allowed me to get the individual elements of the array.


问:
Find pairs of files in one directory with a specific pattern
I need to find pairs of files with a specific pattern in one directory:

HU_IP_number_something.bam & HU_inp_number_something.bam
  NOC_IP_number_something.bam & NOC_inp_number_something.bam

Numbers are 1...N for each pair

I have a solution but it works only for one set of files HU_* or NOC_* in one directory.
How can I improve it to find pairs, when both HU_* and NOC_* are in one directory?

```<code>for ip in *IP*.bam
   do
        num=$(echo $ip | sed 's/[^0-9]//g')
        input=$(find -name *_inp_${num}*.bam)
        echo ip sample: $ip
        echo input sample: $input
   done
</code>```

Examples of files in one directory:

```<code>HU_inp_1-sorted.bam
HU_IP_1-sorted.bam
NOC_inp_1-sorted.bam
NOC_IP_1-sorted.bam
</code>```

for 1,2,3,...N

答:
The following builds an array, $a for each iteration of a for loop.

```<code>$ for f in *IP*.bam; do s=${f#*_}; a=( *${s} ); declare -p a; done
declare -a a=([0]="HU_IP_number_something.bam" [1]="NOC_IP_number_something.bam")
declare -a a=([0]="HU_IP_number_something.bam" [1]="NOC_IP_number_something.bam")
</code>```

This works steps through all the files you've specified in your filespec, stripping off the first "field" (as denoted by the underscore separator), and using globbing to collect the relevant files in the array.

You can test for the length of the array (${#a[@]}) to make sure you have two entries.

If you want to group by the second field instead of the first, you need a little more processing:

```<code>$ for f in *IP*.bam; do s1=${f%%_*}; s2=${f#*_}; s2=${s2#*_}; a=( ${s1}*${s2} ); declare -p a; done
declare -a a=([0]="HU_IP_number_something.bam" [1]="HU_inp_number_something.bam")
declare -a a=([0]="NOC_IP_number_something.bam" [1]="NOC_inp_number_something.bam")
</code>```

The technique here, using ${var#pattern} and ${var%pattern} is called Parameter Expansion, and you can find more details about it in the bash man page.  Here too.

Body:
I need to find pairs of files with a specific pattern in one directory:

HU_IP_number_something.bam & HU_inp_number_something.bam
  NOC_IP_number_something.bam & NOC_inp_number_something.bam

Numbers are 1...N for each pair

I have a solution but it works only for one set of files HU_* or NOC_* in one directory.
How can I improve it to find pairs, when both HU_* and NOC_* are in one directory?

for ip in *IP*.bam
   do
        num=$(echo $ip | sed 's/[^0-9]//g')
        input=$(find -name *_inp_${num}*.bam)
        echo ip sample: $ip
        echo input sample: $input
   done

Examples of files in one directory:

HU_inp_1-sorted.bam
HU_IP_1-sorted.bam
NOC_inp_1-sorted.bam
NOC_IP_1-sorted.bam

for 1,2,3,...N

Body:
The following builds an array, $a for each iteration of a for loop.

$ for f in *IP*.bam; do s=${f#*_}; a=( *${s} ); declare -p a; done
declare -a a=([0]="HU_IP_number_something.bam" [1]="NOC_IP_number_something.bam")
declare -a a=([0]="HU_IP_number_something.bam" [1]="NOC_IP_number_something.bam")

This works steps through all the files you've specified in your filespec, stripping off the first "field" (as denoted by the underscore separator), and using globbing to collect the relevant files in the array.

You can test for the length of the array (${#a[@]}) to make sure you have two entries.

If you want to group by the second field instead of the first, you need a little more processing:

$ for f in *IP*.bam; do s1=${f%%_*}; s2=${f#*_}; s2=${s2#*_}; a=( ${s1}*${s2} ); declare -p a; done
declare -a a=([0]="HU_IP_number_something.bam" [1]="HU_inp_number_something.bam")
declare -a a=([0]="NOC_IP_number_something.bam" [1]="NOC_inp_number_something.bam")

The technique here, using ${var#pattern} and ${var%pattern} is called Parameter Expansion, and you can find more details about it in the bash man page.  Here too.


问:
Angular 2 getBoundingClientRect from component
I have component like below which is basically a popover:

```<code>import {Component, Input, ViewChild} from 'angular2/core'

declare var $: any;

@Component({
  selector: 'popover',
  template: `
  <div id="temp" [ngStyle]="{'position':'absolute', 'z-index':'10000', 'top': y + 'px', left: x + 'px'}"
       [hidden]="hidden" #temp>
    <ng-content></ng-content>
  </div>
  `
})
export class Popover {

  @ViewChild("temp") temp;

  private hidden: boolean = true;
  private y: number = 0;
  private x: number = 0;

  show(target, shiftx = 0, shifty = 0){
    let position = $(target).offset();
    this.x = position.left + shiftx;
    this.y = position.top + shifty;
    this.hidden = false;

    console.log("#temp", this.temp.nativeElement.getBoundingClientRect()); //all 0s
    console.log("temp id", document.getElementById('temp').getBoundingClientRect()); //all 0s
  }

  hide(){
    this.hidden = true;
  }
}
</code>```

Inside the show() method I am trying to get the result of getBoundingClientRect() but its returning 0 for all properties but when I type in document.getElementById("temp").getBoundingClientRect() from Chrome's console I get proper result with actual values in the properties. Why the difference and what can I do to get the actual value from my component?

答:
I would use ngAfterContentChecked(). It works perfectly fine for me.

```<code>import { AfterContentChecked  } from '@angular/core';

export class ModelComponent implements AfterContentChecked  {
   ngAfterContentChecked() {
        //your code
    }
}
</code>```

I hope it helps. :)

Body:
I have component like below which is basically a popover:

import {Component, Input, ViewChild} from 'angular2/core'

declare var $: any;

@Component({
  selector: 'popover',
  template: `

    <ng-content></ng-content>

  `
})
export class Popover {

  @ViewChild("temp") temp;

  private hidden: boolean = true;
  private y: number = 0;
  private x: number = 0;

  show(target, shiftx = 0, shifty = 0){
    let position = $(target).offset();
    this.x = position.left + shiftx;
    this.y = position.top + shifty;
    this.hidden = false;

    console.log("#temp", this.temp.nativeElement.getBoundingClientRect()); //all 0s
    console.log("temp id", document.getElementById('temp').getBoundingClientRect()); //all 0s
  }

  hide(){
    this.hidden = true;
  }
}

Inside the show() method I am trying to get the result of getBoundingClientRect() but its returning 0 for all properties but when I type in document.getElementById("temp").getBoundingClientRect() from Chrome's console I get proper result with actual values in the properties. Why the difference and what can I do to get the actual value from my component?

Body:
I would use ngAfterContentChecked(). It works perfectly fine for me.

import { AfterContentChecked  } from '@angular/core';

export class ModelComponent implements AfterContentChecked  {
   ngAfterContentChecked() {
        //your code
    }
}

I hope it helps. :)