问:
How can I implement a makefile-style algorithm in python
I am implementing an acoustic feature extraction system in python, and I need to implement a makefile-style algorithm to ensure that all blocks in the feature extraction system are run in the correct order, and without repeating any feature extractions stages.

The input to this feature extraction system will be a graph detailing the links between the feature extraction blocks, and I'd like to work out which functions to run when based upon the graph.

An example of such a system might be the following:

```<code>            ,-> [B] -> [D] ----+
input --> [A]           ^      v
            `-> [C] ----+---> [E] --> output
</code>```

and the function calls (assuming each block X is a function of the form output = X(inputs) might be something like:

```<code>a = A(input)
b = B(a)
c = C(a)
d = D(b,c)  # can't call D until both b and c are ready
output = E(d,c)   # can't call E until both c and d are ready
</code>```

I already have the function graph loaded in the form of a dictionary with each dictionary entry of the form (inputs, function) like so:

```<code>blocks = {'A' : (('input'), A),
          'B' : (('A'), B),
          'C' : (('A'), C),
          'D' : (('B','C'), D),
          'output' : (('D','C'), E)}
</code>```

I'm just currently drawing a blank on what the makefile algorithm does exactly, and how to go about implementing it. My google-fu appears to be not-very-helpful here too. If someone at least can give me a pointer to a good discussion of the makefile algorithm that would probably be a good start.

答:
As the other helpful answerers have already pointed out, what I'm after is a topological sort, but I think my particular case is a little simpler because the function graph must always start at input and end at output.

So, here is what I ended up doing (I've edited it slightly to remove some context-dependent stuff, so it may not be completely correct):

```<code>def extract(func_graph):
    def _getsignal(block,signals):
        if block in signals:
            return signals[block]
        else:
            inblocks, fn = func_graph[block]
            inputs = [_getsignal(i,signals) for i in inblocks]
            signals[block] = fn(inputs)
            return signals[block]

    def extract_func (input):
        signals = dict(input=input)
        return _getsignal('output',signals)

    return extract_func
</code>```

So now given I can set up the function with

```<code>fn = extract(blocks)
</code>```

And use it as many times as I like:

```<code>list_of_outputs = [fn(i) for i in list_of_inputs]
</code>```

I should probably also put in some checks for loops, but that is a problem for another day.

Body:
I am implementing an acoustic feature extraction system in python, and I need to implement a makefile-style algorithm to ensure that all blocks in the feature extraction system are run in the correct order, and without repeating any feature extractions stages.

The input to this feature extraction system will be a graph detailing the links between the feature extraction blocks, and I'd like to work out which functions to run when based upon the graph.

An example of such a system might be the following:

            ,-> [B] -> [D] ----+
input --> [A]           ^      v
            `-> [C] ----+---> [E] --> output

and the function calls (assuming each block X is a function of the form output = X(inputs) might be something like:

a = A(input)
b = B(a)
c = C(a)
d = D(b,c)  # can't call D until both b and c are ready
output = E(d,c)   # can't call E until both c and d are ready

I already have the function graph loaded in the form of a dictionary with each dictionary entry of the form (inputs, function) like so:

blocks = {'A' : (('input'), A),
          'B' : (('A'), B),
          'C' : (('A'), C),
          'D' : (('B','C'), D),
          'output' : (('D','C'), E)}

I'm just currently drawing a blank on what the makefile algorithm does exactly, and how to go about implementing it. My google-fu appears to be not-very-helpful here too. If someone at least can give me a pointer to a good discussion of the makefile algorithm that would probably be a good start.

Body:
As the other helpful answerers have already pointed out, what I'm after is a topological sort, but I think my particular case is a little simpler because the function graph must always start at input and end at output.

So, here is what I ended up doing (I've edited it slightly to remove some context-dependent stuff, so it may not be completely correct):

def extract(func_graph):
    def _getsignal(block,signals):
        if block in signals:
            return signals[block]
        else:
            inblocks, fn = func_graph[block]
            inputs = [_getsignal(i,signals) for i in inblocks]
            signals[block] = fn(inputs)
            return signals[block]

    def extract_func (input):
        signals = dict(input=input)
        return _getsignal('output',signals)

    return extract_func

So now given I can set up the function with

fn = extract(blocks)

And use it as many times as I like:

list_of_outputs = [fn(i) for i in list_of_inputs]

I should probably also put in some checks for loops, but that is a problem for another day.


来源: stackexchange

问:
Retrofit: Request from full url, return error
I build the project with retrofit-2.2.0. I wanted to request a full url, but that is failed

```<code>public interface FileRetrofitServer {
@Streaming
@GET
Call<ResponseBody> downloadFileAsync(@Url String fileUrl);
}
</code>```

it return the message as the below:
java.lang.IllegalStateException: Base URL required.

答: I have got the answer. Base url must not be empty, you can set a default value, and then the full url will replace the Base url.</p>

ContentLicense: CC BY-SA 3.0

Body:
I build the project with retrofit-2.2.0. I wanted to request a full url, but that is failed

public interface FileRetrofitServer {
@Streaming
@GET
Call<ResponseBody> downloadFileAsync(@Url String fileUrl);
}

it return the message as the below:
java.lang.IllegalStateException: Base URL required.


问:
How to put titles for each field of a ListView item in Android
I have a Listview with a custom adapter , which displays person's data like

Barak Obama 2008

But I want to put a header with Name Surname Date but properly alligned

A draft example:

ListView Items with titles

How Can I achieve this?

thank you

答:
Custom ListView, All what you need, A xml layout for row with adapter and listview

check out this link explain Custom listview

https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView


问:
Do C# properties always have backup fields "behind the scene"?
I know that when we use properties in C#, the compiler always generate getters and setters for them in CIL (i.e., get_PropertyName and set_PropertyName), for example, consider the following piece of code:

```<code>    class Program
    {
        class Test
        {
            public string Name { get; set; }
        }
        static void Main(string[] args)
        {
            //Here I'm using reflection to inspect methods of Test class
            Type type = typeof(Test);
            foreach (var item in type.GetMethods())
            {
                Console.WriteLine(item.Name);
            }
        }
    }
</code>```

This program will produce output with the methods of Test, among which there will be get_Name and set_Name - the getter and setters I was talking about.
From my understanding then, if getters and setter are created "behind the scenes" then there should be a backing field created as well from which/to which the getters and setter get/set values.
So, from the previous example, I can use reflection to inspect fields for Test class, like that:

```<code>    static void Main(string[] args)
    {
        Type type = typeof(Test);
        foreach (var item in type.GetFields())
        {
            Console.WriteLine(item.Name);
        }
    }
</code>```

The ouput of this program is empty, I assume this is because the backing field that was created has private access, so we cannot see it. But since I don't know how to check it, can you please let me know if a backing field always gets created (even if we have a simple property with only get; and set;) ?

答:
If you mean simple properties like:

```<code>{get;set;}
</code>```

or:

```<code>{get;}
</code>```

then yes, there is a field; add BindingFlags.NonPublic | BindingFlags.Instance to your GetFields() call and you'll see it:

```<code>foreach (var item in type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
    Console.WriteLine(item.Name);
}
</code>```

It usually has an unpronouncable name involving <> - yours is <Name>k__BackingField on my machine - but: this name is a compiler feature (although a lot of serialization etc libraries make use of it, so it is unlikely to change).

But: no, properties don't by themselves always involve fields; for example:

```<code>public int Value => 42; // no field
</code>```

or

```<code>public int Name { get { return obj.Name; } set { obj.Name = value; } }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know that when we use properties in C#, the compiler always generate getters and setters for them in CIL (i.e., get_PropertyName and set_PropertyName), for example, consider the following piece of code:

    class Program
    {
        class Test
        {
            public string Name { get; set; }
        }
        static void Main(string[] args)
        {
            //Here I'm using reflection to inspect methods of Test class
            Type type = typeof(Test);
            foreach (var item in type.GetMethods())
            {
                Console.WriteLine(item.Name);
            }
        }
    }

This program will produce output with the methods of Test, among which there will be get_Name and set_Name - the getter and setters I was talking about.
From my understanding then, if getters and setter are created "behind the scenes" then there should be a backing field created as well from which/to which the getters and setter get/set values.
So, from the previous example, I can use reflection to inspect fields for Test class, like that:

    static void Main(string[] args)
    {
        Type type = typeof(Test);
        foreach (var item in type.GetFields())
        {
            Console.WriteLine(item.Name);
        }
    }

The ouput of this program is empty, I assume this is because the backing field that was created has private access, so we cannot see it. But since I don't know how to check it, can you please let me know if a backing field always gets created (even if we have a simple property with only get; and set;) ?

Body:
If you mean simple properties like:

{get;set;}

or:

{get;}

then yes, there is a field; add BindingFlags.NonPublic | BindingFlags.Instance to your GetFields() call and you'll see it:

foreach (var item in type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
    Console.WriteLine(item.Name);
}

It usually has an unpronouncable name involving <> - yours is <Name>k__BackingField on my machine - but: this name is a compiler feature (although a lot of serialization etc libraries make use of it, so it is unlikely to change).

But: no, properties don't by themselves always involve fields; for example:

public int Value => 42; // no field

or

public int Name { get { return obj.Name; } set { obj.Name = value; } }


问:
How to Make Bootstrap 3 Thumbnail Background Transparent
I want to make the the Backgrounds of the Thumbnails transparent.

I have tried overwriting the CSS by the using the following code combinations:

First:

```<code>    .thumbnail{
    background-color:rgba(0,0,0,0.5);
    background-color: #000;}
</code>```

Second:

```<code>    .thumbnail{
     background-color:transparent;
     background: transparent;}
</code>```

None of this seems to work.

答:
Add a style to the div like so</p>

```<code><div class='thumbnail' style='background-color: transparent'>
</code>```

Body:
I want to make the the Backgrounds of the Thumbnails transparent.

I have tried overwriting the CSS by the using the following code combinations:

First:

    .thumbnail{
    background-color:rgba(0,0,0,0.5);
    background-color: #000;}

Second:

    .thumbnail{
     background-color:transparent;
     background: transparent;}

None of this seems to work.

Body:
Add a style to the div like so

<div class='thumbnail' style='background-color: transparent'>


问:
store multiple data in a vector/list for a loop
I have a code which I want to run on multiple ".RData" files (shown below)

```<code>     load("MYDAILYSALES.RData")
     load("AUDAILYSALES.RData")
     load("CNDAILYSALES.RData")
     load("SGDAILYSALES.RData")
     load("KRDAILYSALES.RData")
     load("AEDAILYSALES.RData")
     load("TWDAILYSALES.RData")
     load("JPDAILYSALES.RData")
     load("BDDAILYSALES.RData")
     load("VNDAILYSALES.RData")
     load("INDAILYSALES.RData")
     load("NZDAILYSALES.RData")
     load("IDDAILYSALES.RData")
     load("PHDAILYSALES.RData")
     load("THDAILYSALES.RData")
     load("HKDAILYSALES.RData")
</code>```

I want to save the above
a list
or
a vector
or in some way, such that I can use it to reference a for(...) loop and traverse over multiple data sources.

答:
Put your list of sources into a vector:

```<code>data_sources <- c("1.Rdata", "2.Rdata" ...)
</code>```

and loop over the resulting vector:

```<code>for (data in data_sources) {
   load(data)
}
</code>```

And if you want to combine the resulting datasets into one:

```<code>save(list=ls(), file="all_together.Rdata")
</code>```

This will save everything which is loaded in the environment, including all the data loaded from the list of Rdata files in the data_sources vector.

Body:
I have a code which I want to run on multiple ".RData" files (shown below)

     load("MYDAILYSALES.RData")
     load("AUDAILYSALES.RData")
     load("CNDAILYSALES.RData")
     load("SGDAILYSALES.RData")
     load("KRDAILYSALES.RData")
     load("AEDAILYSALES.RData")
     load("TWDAILYSALES.RData")
     load("JPDAILYSALES.RData")
     load("BDDAILYSALES.RData")
     load("VNDAILYSALES.RData")
     load("INDAILYSALES.RData")
     load("NZDAILYSALES.RData")
     load("IDDAILYSALES.RData")
     load("PHDAILYSALES.RData")
     load("THDAILYSALES.RData")
     load("HKDAILYSALES.RData")

I want to save the above
a list
or
a vector
or in some way, such that I can use it to reference a for(...) loop and traverse over multiple data sources.

Body:
Put your list of sources into a vector:

data_sources <- c("1.Rdata", "2.Rdata" ...)

and loop over the resulting vector:

for (data in data_sources) {
   load(data)
}

And if you want to combine the resulting datasets into one:

save(list=ls(), file="all_together.Rdata")

This will save everything which is loaded in the environment, including all the data loaded from the list of Rdata files in the data_sources vector.


问:
How to give System property to my test via Gradle and -D
I have a a Java program which reads a System property

```<code>System.getProperty("cassandra.ip");
</code>```

and I have a Gradle build file that I start with

```<code>gradle test -Pcassandra.ip=192.168.33.13
</code>```

or

```<code>gradle test -Dcassandra.ip=192.168.33.13
</code>```

however System.getProperty will always return null.

The only way I found was to add that in my Gradle build file via

```<code>test {
    systemProperty "cassandra.ip", "192.168.33.13"
}
</code>```

How Do I do it via -D

答:
Here's a variant that passes numerous project properties to the test JVM as system properties.  I prefer project properties over system properties to increase flexibility.

```<code>task intTest(type: Test) {
    systemProperties project.properties.subMap(["foo", "bar"])
}
</code>```

Which may be passed on the command-line:

```<code> $ gradle intTest -Pfoo=1 -Pbar=2
</code>```

And retrieved in your test:

```<code>String foo = System.getProperty("foo");
</code>```

Body:
I have a a Java program which reads a System property

System.getProperty("cassandra.ip");

and I have a Gradle build file that I start with

gradle test -Pcassandra.ip=192.168.33.13

or

gradle test -Dcassandra.ip=192.168.33.13

however System.getProperty will always return null.

The only way I found was to add that in my Gradle build file via

test {
    systemProperty "cassandra.ip", "192.168.33.13"
}

How Do I do it via -D

Body:
Here's a variant that passes numerous project properties to the test JVM as system properties.  I prefer project properties over system properties to increase flexibility.

task intTest(type: Test) {
    systemProperties project.properties.subMap(["foo", "bar"])
}

Which may be passed on the command-line:

 $ gradle intTest -Pfoo=1 -Pbar=2

And retrieved in your test:

String foo = System.getProperty("foo");


答:
But since I don't know how to check it, can you please let me know if a backup field always get created (even if we have a simple property with only get; and set; ?

An automatically implemented property, e.g.

```<code>public int ReadWriteProperty { get; set; }
public int ReadOnlyProperty { get; }
</code>```

will indeed always have a backing field generated by the compiler. But if you provide your own implementation of the getter/setter, then the compiler won't generate a field:

```<code>public int Zero => 0;

public int IgnoresSetter
{
    get { return 10; }
    set { /* Meh. Whatever you say, I'm still going to return 10 in the getter... */ }
}
</code>```

Neither of those will cause a field to be generated.

Title: Do C# properties always have backup fields "behind the scene"?

Body:
But since I don't know how to check it, can you please let me know if a backup field always get created (even if we have a simple property with only get; and set; ?

An automatically implemented property, e.g.

public int ReadWriteProperty { get; set; }
public int ReadOnlyProperty { get; }

will indeed always have a backing field generated by the compiler. But if you provide your own implementation of the getter/setter, then the compiler won't generate a field:

public int Zero => 0;

public int IgnoresSetter
{
    get { return 10; }
    set { /* Meh. Whatever you say, I'm still going to return 10 in the getter... */ }
}

Neither of those will cause a field to be generated.


问:
replace a word in a specific location
I want to run a program while scanning a range of parameters
and I need to replace a word in a specific location without matching any pattern

for example my input file contains the following lines:

```<code>...
coords xyz
O 0.0 0.0 0.0
H 1.0 1.0 0.0
H 1.0 -1.0 0.0
...
</code>```

I want substitute the 3rd word in the 66th line (in this example "-1.0") with a different ($i) value in each iteration

I know I can maintain a original_input file, do a pattern search and output it to a Input file each time :

```<code>sed  "6s/-1.0/$i/" original_input > Input
</code>```

but I'm looking for a in-place substitute while the match pattern is continuously changing

答:
For my use I wrapped yunnosch's answer within a bash script:</p>

```<code>#!/bin/bash
# substitute a word in a predefined location disregarding its value
# applied with 4 arguments: ( number of word inside a line, number of line, new value and input text)
# add a 5th argument "-i" to do a in place substitution
echo  substituting the \#$1 word in the \#$2 line with $3
declare -i a=$1
let a-=1
sed -E $5 " $2s/(\s*(\S+\s+){$a})\S+(\s+|$)/\1$3\3/;" $4
</code>```

Title: replace a word in a specific location

Body:
I want to run a program while scanning a range of parameters
and I need to replace a word in a specific location without matching any pattern

for example my input file contains the following lines:

...
coords xyz
O 0.0 0.0 0.0
H 1.0 1.0 0.0
H 1.0 -1.0 0.0
...

I want substitute the 3rd word in the 66th line (in this example "-1.0") with a different ($i) value in each iteration

I know I can maintain a original_input file, do a pattern search and output it to a Input file each time :

sed  "6s/-1.0/$i/" original_input > Input

but I'm looking for a in-place substitute while the match pattern is continuously changing

Body:
For my use I wrapped yunnosch's answer within a bash script:

#!/bin/bash
# substitute a word in a predefined location disregarding its value
# applied with 4 arguments: ( number of word inside a line, number of line, new value and input text)
# add a 5th argument "-i" to do a in place substitution
echo  substituting the \#$1 word in the \#$2 line with $3
declare -i a=$1
let a-=1
sed -E $5 " $2s/(\s*(\S+\s+){$a})\S+(\s+|$)/\1$3\3/;" $4


问:
SPARK DataFrame: select the first 3 rows of each group
I'm stuck with a similar use case as in SPARK DataFrame: select the first row of each group. Only difference is that I need to select the first 3 rows of each group. The agg function allows me to select the top value with the help of max function or by applying sort initially and then using the first function.

Is there way to achieve it using agg function after doing a groupby? If not, what is the best way to do this?

答:
```<code>import org.apache.spark.sql.functions.{row_number, max, broadcast}
import org.apache.spark.sql.expressions.Window

df=Dataframe....

val w = Window.partitionBy($"groupColumn").orderBy($"AnyColumn".desc)

val dfTop = df.withColumn("rn", row_number.over(w)).where($"rn" ===> 3).drop("rn")
dfTop.show
</code>```


问:
jQuery Modal Box with Custom Buttons
I need a plugin to display modal boxes with plugins.

Similar to something like when you add friends on facebook.

At this moment jQuery UI seems to be upto what I need

However I would like to know if there are any more possibilities.

Thanks

答:
have a look o flowplayer library

http://flowplayer.org/tools/demos/overlay/modal-dialog.html

ContentLicense: CC BY-SA 2.5

Title: jQuery Modal Box with Custom Buttons


问:
How to make a step-by-step choice?
There is a task. It is necessary to give the user a choice in the first step between 3 (input radio). After he chose one of the items he needed, a second column appears with the new column (input radio). And also after the choice in the second step appears the third step with the final choice (input radio).

It is important that the second step and the third for each selected item are new.

Help solve this problem.

I found a similar task, but it's a little unsuitable for my purposes.
Updating button content based on selection
for example

$(document).ready(function(){
  var selects = $('.drop-down');
  selects.not(':eq(0)').prop('disabled', true);
  selects.on('change', function() {
    var select = $(this),
        currentIndex = selects.index(select),
        nextIndex = currentIndex + 1;

    if (currentIndex != selects.length - 1) {
      selects.slice(nextIndex)
             .val('')
             .prop('disabled', true);

      selects.eq(nextIndex).prop('disabled', select.val() === '');
    }

  })

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="v1" class="drop-down">
  <option value="">--Выберите Вид рекламы--</option>
  <option value="1">Объявление [Товар / Услуга]</option>
  <option value="2">Визитная карточка</option>
  <option value="3">Статический баннер</option>
</select><br>
<select name="v2" class="drop-down">
  <option value="">--Выберите раздел--</option>
  <option value="1">Товары</option>
  <option value="2">Услуги</option>
  <option value="3">Компании</option>
  <option value="4">Биржа</option>
  <option value="5">Публикации</option>
</select><br>
<select name="v3" class="drop-down">
  <option value="">--Конечная категория--</option>
  <option value="1">Весь раздел</option>
  <option value="2">Главная страница</option>
  <option value="3">Категория товара</option>
  <option value="4">Отдельный товар</option>
</select></code>```

答:
Hope this is what you want:

will create dependencies between each select and the next one only with CSS.
This might not be a perfect solution but for some situations it might definitely be suffice.

Each select must have a required attribute for this to work and also there should be no HTML elements between them.

You can extend this approach to pretty much anything you want, including those radio buttons you've mentioned. just add them to the HTML and change the CSS a bit. it was unclear what exactly you wanted, but this gives you 90% of the way to achieve it probably.

select { margin:1em; display:block; }

/* block all but the first "select" elements from being used (like "disabled" */
select:not(:first-child){ opacity:.3; pointer-events:none; }

/* show the next "select" if any select has a value */
select:valid + select{ opacity:1; pointer-events:auto; }
select:invalid{  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="v1" required>
  <option value="">--Выберите Вид рекламы--</option>
  <option value="1">Объявление [Товар / Услуга]</option>
  <option value="2">Визитная карточка</option>
  <option value="3">Статический баннер</option>
</select>
<select name="v2" required>
  <option value="">--Выберите раздел--</option>
  <option value="1">Товары</option>
  <option value="2">Услуги</option>
  <option value="3">Компании</option>
  <option value="4">Биржа</option>
  <option value="5">Публикации</option>
</select>
<select name="v3" required>
  <option value="">--Конечная категория--</option>
  <option value="1">Весь раздел</option>
  <option value="2">Главная страница</option>
  <option value="3">Категория товара</option>
  <option value="4">Отдельный товар</option>
</select></code>```

Title: How to make a step-by-step choice?

Body:
There is a task. It is necessary to give the user a choice in the first step between 3 (input radio). After he chose one of the items he needed, a second column appears with the new column (input radio). And also after the choice in the second step appears the third step with the final choice (input radio).

It is important that the second step and the third for each selected item are new.

Help solve this problem.

I found a similar task, but it's a little unsuitable for my purposes.
Updating button content based on selection
for example

$(document).ready(function(){
  var selects = $('.drop-down');
  selects.not(':eq(0)').prop('disabled', true);
  selects.on('change', function() {
    var select = $(this),
        currentIndex = selects.index(select),
        nextIndex = currentIndex + 1;

    if (currentIndex != selects.length - 1) {
      selects.slice(nextIndex)
             .val('')
             .prop('disabled', true);

      selects.eq(nextIndex).prop('disabled', select.val() === '');
    }

  })

});

<select name="v1" class="drop-down">
  <option value="">--Выберите Вид рекламы--</option>
  <option value="1">Объявление [Товар / Услуга]</option>
  <option value="2">Визитная карточка</option>
  <option value="3">Статический баннер</option>
</select>

<select name="v2" class="drop-down">
  <option value="">--Выберите раздел--</option>
  <option value="1">Товары</option>
  <option value="2">Услуги</option>
  <option value="3">Компании</option>
  <option value="4">Биржа</option>
  <option value="5">Публикации</option>
</select>

<select name="v3" class="drop-down">
  <option value="">--Конечная категория--</option>
  <option value="1">Весь раздел</option>
  <option value="2">Главная страница</option>
  <option value="3">Категория товара</option>
  <option value="4">Отдельный товар</option>
</select>

Body:
Hope this is what you want:

will create dependencies between each select and the next one only with CSS.
This might not be a perfect solution but for some situations it might definitely be suffice.

Each select must have a required attribute for this to work and also there should be no HTML elements between them.

You can extend this approach to pretty much anything you want, including those radio buttons you've mentioned. just add them to the HTML and change the CSS a bit. it was unclear what exactly you wanted, but this gives you 90% of the way to achieve it probably.

select { margin:1em; display:block; }

/* block all but the first "select" elements from being used (like "disabled" */
select:not(:first-child){ opacity:.3; pointer-events:none; }

/* show the next "select" if any select has a value */
select:valid + select{ opacity:1; pointer-events:auto; }
select:invalid{  }

<select name="v1" required>
  <option value="">--Выберите Вид рекламы--</option>
  <option value="1">Объявление [Товар / Услуга]</option>
  <option value="2">Визитная карточка</option>
  <option value="3">Статический баннер</option>
</select>
<select name="v2" required>
  <option value="">--Выберите раздел--</option>
  <option value="1">Товары</option>
  <option value="2">Услуги</option>
  <option value="3">Компании</option>
  <option value="4">Биржа</option>
  <option value="5">Публикации</option>
</select>
<select name="v3" required>
  <option value="">--Конечная категория--</option>
  <option value="1">Весь раздел</option>
  <option value="2">Главная страница</option>
  <option value="3">Категория товара</option>
  <option value="4">Отдельный товар</option>
</select>


问:
Getting greek character in plot axis
I am making barplots for different metal concentration in various materials, and need the axis to say μg/g. I've searched for how to implement greek characters into different plots, but I don't seem able to actually do so. It looks like I should be able to use (expression(paste)) - can anyone help me?

This is an extract of my current script:

```<code>BP.Ag <- ggplot(data=dat, aes(x=Material, y=Ag, fill=Sample.Material)) +
  geom_bar(stat="identity", position="dodge") + theme_bw() +
  scale_fill_brewer(palette = "Set1") + ylab("Silver (μg/g)") + guides(fill=FALSE) + theme(axis.text.x = element_text(angle = 45, hjust = 1))
</code>```

Thanks!

答:
Have you tried the UTF-8 for µ ("\u00B5"):

```<code>>cat("\u00B5")
µ
</code>```

In your plot you could use:

```<code>ylab("Silver (\u00B5g/g)")
</code>```

Title: Getting greek character in plot axis

Body:
I am making barplots for different metal concentration in various materials, and need the axis to say μg/g. I've searched for how to implement greek characters into different plots, but I don't seem able to actually do so. It looks like I should be able to use (expression(paste)) - can anyone help me?

This is an extract of my current script:

BP.Ag <- ggplot(data=dat, aes(x=Material, y=Ag, fill=Sample.Material)) +
  geom_bar(stat="identity", position="dodge") + theme_bw() +
  scale_fill_brewer(palette = "Set1") + ylab("Silver (μg/g)") + guides(fill=FALSE) + theme(axis.text.x = element_text(angle = 45, hjust = 1))

Thanks!

Body:
Have you tried the UTF-8 for µ ("\u00B5"):

>cat("\u00B5")
µ

In your plot you could use:

ylab("Silver (\u00B5g/g)")


问:
Best practice mongodump backing up 250GB database
I'm tring another aproach. Full dump and the daily dump of new data using:

oid=$(mongo --quiet --eval 'ObjectId.fromDate(ISODate("2017-03-29 00:10:20"))')

mongodump -q "{_id:{$gt:$oid}}" -d dbname --collection name_data

But I'm getting:

Failed: error parsing query as json: invalid character ':' looking for beginning of object key string

答:
The first $ needs to be escaped:

mongodump -q "{_id:{\$gt:$oid}}" -d dbname --collection name_data


问:
Passing cv::Mat by reference or return it?
I was wondering which version of this function is more efficient:

```<code>void myimread (cv::Mat &mat, const std::string &imgname){
  mat = imread(imgname);
}
</code>```

or

```<code>cv::Mat myimread (const std::string &imgname){
  return imread(imgname);
}
</code>```

From my knowledge, cv::Mat is kinda of a smart pointer and combined with the move semantic that cv::Mat should implement (again, if I'm not wrong) the second version should be not more expensive than the first one.

答:
If copy elision gets applied, the 2nd case would be more efficient.

For the 1st case, the usage would be:

```<code>cv::Mat mat;            // default constructed
myimread(mat, imgname); // copy assigned by imread(imgname) inside myimread
</code>```

For the 2nd case:

```<code>cv::Mat mat = myimread(imgname); // mat is constructed by imread(imgname) directly; copy/move operation is omitted
</code>```

From C++17 when the operand of a return statement is a prvalue and the return type of the function is the same as the type of that prvalue, copy elision is guaranteed.

Body:
I was wondering which version of this function is more efficient:

void myimread (cv::Mat &mat, const std::string &imgname){
  mat = imread(imgname);
}

or

cv::Mat myimread (const std::string &imgname){
  return imread(imgname);
}

From my knowledge, cv::Mat is kinda of a smart pointer and combined with the move semantic that cv::Mat should implement (again, if I'm not wrong) the second version should be not more expensive than the first one.

Body:
If copy elision gets applied, the 2nd case would be more efficient.

For the 1st case, the usage would be:

cv::Mat mat;            // default constructed
myimread(mat, imgname); // copy assigned by imread(imgname) inside myimread

For the 2nd case:

cv::Mat mat = myimread(imgname); // mat is constructed by imread(imgname) directly; copy/move operation is omitted

From C++17 when the operand of a return statement is a prvalue and the return type of the function is the same as the type of that prvalue, copy elision is guaranteed.


问:
I have 2 text areas. On consecutive clicks of add description button the text of both the textareas will get merged into the first one
I am able to achieve this but I also need a time/date stamp along with each new entry.
Here's a fiddle link:

https://jsfiddle.net/Anupriya24/pstynje9/

Script:

```<code>    var count=0;
$('.addDescBtn').on('click', function() {
    count++;
    if(count<=1){
        if($("#description").val()==""){
            alert("Please add to existing description field.");
            $("#description").val("");
            $("#description").removeAttr("readonly");
            count=0;
        }
        else {
            $("#descriptionHolder").append('<div class="form-group col-md-12 pad0 mar-t20" id="newDesc"><label class="col-md-3 pad0 visible-none" for="description1">Description:</label><textarea rows="5" cols="50" class="form-control col-md-9" id="description1" placeholder="Description"></textarea> </div>');
        }
    }
    if($('#descriptionHolder').find('#newDesc').length){
        var text=$("#description").val().trim();
        var text1=$("#description1").val();
        var combinedText=text+"\n"+text1+"\n";
        $("#description").val(combinedText);
        $("#description").attr('readonly', 'readonly');
        $("#description1").val("");
    }

});
</code>```

Html

```<code>                        <div class="form-group col-md-12 pad0" id="descriptionHolder">
                            <label class="col-md-3 pad0" for="description">Description:</label>
                            <textarea rows="5" cols="50" class="form-control col-md-9" id="description" placeholder="Description" ></textarea>
                        </div>
                        <div class="form-group col-md-12 pad0">
                            <input type="button" class="addDescBtn orangeBtn btn fright" value="Add Description" id="addDescription"/>
                        </div>
</code>```

答:
What about this? https://jsfiddle.net/pstynje9/16/</p>

```<code>var count=0, descs = [];
$('.addDescBtn').on('click', function() {
    if($('#descriptionHolder').find('#newDesc').length){
        descs.push(new Date().toString() + ':' + $("#description1").val());
    } else {
        descs.push(new Date().toString() + ':' + $("#description").val());
    }

    $("#description").val(descs.join('\n'));
    count++;
    if(count<=1){
        if($("#description").val()==""){
            alert("Please add to existing description field.");
            $("#description").val("");
            $("#description").removeAttr("readonly");
            count=0;
        }
        else {
            $("#descriptionHolder").append('<div class="form-group col-md-12 pad0 mar-t20" id="newDesc"><label class="col-md-3 pad0 visible-none" for="description1">Description:</label><textarea rows="5" cols="50" class="form-control col-md-9" id="description1" placeholder="Description"></textarea> </div>');
        }
    }

    $("#description").attr('readonly', 'readonly');
    $("#description1").val("");

});
</code>```

Body:
I am able to achieve this but I also need a time/date stamp along with each new entry.
Here's a fiddle link:

https://jsfiddle.net/Anupriya24/pstynje9/

Script:

    var count=0;
$('.addDescBtn').on('click', function() {
    count++;
    if(count<=1){
        if($("#description").val()==""){
            alert("Please add to existing description field.");
            $("#description").val("");
            $("#description").removeAttr("readonly");
            count=0;
        }
        else {
            $("#descriptionHolder").append('
Description:<textarea rows="5" cols="50" class="form-control col-md-9" id="description1" placeholder="Description"></textarea>
');
        }
    }
    if($('#descriptionHolder').find('#newDesc').length){
        var text=$("#description").val().trim();
        var text1=$("#description1").val();
        var combinedText=text+"\n"+text1+"\n";
        $("#description").val(combinedText);
        $("#description").attr('readonly', 'readonly');
        $("#description1").val("");
    }

});

Html

                            Description:
                            <textarea rows="5" cols="50" class="form-control col-md-9" id="description" placeholder="Description" ></textarea>

                            <input type="button" class="addDescBtn orangeBtn btn fright" value="Add Description" id="addDescription"/>

Body:
What about this? https://jsfiddle.net/pstynje9/16/

var count=0, descs = [];
$('.addDescBtn').on('click', function() {
    if($('#descriptionHolder').find('#newDesc').length){
        descs.push(new Date().toString() + ':' + $("#description1").val());
    } else {
        descs.push(new Date().toString() + ':' + $("#description").val());
    }

    $("#description").val(descs.join('\n'));
    count++;
    if(count<=1){
        if($("#description").val()==""){
            alert("Please add to existing description field.");
            $("#description").val("");
            $("#description").removeAttr("readonly");
            count=0;
        }
        else {
            $("#descriptionHolder").append('<div class="form-group col-md-12 pad0 mar-t20" id="newDesc"><label class="col-md-3 pad0 visible-none" for="description1">Description:</label><textarea rows="5" cols="50" class="form-control col-md-9" id="description1" placeholder="Description"></textarea> </div>');
        }
    }

    $("#description").attr('readonly', 'readonly');
    $("#description1").val("");

});


问:
What is the easiest way to keep track of a group of checkable buttons in QT?
I have six checkable push buttons in QT, and I want it so that only one of the buttons are checked at one time (like radio buttons). I could probably do it with lots of signals and slots, but is there a easier way to do this?

I'm looking for something similar to how the QGroupBox and QRadioButtons work together.

Thanks

答:
I think you're looking for http://doc.trolltech.com/4.7/qbuttongroup.html .

Make sure all of your buttons are checkable, make the group exclusive, use addButton() for each button and run with it.


问:
panda plot multiple lines base on a certain column
I have a dataframe like this

```<code>timestamp|type|value_1|value_2

t1|A|v1|v2

t2|B|v3|v4

t3|C|v5|v6

t4|A|v7|v8
</code>```

I would like to plot a graph with 6 lines each type and value
for example

```<code>type A - value_1
type A - value_2

type B - value_1
type B - value_2

type C - value_1
type C - value_2
</code>```

thanks,

it is like doing this

```<code>A = df[df["type"] == A]

A.plot(x="time", y=["value_1", "value_2"])
</code>```

do this for three types
and combine those 6 lines on the same graph

答:
I think you can reshape DataFrame to columns and then plot:

```<code>df['g'] = df.groupby('type').cumcount()
df = df.set_index(['timestamp','g', 'type']).unstack().reset_index(level=1, drop=True)
df.columns = df.columns.map('_'.join)

df.plot()
</code>```

Body:
I have a dataframe like this

timestamp|type|value_1|value_2

t1|A|v1|v2

t2|B|v3|v4

t3|C|v5|v6

t4|A|v7|v8

I would like to plot a graph with 6 lines each type and value
for example

type A - value_1
type A - value_2

type B - value_1
type B - value_2

type C - value_1
type C - value_2

thanks,

it is like doing this

A = df[df["type"] == A]

A.plot(x="time", y=["value_1", "value_2"])

do this for three types
and combine those 6 lines on the same graph

Body:
I think you can reshape DataFrame to columns and then plot:

df['g'] = df.groupby('type').cumcount()
df = df.set_index(['timestamp','g', 'type']).unstack().reset_index(level=1, drop=True)
df.columns = df.columns.map('_'.join)

df.plot()


问:
django/python count number of row inserted in specific month
Purchase_History model

```<code>class Purchase_History(models.Model):
   barcode = models.BigIntegerField()
   email = models.CharField(max_length=100)
   bill_no = models.IntegerField()
   longitude = models.CharField(max_length=500)
   latitude = models.CharField(max_length=500)
   timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
</code>```

i want to count number of rows from specific month
i tried something like

```<code>m=Purchase_History.objects.filter(timestamp="month").count()
</code>```

and

```<code>m=Purchase_History.objects.filter(timestamp=["2017-01-01", "2017-01-31"]).count()
</code>```

its good practice to use timestamp field, please help me, if you have any solution to it.

thanks in advance

答:
You can use the __range filter:

```<code>Purchase_History.objects.filter(timestamp__range=["2017-01-01", "2017-01-31"]).count()
</code>```

Body:
Purchase_History model

class Purchase_History(models.Model):
   barcode = models.BigIntegerField()
   email = models.CharField(max_length=100)
   bill_no = models.IntegerField()
   longitude = models.CharField(max_length=500)
   latitude = models.CharField(max_length=500)
   timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)

i want to count number of rows from specific month
i tried something like

m=Purchase_History.objects.filter(timestamp="month").count()

and

m=Purchase_History.objects.filter(timestamp=["2017-01-01", "2017-01-31"]).count()

its good practice to use timestamp field, please help me, if you have any solution to it.

thanks in advance

Body:
You can use the __range filter:

Purchase_History.objects.filter(timestamp__range=["2017-01-01", "2017-01-31"]).count()


问:
SourceTree installation is failed
I downloaded SourceTreeSetup.exe file from the SourceTree site.
 - version: SourceTreeSetup-1.10.23.1.exe

I installed it in my Windows 7 (32bit), and can find the Icon in my desktop.

When I run the SourceTree, a error popup is shown.

Downloading from https://downloads.atlassian.com/software/sourcetree/windows/PortableGcmSt-1.8.1.6.7z ...

with Below error popup.

System.Net.WebException: The underlying connection was closed. Send has encountered an unexpected error.

System.IO.IOException: The transport connection could not read data from the current connection that was forcibly disconnected by the remote host.

System.Net.Sockets.SocketException: The current connection was forcibly disconnected by the remote host

I suspect our company's firewall, but I don't know exactly.
I tried to googling with these error, but I cannot find any clue.

Anyone to help, please?

答:
https://jira.atlassian.com/browse/SRCTREEWIN-6886

the solution for me was to download this version:
https://downloads.atlassian.com/software/sourcetree/windows/ga/SourceTreeSetup-1.10.24.1.exe

Title: SourceTree installation is failed


问:
Parse variable number of differently typed integers from a line in C
I have a file with lines separated by '\n' where each line looks like either

```<code>10010 0 19 7 18
</code>```

or

```<code>10014 -1 -1 -1 11 10db8 1
</code>```

That is, every line will always either have 5 or 7 space separated values and the type of every value is also known beforehand. I want to read the file line by line and parse each line to extract inttypes (SCNi32, SCNu32, SCNx32..) and store in corresponding inttype variables. What is the easiest way to do this? I am new to C.

答:
Read the line using fgets() parse the line by breaking the line into tokens.

Use strtok() to break the line into tokens.

Convert the token into integer using atoi() or any other string to integer.

Body:
I have a file with lines separated by '\n' where each line looks like either

10010 0 19 7 18

or

10014 -1 -1 -1 11 10db8 1

That is, every line will always either have 5 or 7 space separated values and the type of every value is also known beforehand. I want to read the file line by line and parse each line to extract inttypes (SCNi32, SCNu32, SCNx32..) and store in corresponding inttype variables. What is the easiest way to do this? I am new to C.


问:
How to put sql result into single cell
I'm coding sql in a simplified platform and can't access the platform code so I need some workaround every now and then (not always the best practise code).

I would need to store result of select clause to single cell for further use.

For example:
Table products has productID, productName, packages.

Table variants has productID, packageID.

Example data of variants:

```<code>productID - packageID
1001 - K1001
1001 - K1002
1001 - K1003
</code>```

I would need to save the result to cell packages in form of (K1001, K1002, K1003) or similar.

Is this possible to do just using sql?

I'm using ms sql server xpress, platform/RDBMS is custom coded and not widely known.

答:
You can use STUFF with FOR XML PATH.

Query

```<code>select productID, stuff((
    select ', ' + packageID
    from your_table_name
    where (productID = t.productID)
    for xml path(''), type).value('(./text())[1]','varchar(max)')
    , 1, 2, '') as single_value
from your_table_name  t
group by productID;
</code>```

Find demo here

Title: How to put sql result into single cell

Body:
I'm coding sql in a simplified platform and can't access the platform code so I need some workaround every now and then (not always the best practise code).

I would need to store result of select clause to single cell for further use.

For example:
Table products has productID, productName, packages.

Table variants has productID, packageID.

Example data of variants:

productID - packageID
1001 - K1001
1001 - K1002
1001 - K1003

I would need to save the result to cell packages in form of (K1001, K1002, K1003) or similar.

Is this possible to do just using sql?

I'm using ms sql server xpress, platform/RDBMS is custom coded and not widely known.

Body:
You can use STUFF with FOR XML PATH.

Query

select productID, stuff((
    select ', ' + packageID
    from your_table_name
    where (productID = t.productID)
    for xml path(''), type).value('(./text())[1]','varchar(max)')
    , 1, 2, '') as single_value
from your_table_name  t
group by productID;

Find demo here


问:
Low memory image resizing
I am looking for some advice on how to construct a very low memory image resizing program that will be run as a child process of my nodejs application in linux.

The solution I am looking for is a linux executable that will take a base64 string image (uploaded from a client) using stdin, resizing the photo to a specified size and then pumping the resulting image data back through stdout.

I've looked into image magick and it might be what I end up using, but I figured I would ask and see if anyone had a suggestion.

Suggestions of libraries or examples of pre compiled executables in C/C++ would be greatly appreciated. Also a helpful answer would include general strategies for low memory image resizing.

Thank you

答: GraphicsMagick is generally a better version of ImageMagick, I'd take a look at that. If you really need something fast, you probably want to drop to something like libjpeg - while you say you want something that's non-blocking IO, the operation you want to do is relatively CPU-bound (i.e decoding the image, then trying to resize it).</p>

Title: Low memory image resizing


问:
Ant Design error: "Unknown plugin 'import' specified in '[..]/.babelrc'"
I've put the following in my .babelrc:

```<code>{
  "plugins": [
    ["import", { libraryName: "antd", style: "css" }] // `style: true` for less
  ]
}
</code>```

This is the error:
Unknown plugin "import" specified in "[..]/.babelrc"

Additionally it's not clear to me from the docs whether I have to import the CSS for:

every single component (e.g. DatePicker) or

if antd/dist/antd.css includes just everything.

In case of 1. it would be nice to have the CSS paths as part of the examples.

In case of 2. where do I put that include, in my App.js?

These are the babel packages I have installed:

```<code>"babel-core": "^6.24.0",
"babel-eslint": "^7.2.1",
"babel-loader": "^6.4.1",
"babel-plugin-transform-class-properties": "^6.23.0",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.24.0",
"babel-preset-react": "^6.23.0",
"babel-preset-stage-0": "^6.22.0",
</code>```

And this is my webpack.config.js:

```<code>const webpack = require('webpack');
const path = require('path');
const nodeModulesPath = path.resolve(__dirname, 'node_modules');

const config = {

  // Render source-map file for final build
  devtool: 'source-map',

  // Entrypoint of the app, first JS to load
  entry: [
    path.join(__dirname, './app/index.js'),
  ],

  output: {
    path: path.resolve(__dirname, "build"), // absolute Path of output file
    filename: 'bundle.js', // Name of output file
    publicPath: '/static'
  },

  module: {
    rules: [
      {
        test: /\.js$/, // All .js files
        exclude: [nodeModulesPath],
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: [
                "es2015",
                "stage-0",
                "react",
              ],
              plugins: [
                "transform-class-properties",
                "transform-decorators-legacy"
              ]
            }
          }
        ]
      }
    ]
  },

  plugins: [
    // Define production build to allow React to strip out unnecessary checks
    new webpack.DefinePlugin({
      'process.env':{
        'NODE_ENV': JSON.stringify('development')
      }
    }),
    // Suppress all the "Condition always true" warnings
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      minimize: true,
    }),
  ],

};

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

答: Install babel-plugin-import You can see docs in https://github.com/ant-design/babel-plugin-import

Body:
I've put the following in my .babelrc:

{
  "plugins": [
    ["import", { libraryName: "antd", style: "css" }] // `style: true` for less
  ]
}

This is the error:
Unknown plugin "import" specified in "[..]/.babelrc"

Additionally it's not clear to me from the docs whether I have to import the CSS for:

every single component (e.g. DatePicker) or

if antd/dist/antd.css includes just everything.

In case of 1. it would be nice to have the CSS paths as part of the examples.

In case of 2. where do I put that include, in my App.js?

These are the babel packages I have installed:

"babel-core": "^6.24.0",
"babel-eslint": "^7.2.1",
"babel-loader": "^6.4.1",
"babel-plugin-transform-class-properties": "^6.23.0",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.24.0",
"babel-preset-react": "^6.23.0",
"babel-preset-stage-0": "^6.22.0",

And this is my webpack.config.js:

const webpack = require('webpack');
const path = require('path');
const nodeModulesPath = path.resolve(__dirname, 'node_modules');

const config = {

  // Render source-map file for final build
  devtool: 'source-map',

  // Entrypoint of the app, first JS to load
  entry: [
    path.join(__dirname, './app/index.js'),
  ],

  output: {
    path: path.resolve(__dirname, "build"), // absolute Path of output file
    filename: 'bundle.js', // Name of output file
    publicPath: '/static'
  },

  module: {
    rules: [
      {
        test: /\.js$/, // All .js files
        exclude: [nodeModulesPath],
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: [
                "es2015",
                "stage-0",
                "react",
              ],
              plugins: [
                "transform-class-properties",
                "transform-decorators-legacy"
              ]
            }
          }
        ]
      }
    ]
  },

  plugins: [
    // Define production build to allow React to strip out unnecessary checks
    new webpack.DefinePlugin({
      'process.env':{
        'NODE_ENV': JSON.stringify('development')
      }
    }),
    // Suppress all the "Condition always true" warnings
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      minimize: true,
    }),
  ],

};

module.exports = config;


问:
Apply a function to every specified column in a data.table and update by reference
I have a data.table with which I'd like to perform the same operation on certain columns.  The names of these columns are given in a character vector. In this particular example, I'd like to multiply all of these columns by -1.

Some toy data and a vector specifying relevant columns:

```<code>library(data.table)
dt <- data.table(a = 1:3, b = 1:3, d = 1:3)
cols <- c("a", "b")
</code>```

Right now I'm doing it this way, looping over the character vector:

```<code>for (col in 1:length(cols)) {
   dt[ , eval(parse(text = paste0(cols[col], ":=-1*", cols[col])))]
}
</code>```

Is there a way to do this directly without the for loop?

答:
I would like to add an answer, when you would like to change the name of the columns as well. This comes in quite handy if you want to calculate the logarithm of multiple columns, which is often the case in empirical work.</p>

```<code>cols <- c("a", "b")
out_cols = paste("log", cols, sep = ".")
dt[, c(out_cols) := lapply(.SD, function(x){log(x = x, base = exp(1))}), .SDcols = cols]
</code>```

Body:
I have a data.table with which I'd like to perform the same operation on certain columns.  The names of these columns are given in a character vector. In this particular example, I'd like to multiply all of these columns by -1.

Some toy data and a vector specifying relevant columns:

library(data.table)
dt <- data.table(a = 1:3, b = 1:3, d = 1:3)
cols <- c("a", "b")

Right now I'm doing it this way, looping over the character vector:

for (col in 1:length(cols)) {
   dt[ , eval(parse(text = paste0(cols[col], ":=-1*", cols[col])))]
}

Is there a way to do this directly without the for loop?

Body:
I would like to add an answer, when you would like to change the name of the columns as well. This comes in quite handy if you want to calculate the logarithm of multiple columns, which is often the case in empirical work.

cols <- c("a", "b")
out_cols = paste("log", cols, sep = ".")
dt[, c(out_cols) := lapply(.SD, function(x){log(x = x, base = exp(1))}), .SDcols = cols]


问:
How to perform some action when device is connected to WiFi and app is terminated?
How should I communicate with server or do some action when my device is connected to the WiFi and my app is terminated (not runnning on background/foreground)?</p>

答:
According to the documentation for UIApplicationDelegate's applicationWillTerminate API (which has a companion UIApplicationWillTerminate notification you can observer), you have approximately five seconds to perform any tasks and return before the app dies.

If this were my problem, I'd be wondering if five seconds is that long enough to reliably talk to the server or do any useful action aside from cleanup.


问:
Resolving Mixed Content warning from external insecure server
I have a https site and need to show content from other sites that may or may not be themselves https.  Predictably enough, I'm getting warning messages like this in the console...

"Mixed Content: The page at 'https://www.example.com/' (my server) was loaded over HTTPS, but requested an insecure image 'http://www.aninsecuredomain.com/image.jpg'. (not my server) This content should also be served over HTTPS."

(not to the mention the fact that I no longer see the little padlock displayed properly in most browsers who now consider my site's network insecure).

I've read through a bunch of posts on SO on this topic, but I can't seem to find a definitive answer on whether there's anything I can do when I don't own the external servers (so can't guarantee they'll have a https version).  Appreciate any thoughts on whether this is possible, and if so how I could go about achieving it!

答:
You should use the // prefix.  (instead of http[s]://)

On an https page, the secure version wil be loaded.

On on a plain http page, the plain http version will be loaded.

Edit your theme replacing every occurence of http://fonts.googleapis.com/... with //fonts.googleapis.com/...


问:
Swift AVFoundation in playground not outputting sound
My Morse code translator will not output the sound as it should. I have tested the speakers and my methods without this function and it works flawlessly, but it is not in context with the rest of the program. The compiler gives me no errors and the playground does not crash, it just doesn't play sound. Volume and ringer is at full.

```<code>func speakTheCode(message: String) {
    var speaker = AVAudioPlayer()
    let longBeep = #fileLiteral(resourceName: "beep_long.mp3")
    let shortBeep = #fileLiteral(resourceName: "beep_short.mp3")
    let dash = "-"
    let dot = "."
    for character in message.characters {
        if character == dash[dash.startIndex] {
                speaker = try! AVAudioPlayer(contentsOf: longBeep)
                speaker.prepareToPlay()
            print("-")
        }
        else if character == dot[dot.startIndex] {
                speaker = try! AVAudioPlayer(contentsOf: shortBeep)
                speaker.prepareToPlay()
                print(".")
        }
        speaker.play()
    }
}
</code>```

I've been messing around with the code for hours now and nothing is working. What (if anything) am I doing wrong?

答:
There seems to some playgrounds issues with playing audio. See this thread:

Playing a sound in a Swift Playground

However, I was able to make some changes to your code and get it to work. Here's my code:

```<code>class Morse:NSObject, AVAudioPlayerDelegate {
    private var message = ""
    private var dotSound:AVAudioPlayer!
    private var dashSound:AVAudioPlayer!
    private let dash = Character("-")
    private let dot = Character(".")
    private var index:String.Index!

    init(message:String) {
        super.init()
        do {
            if let url = Bundle.main.url(forResource:"beep_short", withExtension:"mp3") {
                self.dotSound = try AVAudioPlayer(contentsOf:url)
                self.dotSound.delegate = self
                self.dotSound.prepareToPlay()
            }
        } catch {
            NSLog("Error loading dot audio!")
        }
        do {
            if let url = Bundle.main.url(forResource:"beep_long", withExtension:"mp3") {
                self.dashSound = try AVAudioPlayer(contentsOf:url)
                self.dashSound.delegate = self
                self.dashSound.prepareToPlay()
            }
        } catch {
            NSLog("Error loading dash audio!")
        }
        self.message = message
        self.index = message.startIndex
    }

    func playCharacter() {
        let character = message.characters[index]
        NSLog("Character: \(character)")
        if character == dash {
            dashSound.play()
        } else if character == dot {
            dotSound.play()
        }
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        NSLog("Finished playing")
        if index != message.endIndex {
            self.index = message.index(after:index)
            playCharacter()
        }
    }
}

let m = Morse(message:"...---")
m.playCharacter()

PlaygroundPage.current.needsIndefiniteExecution = true
</code>```

I had to enable indefinite execution to get the code to execute at all. Also, I had some issues with the second audio file loading but I didn't investigate further to see if it was an issue with my test file or something else since it mostly worked.

Body:
My Morse code translator will not output the sound as it should. I have tested the speakers and my methods without this function and it works flawlessly, but it is not in context with the rest of the program. The compiler gives me no errors and the playground does not crash, it just doesn't play sound. Volume and ringer is at full.

func speakTheCode(message: String) {
    var speaker = AVAudioPlayer()
    let longBeep = #fileLiteral(resourceName: "beep_long.mp3")
    let shortBeep = #fileLiteral(resourceName: "beep_short.mp3")
    let dash = "-"
    let dot = "."
    for character in message.characters {
        if character == dash[dash.startIndex] {
                speaker = try! AVAudioPlayer(contentsOf: longBeep)
                speaker.prepareToPlay()
            print("-")
        }
        else if character == dot[dot.startIndex] {
                speaker = try! AVAudioPlayer(contentsOf: shortBeep)
                speaker.prepareToPlay()
                print(".")
        }
        speaker.play()
    }
}

I've been messing around with the code for hours now and nothing is working. What (if anything) am I doing wrong?

Body:
There seems to some playgrounds issues with playing audio. See this thread:

Playing a sound in a Swift Playground

However, I was able to make some changes to your code and get it to work. Here's my code:

class Morse:NSObject, AVAudioPlayerDelegate {
    private var message = ""
    private var dotSound:AVAudioPlayer!
    private var dashSound:AVAudioPlayer!
    private let dash = Character("-")
    private let dot = Character(".")
    private var index:String.Index!

    init(message:String) {
        super.init()
        do {
            if let url = Bundle.main.url(forResource:"beep_short", withExtension:"mp3") {
                self.dotSound = try AVAudioPlayer(contentsOf:url)
                self.dotSound.delegate = self
                self.dotSound.prepareToPlay()
            }
        } catch {
            NSLog("Error loading dot audio!")
        }
        do {
            if let url = Bundle.main.url(forResource:"beep_long", withExtension:"mp3") {
                self.dashSound = try AVAudioPlayer(contentsOf:url)
                self.dashSound.delegate = self
                self.dashSound.prepareToPlay()
            }
        } catch {
            NSLog("Error loading dash audio!")
        }
        self.message = message
        self.index = message.startIndex
    }

    func playCharacter() {
        let character = message.characters[index]
        NSLog("Character: \(character)")
        if character == dash {
            dashSound.play()
        } else if character == dot {
            dotSound.play()
        }
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        NSLog("Finished playing")
        if index != message.endIndex {
            self.index = message.index(after:index)
            playCharacter()
        }
    }
}

let m = Morse(message:"...---")
m.playCharacter()

PlaygroundPage.current.needsIndefiniteExecution = true

I had to enable indefinite execution to get the code to execute at all. Also, I had some issues with the second audio file loading but I didn't investigate further to see if it was an issue with my test file or something else since it mostly worked.


问:
Speeding up odeint calculation
I am running a fairly large system of ODEs using scipy's odeint. In order to keep the system coherent, easy to read and shorter I have divided most of it into classes to call upon each other. From the readability point of view it seems to work fine, however due to repeated calls to python objects it significantly slows down the actual ODE solver. I looked around into ways of optimizing the code to maintain some level of readability while also making it more efficient at calculations (either using Numba or using Sympy before converting it to numpy-aware lambda functions), however I have not been very successful so far. I was wondering what strategies could be helpful in this case. I have provided a simple version of the code below. Thank you in advance.  </p>

```<code>class NaL():
    g = 0
    def I(self, v, E): return self.g * (v - E) #Leak current

class Neuron():
    C_m = 1.0 #membrane capacitance
    V = 0  # Voltage
    m, h = 0, 0  #activating variables
    def I_Na(self): #Sodium Currents
        return self.NaT.I(self.V, self.m, self.h)+ self.NaL.I(self.V)
    def __init__(self):
        self.NaT = NaT()
        self.NaL = NaL()
        self.NaT.g = 3000
        self.NaL.g = 20

I1 = Neuron()

def Run(X,t):
    I1.V, I1.m, I1.h = X
    dydt = [(0 - I1.I_Na()) / I1.C_m, #dV/dt for neuron
            I1.NaT.dmdt(I1.V, I1.m), #dm/dt for sodium channel
            I1.NaT.dhdt(I1.V, I1.h) #dh/dt for sodium channel
           ]
    return dydt
X = odeint(Run, [-70, 0.0050, 0.9961], t)
</code>```

答:
The bottleneck of your integration is almost certainly evaluation the derivative Run, as this has to be called multiple times for every step of integration. Right now, you have a considerable Python overhead in there due to all the class members and function calls.

One solution for this is using the module JiTCODE by yours truly, where instead of defining a function to be used by the integrator, you define the differential equations symbolically (with SymPy). They are then translated to C code, which is compiled to a Python function, which in turn is used for integrating. This way, your classes and class functions are only called a few times before the actual integration and the integration is as efficient as it would be if you defined your derivative without classes and similar. (Also, you may get a considerable speed boost through compilation, in particular if you have many neurons.)

As it stands, you translating your example to JiTCODE is straightforward:

```<code>from jitcode import jitcode, provide_basic_symbols

t, y = provide_basic_symbols()

class NaL():
    […]

class Neuron():
    […]

I1 = Neuron()

I1.V, I1.m, I1.h = y(0), y(1), y(2)

Run = [
    (0 - I1.I_Na()) / I1.C_m,
    I1.NaT.dmdt(I1.V, I1.m),
    I1.NaT.dhdt(I1.V, I1.h)
]

t = range(100)

ODE = jitcode(Run)
ODE.set_initial_value([-70,0.0050,0.9961], t[0])
X = np.vstack(ODE.integrate for time in t[1:])
</code>```

This code does not work right now for the same reasons that your example code does not work. Note that all the arithmetics in your class that involves dynamical variables becomes symbolic. With additions and multiplications, this works out of the box, but if you have something like math.sin or sympy.sin, you have to replace it by sympy.sin.

Title: Speeding up odeint calculation

Body:
I am running a fairly large system of ODEs using scipy's odeint. In order to keep the system coherent, easy to read and shorter I have divided most of it into classes to call upon each other. From the readability point of view it seems to work fine, however due to repeated calls to python objects it significantly slows down the actual ODE solver. I looked around into ways of optimizing the code to maintain some level of readability while also making it more efficient at calculations (either using Numba or using Sympy before converting it to numpy-aware lambda functions), however I have not been very successful so far. I was wondering what strategies could be helpful in this case. I have provided a simple version of the code below. Thank you in advance.

class NaL():
    g = 0
    def I(self, v, E): return self.g * (v - E) #Leak current

class Neuron():
    C_m = 1.0 #membrane capacitance
    V = 0  # Voltage
    m, h = 0, 0  #activating variables
    def I_Na(self): #Sodium Currents
        return self.NaT.I(self.V, self.m, self.h)+ self.NaL.I(self.V)
    def __init__(self):
        self.NaT = NaT()
        self.NaL = NaL()
        self.NaT.g = 3000
        self.NaL.g = 20

I1 = Neuron()

def Run(X,t):
    I1.V, I1.m, I1.h = X
    dydt = [(0 - I1.I_Na()) / I1.C_m, #dV/dt for neuron
            I1.NaT.dmdt(I1.V, I1.m), #dm/dt for sodium channel
            I1.NaT.dhdt(I1.V, I1.h) #dh/dt for sodium channel
           ]
    return dydt
X = odeint(Run, [-70, 0.0050, 0.9961], t)

Body:
The bottleneck of your integration is almost certainly evaluation the derivative Run, as this has to be called multiple times for every step of integration. Right now, you have a considerable Python overhead in there due to all the class members and function calls.

One solution for this is using the module JiTCODE by yours truly, where instead of defining a function to be used by the integrator, you define the differential equations symbolically (with SymPy). They are then translated to C code, which is compiled to a Python function, which in turn is used for integrating. This way, your classes and class functions are only called a few times before the actual integration and the integration is as efficient as it would be if you defined your derivative without classes and similar. (Also, you may get a considerable speed boost through compilation, in particular if you have many neurons.)

As it stands, you translating your example to JiTCODE is straightforward:

from jitcode import jitcode, provide_basic_symbols

t, y = provide_basic_symbols()

class NaL():
    […]

class Neuron():
    […]

I1 = Neuron()

I1.V, I1.m, I1.h = y(0), y(1), y(2)

Run = [
    (0 - I1.I_Na()) / I1.C_m,
    I1.NaT.dmdt(I1.V, I1.m),
    I1.NaT.dhdt(I1.V, I1.h)
]

t = range(100)

ODE = jitcode(Run)
ODE.set_initial_value([-70,0.0050,0.9961], t[0])
X = np.vstack(ODE.integrate for time in t[1:])

This code does not work right now for the same reasons that your example code does not work. Note that all the arithmetics in your class that involves dynamical variables becomes symbolic. With additions and multiplications, this works out of the box, but if you have something like math.sin or sympy.sin, you have to replace it by sympy.sin.


问:
On long press context menu (floating menu) not getting call when registerForContextMenu(photoViewAttacher.getImageView())?
ImageView attached to PhotoViewAttacher. But as I have used it in PhotoViewAttacher, OnLong press onCreateContextMenu() not getting called.

```<code>photoViewAttacher = new PhotoViewAttacher(imageView);
registerForContextMenu(photoViewAttacher.getImageView());

imageView.setImageDrawable(getResources().getDrawable(R.drawable.placeholder));

photoViewAttacher.update();

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            super.onCreateContextMenu(menu, v, menuInfo);
            MenuInflater menuInflater = getMenuInflater();
            menuInflater.inflate(R.menu.context_menu, menu);
}
</code>```

How it will work?

答:
ok I just checked what PhotoViewAttacher is. For showing contextmenu you will have to do this

```<code>photoViewAttacher.setOnLongClickListener(myLongClickListener);
</code>```

And in onLongClick method of myLongClickListener call openContextMenu(photoViewAttacher.getImageView())

Hope that helps.

Body:
ImageView attached to PhotoViewAttacher. But as I have used it in PhotoViewAttacher, OnLong press onCreateContextMenu() not getting called.

photoViewAttacher = new PhotoViewAttacher(imageView);
registerForContextMenu(photoViewAttacher.getImageView());

imageView.setImageDrawable(getResources().getDrawable(R.drawable.placeholder));

photoViewAttacher.update();

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            super.onCreateContextMenu(menu, v, menuInfo);
            MenuInflater menuInflater = getMenuInflater();
            menuInflater.inflate(R.menu.context_menu, menu);
}

How it will work?

Body:
ok I just checked what PhotoViewAttacher is. For showing contextmenu you will have to do this

photoViewAttacher.setOnLongClickListener(myLongClickListener);

And in onLongClick method of myLongClickListener call openContextMenu(photoViewAttacher.getImageView())

Hope that helps.


问:
Indexes of all occurrences of character in a string
The following code will print 2

```<code>String word = "bannanas";
String guess = "n";
int index;
System.out.println(
    index = word.indexOf(guess)
);
</code>```

I would like to know how to get all the indexes of "n" ("guess") in the string "bannanas"

The expected result would be: [2,3,5]

答:
A class for splitting strings I came up with. A short test is provided at the end.

SplitStringUtils.smartSplitToShorterStrings(String str, int maxLen, int maxParts) will split by spaces without breaking words, if possible, and if not, will split by indexes according to maxLen.

Other methods provided to control how it is split: bruteSplitLimit(String str, int maxLen, int maxParts), spaceSplit(String str, int maxLen, int maxParts).

```<code>public class SplitStringUtils {

  public static String[] smartSplitToShorterStrings(String str, int maxLen, int maxParts) {
    if (str.length() <= maxLen) {
      return new String[] {str};
    }
    if (str.length() > maxLen*maxParts) {
      return bruteSplitLimit(str, maxLen, maxParts);
    }

    String[] res = spaceSplit(str, maxLen, maxParts);
    if (res != null) {
      return res;
    }

    return bruteSplitLimit(str, maxLen, maxParts);
  }

  public static String[] bruteSplitLimit(String str, int maxLen, int maxParts) {
    String[] bruteArr = bruteSplit(str, maxLen);
    String[] ret = Arrays.stream(bruteArr)
          .limit(maxParts)
          .collect(Collectors.toList())
          .toArray(new String[maxParts]);
    return ret;
  }

  public static String[] bruteSplit(String name, int maxLen) {
    List<String> res = new ArrayList<>();
    int start =0;
    int end = maxLen;
    while (end <= name.length()) {
      String substr = name.substring(start, end);
      res.add(substr);
      start = end;
      end +=maxLen;
    }
    String substr = name.substring(start, name.length());
    res.add(substr);
    return res.toArray(new String[res.size()]);
  }

  public static String[] spaceSplit(String str, int maxLen, int maxParts) {
    List<Integer> spaceIndexes = findSplitPoints(str, ' ');
    List<Integer> goodSplitIndexes = new ArrayList<>();
    int goodIndex = -1;
    int curPartMax = maxLen;
    for (int i=0; i< spaceIndexes.size(); i++) {
      int idx = spaceIndexes.get(i);
      if (idx < curPartMax) {
        goodIndex = idx;
      } else {
        goodSplitIndexes.add(goodIndex+1);
        curPartMax = goodIndex+1+maxLen;
      }
    }
    if (goodSplitIndexes.get(goodSplitIndexes.size()-1) != str.length()) {
      goodSplitIndexes.add(str.length());
    }
    if (goodSplitIndexes.size()<=maxParts) {
      List<String> res = new ArrayList<>();
      int start = 0;
      for (int i=0; i<goodSplitIndexes.size(); i++) {
        int end = goodSplitIndexes.get(i);
        if (end-start > maxLen) {
          return null;
        }
        res.add(str.substring(start, end));
        start = end;
      }
      return res.toArray(new String[res.size()]);
    }
    return null;
  }

  private static List<Integer> findSplitPoints(String str, char c) {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) == c) {
        list.add(i);
      }
    }
    list.add(str.length());
    return list;
  }
}
</code>```

Simple test code:

```<code>  public static void main(String[] args) {
    String [] testStrings = {
        "123",
        "123 123 123 1123 123 123 123 123 123 123",
        "123 54123 5123 513 54w567 3567 e56 73w45 63 567356 735687 4678 4678 u4678 u4678 56rt64w5 6546345",
        "1345678934576235784620957029356723578946",
        "12764444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444",
        "3463356 35673567567 3567 35 3567 35 675 653 673567 777777777777777777777777777777777777777777777777777777777777777777"
    };

    int max = 35;
    int maxparts = 2;

    for (String str : testStrings) {
      System.out.println("TEST\n    |"+str+"|");
      printSplitDetails(max, maxparts);
      String[] res = smartSplitToShorterStrings(str, max, maxparts);
      for (int i=0; i< res.length;i++) {
        System.out.println("  "+i+": "+res[i]);
      }
      System.out.println("===========================================================================================================================================================");
    }

  }

  static void printSplitDetails(int max, int maxparts) {
    System.out.print("  X: ");
    for (int i=0; i<max*maxparts; i++) {
      if (i%max == 0) {
        System.out.print("|");
      } else {
        System.out.print("-");
      }
    }
    System.out.println();
  }
</code>```

Body:
The following code will print 2

String word = "bannanas";
String guess = "n";
int index;
System.out.println(
    index = word.indexOf(guess)
);

I would like to know how to get all the indexes of "n" ("guess") in the string "bannanas"

The expected result would be: [2,3,5]

Body:
A class for splitting strings I came up with. A short test is provided at the end.

SplitStringUtils.smartSplitToShorterStrings(String str, int maxLen, int maxParts) will split by spaces without breaking words, if possible, and if not, will split by indexes according to maxLen.

Other methods provided to control how it is split: bruteSplitLimit(String str, int maxLen, int maxParts), spaceSplit(String str, int maxLen, int maxParts).

public class SplitStringUtils {

  public static String[] smartSplitToShorterStrings(String str, int maxLen, int maxParts) {
    if (str.length() <= maxLen) {
      return new String[] {str};
    }
    if (str.length() > maxLen*maxParts) {
      return bruteSplitLimit(str, maxLen, maxParts);
    }

    String[] res = spaceSplit(str, maxLen, maxParts);
    if (res != null) {
      return res;
    }

    return bruteSplitLimit(str, maxLen, maxParts);
  }

  public static String[] bruteSplitLimit(String str, int maxLen, int maxParts) {
    String[] bruteArr = bruteSplit(str, maxLen);
    String[] ret = Arrays.stream(bruteArr)
          .limit(maxParts)
          .collect(Collectors.toList())
          .toArray(new String[maxParts]);
    return ret;
  }

  public static String[] bruteSplit(String name, int maxLen) {
    List<String> res = new ArrayList<>();
    int start =0;
    int end = maxLen;
    while (end <= name.length()) {
      String substr = name.substring(start, end);
      res.add(substr);
      start = end;
      end +=maxLen;
    }
    String substr = name.substring(start, name.length());
    res.add(substr);
    return res.toArray(new String[res.size()]);
  }

  public static String[] spaceSplit(String str, int maxLen, int maxParts) {
    List<Integer> spaceIndexes = findSplitPoints(str, ' ');
    List<Integer> goodSplitIndexes = new ArrayList<>();
    int goodIndex = -1;
    int curPartMax = maxLen;
    for (int i=0; i< spaceIndexes.size(); i++) {
      int idx = spaceIndexes.get(i);
      if (idx < curPartMax) {
        goodIndex = idx;
      } else {
        goodSplitIndexes.add(goodIndex+1);
        curPartMax = goodIndex+1+maxLen;
      }
    }
    if (goodSplitIndexes.get(goodSplitIndexes.size()-1) != str.length()) {
      goodSplitIndexes.add(str.length());
    }
    if (goodSplitIndexes.size()<=maxParts) {
      List<String> res = new ArrayList<>();
      int start = 0;
      for (int i=0; i<goodSplitIndexes.size(); i++) {
        int end = goodSplitIndexes.get(i);
        if (end-start > maxLen) {
          return null;
        }
        res.add(str.substring(start, end));
        start = end;
      }
      return res.toArray(new String[res.size()]);
    }
    return null;
  }

  private static List<Integer> findSplitPoints(String str, char c) {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) == c) {
        list.add(i);
      }
    }
    list.add(str.length());
    return list;
  }
}

Simple test code:

  public static void main(String[] args) {
    String [] testStrings = {
        "123",
        "123 123 123 1123 123 123 123 123 123 123",
        "123 54123 5123 513 54w567 3567 e56 73w45 63 567356 735687 4678 4678 u4678 u4678 56rt64w5 6546345",
        "1345678934576235784620957029356723578946",
        "12764444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444",
        "3463356 35673567567 3567 35 3567 35 675 653 673567 777777777777777777777777777777777777777777777777777777777777777777"
    };

    int max = 35;
    int maxparts = 2;

    for (String str : testStrings) {
      System.out.println("TEST\n    |"+str+"|");
      printSplitDetails(max, maxparts);
      String[] res = smartSplitToShorterStrings(str, max, maxparts);
      for (int i=0; i< res.length;i++) {
        System.out.println("  "+i+": "+res[i]);
      }
      System.out.println("===========================================================================================================================================================");
    }

  }

  static void printSplitDetails(int max, int maxparts) {
    System.out.print("  X: ");
    for (int i=0; i<max*maxparts; i++) {
      if (i%max == 0) {
        System.out.print("|");
      } else {
        System.out.print("-");
      }
    }
    System.out.println();
  }


问:
Php days error when calculating -1 month
I surprised when i getting the issue in PHP date calculation.

```<code>$add = '- 30 days';
echo date('Y-m-01', strtotime($add)); // result is 2017-02-01 which is correct as need
</code>```

but in

```<code>$add = '-1 month';
echo date('Y-m-01', strtotime($add)); // result is 2017-03-01 which is in correct
</code>```

please help me in this how could i resolve this issue.

答:
In your case you Calculating February month. In February month have only 28 days right?

As noted in several blogs, strtotime() solves the "-1 month" ("previos month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.

```<code><?php
echo date( "Y-m-d", strtotime( "2017-01-31 -1 month" ) ); // PHP:  2016-12-31
echo date( "Y-m-d", strtotime( "2017-01-31 -2 month" ) ); // PHP:  2016-12-01
?>
</code>```

If you calculate like this you get correct:

```<code>$add = '- 28 days';
echo date('Y-m-01', strtotime($add))."<br/>";

$add = '-1 month';
echo date('Y-m-01', strtotime($add))."<br/>";
</code>```

Body:
I surprised when i getting the issue in PHP date calculation.

$add = '- 30 days';
echo date('Y-m-01', strtotime($add)); // result is 2017-02-01 which is correct as need

but in

$add = '-1 month';
echo date('Y-m-01', strtotime($add)); // result is 2017-03-01 which is in correct

please help me in this how could i resolve this issue.

Body:
In your case you Calculating February month. In February month have only 28 days right?

As noted in several blogs, strtotime() solves the "-1 month" ("previos month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.

<?php
echo date( "Y-m-d", strtotime( "2017-01-31 -1 month" ) ); // PHP:  2016-12-31
echo date( "Y-m-d", strtotime( "2017-01-31 -2 month" ) ); // PHP:  2016-12-01
?>

If you calculate like this you get correct:

$add = '- 28 days';
echo date('Y-m-01', strtotime($add))."<br/>";

$add = '-1 month';
echo date('Y-m-01', strtotime($add))."<br/>";


问:
Can we execute the code beyond the time limit of 30 sec when extracting data from forum site?
I have a DOM web crawler in php and it works fine. all it does is to extract the mentioned specific class statements from a forum site and echo them in my php page.

So, since the forum site has more than 1000+ post, the DOM parser code extracts upto a limit and prints a error as Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\usmlemed\dom\simple_html_dom.php on line 75

so, how can i make the execution time to go till all statements are parsed?

答:
Use set_time_limit to set a limit for the whole processing. This is obviously to be set in the beginning of the script

```<code>set_time_limit(3600);
</code>```

http://php.net/manual/en/function.set-time-limit.php

Body:
Use set_time_limit to set a limit for the whole processing. This is obviously to be set in the beginning of the script

set_time_limit(3600);

http://php.net/manual/en/function.set-time-limit.php


问:
More than one value for the key user.name Git
For some reason I'm getting the error that "More than one value for the key user.name" when I try to set the user.name for my git account.  How can I set it to a single name?</p>

答:
Update (December 2012)

git1.8.1rc1 now operates differently:

"git config --get" used to diagnose presence of multiple definitions of the same variable in the same configuration file as an error, but it now applies the "last one wins" rule used by the internal configuration logic.

Strictly speaking, this may be an API regression but it is expected that nobody will notice it in practice.

Original answer (November 2010)

The git config man page mentions:

The variable names are case-insensitive and only alphanumeric characters and - are allowed.

  There can be more than one value for a given variable; we say then that variable is multivalued.

Actually, such config settings (with multiple possible values) are called multivar

As Jefromi suggests, see in what of the 3 config files you have more than one user.name line.

You can query multiple values like so:

```<code>git config --local  --get-all user.name #local repo git config file)
git config --global --get-all user.name #user config file)
git config --system --get-all user.name #system git config file)
</code>```

The one config file which answers more than one user.name value needs to be fixed.

From the comments:

Examining files "local", "global" and "settings" I can see only one user.name in global.

  But git config --list and git config --get-all user.name gives it twice to me

As I mention in here with Git 2.8 (March 2016), you can use (to see all settings:

```<code>git config -l --show-origin
</code>```

One you see where the duplicate setting is (local, global, system), you can use git config [--local/--global/--system] --replace-all key value, as in mb21's answer.

Body:
Update (December 2012)

git1.8.1rc1 now operates differently:

"git config --get" used to diagnose presence of multiple definitions of the same variable in the same configuration file as an error, but it now applies the "last one wins" rule used by the internal configuration logic.

Strictly speaking, this may be an API regression but it is expected that nobody will notice it in practice.

Original answer (November 2010)

The git config man page mentions:

The variable names are case-insensitive and only alphanumeric characters and - are allowed.

  There can be more than one value for a given variable; we say then that variable is multivalued.

Actually, such config settings (with multiple possible values) are called multivar

As Jefromi suggests, see in what of the 3 config files you have more than one user.name line.

You can query multiple values like so:

git config --local  --get-all user.name #local repo git config file)
git config --global --get-all user.name #user config file)
git config --system --get-all user.name #system git config file)

The one config file which answers more than one user.name value needs to be fixed.

From the comments:

Examining files "local", "global" and "settings" I can see only one user.name in global.

  But git config --list and git config --get-all user.name gives it twice to me

As I mention in here with Git 2.8 (March 2016), you can use (to see all settings:

git config -l --show-origin

One you see where the duplicate setting is (local, global, system), you can use git config [--local/--global/--system] --replace-all key value, as in mb21's answer.


问:
Can't add VS command prompt as a tool in VS15 Community

Arguments: /k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat"

I want to add visual studio command prompt as a tool. I try with all kind of ways, but still can't able to open vs cmd.

[![enter image description here][2]][2]

This is what cmd shows when i run CMD tool.
Framework: .NET Framework 4.6

Can anyone tell me where i am doing mistake?

答:
If I'm not mistaken (I have several Visual Studio versions installed so I'm talking from memory here), Visual Studio 2015 uses Microsoft Visual Studio 14.0 as a folder. You are using 12.0 which won't more likely contain a VsDevCmd.bat file (not even a Tools folder inside Common7).

Try changing it to /k "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat"


问:
Align time series by setting the start date of each serie on an anchor date (icCube)
(I hope my title is clear)

I have a MDX statement that results in:

time (months) in the rows

several projects in the columns

The data displayed is an amount (e.g. costs).

Now I would like to compare the project expenditure for each project and see if there are temporal differences. As such I want to get a fictive time axis (start month, month + 1, month + 2, .... month + 60) and for each relative month the expenditure for each project.

I will give a data example to illustrate (attached picture). (consider the green part as the lifetime of the project - you can assume 0 costs during the lifetime and null costs outside the lifetime):

I think I can write a rather complex MDX for this (e.g. use the current period as the start month and add 12 months to it), then for each project lookup the amount in the "current projected period" - "start date of the project". It will be a bit messy though.

Is there an easier way to do this. For example using one or more of icCube's custom Matrix/Vector functions? I would like to use the end result in a widget to graphically display the data.

答:
We're looking for a table like this one :

```<code>+----------+-----------------+----------------+
|          |   Proj1         | Proj2          |
+----------+-----------------+----------------+
| Month 1  | (Month1,Proj1)  | (Month1,Proj2) |
| Month 2  | (Month2,Proj1)  | (Month2,Proj2) |
| Month 3  | (Month2,Proj1)  | (Month3,Proj2) |
+----------+-----------------+----------------+
</code>```

Where

```<code> MonthN is the Nth month from the start of the project
</code>```

This MonthN changes dynamically on each cell and will depend on the start date of the project. In MDX this is a calculated member that should look like :

```<code>MyCalcM AS IIF( [Project].current.isAll, null, ProjectStartDate([Project].current).lag(n) )
</code>```

where ProjectStartDate is a function that returns the start date of a project. We won't enter how this function is but we can create a cached schema level declared function with a static context so it will be calculated just once.

Now we need to link this calculated measure with a [project date] dimension.
In MDX this can be done with what we call an Utility dimension ( link ). Utility dimensions are dimension that define a transformation, aka calc. member, for each each of his members instead of the clasical slice&dice behavior.

There are different solutions for building this dimension.

One is doing something similar as the historgram defined here, this might be a bit cumbersome as you need to create manually each member.

Another one is creating directly from a fact table the new dimension, [Project Time], that is not linked in the schema to any facts like this one :

```<code> Name ,  addMonths
 First Month, 0
 Month 2, 1
 Month 3, 2
 ..
 Month N, n-1
</code>```

We have to create a calculated member that binds this dimension to the calc. members using the member key to calculate the lag ( lag(n) -> lag( [Project Time].current.key ) ) . The drawback of this solution is that we need to activate this calculated measure.

hope it helps

Body:
We're looking for a table like this one :

+----------+-----------------+----------------+
|          |   Proj1         | Proj2          |
+----------+-----------------+----------------+
| Month 1  | (Month1,Proj1)  | (Month1,Proj2) |
| Month 2  | (Month2,Proj1)  | (Month2,Proj2) |
| Month 3  | (Month2,Proj1)  | (Month3,Proj2) |
+----------+-----------------+----------------+

Where

 MonthN is the Nth month from the start of the project

This MonthN changes dynamically on each cell and will depend on the start date of the project. In MDX this is a calculated member that should look like :

MyCalcM AS IIF( [Project].current.isAll, null, ProjectStartDate([Project].current).lag(n) )

where ProjectStartDate is a function that returns the start date of a project. We won't enter how this function is but we can create a cached schema level declared function with a static context so it will be calculated just once.

Now we need to link this calculated measure with a [project date] dimension.
In MDX this can be done with what we call an Utility dimension ( link ). Utility dimensions are dimension that define a transformation, aka calc. member, for each each of his members instead of the clasical slice&dice behavior.

There are different solutions for building this dimension.

One is doing something similar as the historgram defined here, this might be a bit cumbersome as you need to create manually each member.

Another one is creating directly from a fact table the new dimension, [Project Time], that is not linked in the schema to any facts like this one :

 Name ,  addMonths
 First Month, 0
 Month 2, 1
 Month 3, 2
 ..
 Month N, n-1

We have to create a calculated member that binds this dimension to the calc. members using the member key to calculate the lag ( lag(n) -> lag( [Project Time].current.key ) ) . The drawback of this solution is that we need to activate this calculated measure.

hope it helps


问:
How to undo the row added in the grid of extjs
I want to how can we undo the specific being added in the grid before actually saving it .

Please have a look at this

I 've added two rows but since for eg: for some validations failures the second row is not valid so I want to undo the second row but keeping the first dirty for the saving of that data to the db.

What i was trying is I was pushing all the dirty rows to an array and then updating in the database. But I don't know how to undo or delete the invalid row being added. Without reloading the grid
Example for reference
Live example

答:
You shouldn't have to push the rows into an array for synchronization. What you really want to use is the methods available on the underlying store and/or model.

To reject the second model and update all other ones in the database, two lines suffice. The exact code may differ depending on the Ext version; in ExtJS 6.2.1, it would be:

grid.getStore().getAt(1).reject() (or .drop())

grid.getStore().sync()

while the generalized approach would be to reject all invalid models:

```<code>var store = grid.getStore(),
    invalidRecords = store.query(function(record) {
        return !record.getValidation().isValid();
    });
invalidRecords.each(function(record) {
     record.reject();
})
store.sync();
</code>```

Body:
You shouldn't have to push the rows into an array for synchronization. What you really want to use is the methods available on the underlying store and/or model.

To reject the second model and update all other ones in the database, two lines suffice. The exact code may differ depending on the Ext version; in ExtJS 6.2.1, it would be:

grid.getStore().getAt(1).reject() (or .drop())

grid.getStore().sync()

while the generalized approach would be to reject all invalid models:

var store = grid.getStore(),
    invalidRecords = store.query(function(record) {
        return !record.getValidation().isValid();
    });
invalidRecords.each(function(record) {
     record.reject();
})
store.sync();


问:
Failed to execute 'play' on 'HTMLMediaElement': API can only be initiated by a user gesture
I'm making a music playing page, where I use SoundManager 2 for AngularJs.
I'm using a remote API to get a song URL to play. I enhanced an angular-soundmanager2 click event handler :

```<code>element.bind('click', function () {
    if (angular.isFunction(scope.loadFunction)) {
        scope.loadFunction(scope.song, function () {
            $log.debug('adding song to playlist');
            addToPlaylist(scope.song.playDetails);

        })
    } else {
        $log.debug('adding song to playlist');
        addToPlaylist(scope.song);
    }
});
</code>```

Where I added a part, that calls scope.loadFunction(song,callback) and after this function loads a song URL it calls a callback to give the control back to angular-soundmanager2.

The problem is that on chrome for android I get an error :

```<code>Failed to execute 'play' on 'HTMLMediaElement': API can only be initiated by a user gesture.
</code>```

it doesn't happen if a song has a URL from the beginning and async loading isn't used.

Are there any workarounds for it?

答:
```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
  webSettings.setMediaPlaybackRequiresUserGesture(false);
}
</code>```

Body:
I'm making a music playing page, where I use SoundManager 2 for AngularJs.
I'm using a remote API to get a song URL to play. I enhanced an angular-soundmanager2 click event handler :

element.bind('click', function () {
    if (angular.isFunction(scope.loadFunction)) {
        scope.loadFunction(scope.song, function () {
            $log.debug('adding song to playlist');
            addToPlaylist(scope.song.playDetails);

        })
    } else {
        $log.debug('adding song to playlist');
        addToPlaylist(scope.song);
    }
});

Where I added a part, that calls scope.loadFunction(song,callback) and after this function loads a song URL it calls a callback to give the control back to angular-soundmanager2.

The problem is that on chrome for android I get an error :

Failed to execute 'play' on 'HTMLMediaElement': API can only be initiated by a user gesture.

it doesn't happen if a song has a URL from the beginning and async loading isn't used.

Are there any workarounds for it?