问:
how to use distinct to use join two table in mysql
This is my sql query to show hotels with price below 500

```<code>select a.*, b.room_price, b.hotel_id
from hotels a , hotel_room_type b
where a.sub_destination_id=1
and a.destination_id=1 and
a.id = b.hotel_id
and b.room_price BETWEEN 0 AND 500
</code>```

here showing duplicate record
ids 190 have come two time , how can i solve

答:
try with this</p>

```<code>SELECT a.*,
   b.room_price,
   b.hotel_id
FROM   hotels a
   INNER JOIN hotel_room_type b
           ON a.id = b.hotel_id
WHERE  a.sub_destination_id = 1
   AND a.destination_id = 1
   AND b.room_price BETWEEN 0 AND 500
GROUP  BY a.id
</code>```

Body:
This is my sql query to show hotels with price below 500

select a.*, b.room_price, b.hotel_id
from hotels a , hotel_room_type b
where a.sub_destination_id=1
and a.destination_id=1 and
a.id = b.hotel_id
and b.room_price BETWEEN 0 AND 500

here showing duplicate record
ids 190 have come two time , how can i solve

Body:
try with this

SELECT a.*,
   b.room_price,
   b.hotel_id
FROM   hotels a
   INNER JOIN hotel_room_type b
           ON a.id = b.hotel_id
WHERE  a.sub_destination_id = 1
   AND a.destination_id = 1
   AND b.room_price BETWEEN 0 AND 500
GROUP  BY a.id


来源: stackexchange

问:
What is the relationship between real collections' names and those in file system
I use MongoDB 3.0 with WiredTiger storage engine.
When I checked my Mongo files in dbPath, I saw the names of the files with the formats as below:
collection-0--4989330656807016483.wt
collection-2--4989330656807016483.wt
collection-4--4989330656807016483.wt
.
.
.
How can I know the relationship between these file names and real collections' names except the way of data size??</p>

答:
Use this</p>

```<code>db.getCollection('collection_name').stats()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use this

db.getCollection('collection_name').stats()


问:
reading two long sentences using scanf
I want to read two long sentences from input using scanf() which are in two new lines.

Code:

```<code>int main() {
    char a[100], b[100];
    scanf("%[^\n]s", a);
    scanf("%[^\n]s", b);
    printf("%s\n%s", a, b);
}
</code>```

Input:

```<code>she is beautiful
That is a flower
</code>```

Output:

```<code>she is beautiful
</code>```

The second input is not being read by the scanf() statement.

How to fix it?

答:
Use like this </p>

```<code>int main(){

    char a[100];

    while (scanf("%[^\n]%*c", a)==1) {
     printf("%s\n",a);
    }
    return 0;
  }
</code>```

Title: reading two long sentences using scanf

Body:
I want to read two long sentences from input using scanf() which are in two new lines.

Code:

int main() {
    char a[100], b[100];
    scanf("%[^\n]s", a);
    scanf("%[^\n]s", b);
    printf("%s\n%s", a, b);
}

Input:

she is beautiful
That is a flower

Output:

she is beautiful

The second input is not being read by the scanf() statement.

How to fix it?

Body:
Use like this

int main(){

    char a[100];

    while (scanf("%[^\n]%*c", a)==1) {
     printf("%s\n",a);
    }
    return 0;
  }


问:
Problems encoding japanese characters in Excel5 output PHPExcel
I'm using PHPExcel on a restricted server running PHP 5.6.

I have some Japanese characters that I'm trying to include in a CSV and Excel output. Seeing as there's potential to have the same output also in HTML or PDF I'm using PHPExcel to build all the data and just changing the writer depending on the request.

I've managed to get CSV export to open successfully in Excel by using $objWriter->setUseBOM(true) however exporting as an Excel file I'm getting the Japanese characters replaced with nonsense, such as:

```<code>Ã©ÂÂÃ¤Â¿Â¡Ã£ÂÂÃ£ÂÂÃ£ÂÂÃ¯Â¼Â©Ã¯Â¼Â¤Ã£ÂÂ¡Ã£ÂÂ¼Ã£ÂÂ«Ã£ÂÂ«Ã¯Â¼Â©Ã¯Â¼Â¤Ã£ÂÂ®Ã¨Â¨ÂÃ¨Â¼ÂÃ£ÂÂÃ£ÂÂªÃ£ÂÂ
</code>```

From what I've read my best bet is to convert the string to UTF-16LE, however, I don't have access to mb_string or iconv and I'm struggling to see how else I can solve this. I wondered whether Excel2007 would have the same issues, but I don't have access to php_zip or to zlib in order to use PCLZip. I think I'm screwed.

Does anyone have any idea how I can get Excel to correctly interpret these characters?

答:
In my case, the problem is the lack of mb_convert_encoding or iconv on the server. Without those, the encoding from UTF-8 to Biff8 (see PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong) doesn't happen correctly.

In this case PHPExcel_Shared_String::ConvertEncoding simply returns the original character, which will not make sense in Biff8 - hence the issues experienced.

A standalone converter would need to be written, which is possible but is excessive for this particular situation where we can simply fall back to CSV. If anyone else gets this problem I would first check for the presence of mb_convert_encoding or iconv and, if possible, install those.

Body:
I'm using PHPExcel on a restricted server running PHP 5.6.

I have some Japanese characters that I'm trying to include in a CSV and Excel output. Seeing as there's potential to have the same output also in HTML or PDF I'm using PHPExcel to build all the data and just changing the writer depending on the request.

I've managed to get CSV export to open successfully in Excel by using $objWriter->setUseBOM(true) however exporting as an Excel file I'm getting the Japanese characters replaced with nonsense, such as:

Ã©ÂÂÃ¤Â¿Â¡Ã£ÂÂÃ£ÂÂÃ£ÂÂÃ¯Â¼Â©Ã¯Â¼Â¤Ã£ÂÂ¡Ã£ÂÂ¼Ã£ÂÂ«Ã£ÂÂ«Ã¯Â¼Â©Ã¯Â¼Â¤Ã£ÂÂ®Ã¨Â¨ÂÃ¨Â¼ÂÃ£ÂÂÃ£ÂÂªÃ£ÂÂ

From what I've read my best bet is to convert the string to UTF-16LE, however, I don't have access to mb_string or iconv and I'm struggling to see how else I can solve this. I wondered whether Excel2007 would have the same issues, but I don't have access to php_zip or to zlib in order to use PCLZip. I think I'm screwed.

Does anyone have any idea how I can get Excel to correctly interpret these characters?


问:
how to treat a single table as multiple tables in sql
I came across this sql challenge from Hackerrank.com
sample Input :

```<code>select * from occupation
</code>```

sample output :

```<code>Name        Occupation
samantha    doctor
jenny       doctor
julia       actor
maria       actor
jane        actor
meera       singer
priya       singer
ashley      professor
ketty       professor
christeen   professor
</code>```

Output should be :(doctor,professor,singer,actor also order by name)

```<code>jenny       ashley         meera       jane
samantha    christeen      priya       julia
null        ketty          null        maria
</code>```

What I have tried is :

```<code>SELECT DECODE(occupation,'doctor',name,NULL   ),DECODE(occupation,'professor',name,NULL),DECODE(occupation,'singer',name,NULL)  ,
DECODE(occupation , 'actor',name,NULL)
FROM occupation ;
</code>```

But it doesnot give me desired result.Also I have tried this :

```<code>SELECT oc1.name ,
oc2.name,oc3.name,oc4.name
FROM
(SELECT name,occupation FROM occupation WHERE occupation = 'doctor'
) oc1 ,
(SELECT name,occupation FROM occupation WHERE occupation = 'actor'
) oc2 ,
(SELECT name,occupation FROM occupation WHERE occupation = 'singer') oc3,
(SELECT name,occupation FROM occupation WHERE occupation = 'professor')oc4  ,   occupation oc

WHERE
oc1.occupation= oc.occupation(+)
and oc2.occupation = oc.occupation(+)
AND oc3.occupation       = oc.occupation(+)
AND oc4.occupation       = oc.occupation(+);
</code>```

But it gives duplicate records . Can someone please help me

Thanks

答:
Use a PIVOT:

```<code>SELECT doctor, professor, singer, actor
FROM   (
  SELECT o.*,
         ROW_NUMBER() OVER ( PARTITION BY occupation ORDER BY name ) AS rn
  FROM   occupation o
)
PIVOT ( MAX( name ) FOR Occupation IN (
  'doctor'    AS doctor,
  'actor'     AS actor,
  'singer'    AS singer,
  'professor' AS professor
) )
ORDER BY rn;
</code>```

Body:
I came across this sql challenge from Hackerrank.com
sample Input :

select * from occupation

sample output :

Name        Occupation
samantha    doctor
jenny       doctor
julia       actor
maria       actor
jane        actor
meera       singer
priya       singer
ashley      professor
ketty       professor
christeen   professor

Output should be :(doctor,professor,singer,actor also order by name)

jenny       ashley         meera       jane
samantha    christeen      priya       julia
null        ketty          null        maria

What I have tried is :

SELECT DECODE(occupation,'doctor',name,NULL   ),DECODE(occupation,'professor',name,NULL),DECODE(occupation,'singer',name,NULL)  ,
DECODE(occupation , 'actor',name,NULL)
FROM occupation ;

But it doesnot give me desired result.Also I have tried this :

SELECT oc1.name ,
oc2.name,oc3.name,oc4.name
FROM
(SELECT name,occupation FROM occupation WHERE occupation = 'doctor'
) oc1 ,
(SELECT name,occupation FROM occupation WHERE occupation = 'actor'
) oc2 ,
(SELECT name,occupation FROM occupation WHERE occupation = 'singer') oc3,
(SELECT name,occupation FROM occupation WHERE occupation = 'professor')oc4  ,   occupation oc

WHERE
oc1.occupation= oc.occupation(+)
and oc2.occupation = oc.occupation(+)
AND oc3.occupation       = oc.occupation(+)
AND oc4.occupation       = oc.occupation(+);

But it gives duplicate records . Can someone please help me

Thanks

Body:
Use a PIVOT:

SELECT doctor, professor, singer, actor
FROM   (
  SELECT o.*,
         ROW_NUMBER() OVER ( PARTITION BY occupation ORDER BY name ) AS rn
  FROM   occupation o
)
PIVOT ( MAX( name ) FOR Occupation IN (
  'doctor'    AS doctor,
  'actor'     AS actor,
  'singer'    AS singer,
  'professor' AS professor
) )
ORDER BY rn;


问:
SQL - building a certain query (intersect between two conditions)
i have a table that has two columns (that are relevant to my question) - Companies and Products.
It is providing me information about which companies use several Products.

For instance, lets say i want to retrieve all the companies that using Microsoft Office, i will query with a condition - product = Microsoft Office.

now, my question -
I need to build a query that will retrieve me all the companies that are using two products, not just one.
How should i build the query?
I think it should sort of use subquery maybe? because the SQL need to do two queries - one for each product i want, and than intersect both queries in order to find the companies that are in both lists...

Thanks alot for the helpers!

答:
Thomas is right and to add the two products:</p>

```<code>SELECT
    COUNT(*),
    <name of the company column>,
    <name of the product column>
FROM
    <table name>
GROUP BY
    <name of the company column>
HAVING
    COUNT(*) = 2
    AND <name of the product column> IN ('product1', 'product2');
</code>```

Body:
Thomas is right and to add the two products:

SELECT
    COUNT(*),
    <name of the company column>,
    <name of the product column>
FROM
    <table name>
GROUP BY
    <name of the company column>
HAVING
    COUNT(*) = 2
    AND <name of the product column> IN ('product1', 'product2');


问:
Android: Error while installing APKs
I'm slowly trying to do some simple tasks in Android Studio. The following app is installed on emulator without any errors. But when I tried to install it on a real device Redmi 3S this error occured:

```<code>Unknown failure (Failure - not installed for 0)
Error while Installing APKs
</code>```

I went through similar questions around here but in these cases the error was caused by not enabled debugging, or not accepitng the app instalation. However, I allowed debugging and I also tried to install some other app in Studio and it worked fine.

So the question probably is, what's wrong with the code.

MainActivity.java

```<code>package tlacitko.button;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

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

    public void sendMessage(View view) {
        new Thread(new Runnable() {
            public void run() {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            URL url = new URL("http://147.32.186.51:8080");
                           // HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                            InputStream is = url.openStream();
                            BufferedReader br = new BufferedReader(new
                                    InputStreamReader(is));
                            String s = "";
                        }catch(MalformedURLException ex){

                        }catch(IOException e){
                        }
                    }
                });
            }
        }).start();
    }
}
</code>```

And the xml code:

activity_main.xml

```<code>    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Try to connect the server."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="7dp"
        android:layout_marginTop="16dp"
        android:onClick="sendMessage"
        android:text="Conncect"
        app:layout_constraintLeft_toRightOf="@+id/editText"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

答:
For Redmi and Mi devices turn off MIUI Optimization and reboot your phone.

Settings > Additional Settings > Developer Options > MIUI Optimization

Check Answer here

Title: Android: Error while installing APKs

Body:
I'm slowly trying to do some simple tasks in Android Studio. The following app is installed on emulator without any errors. But when I tried to install it on a real device Redmi 3S this error occured:

Unknown failure (Failure - not installed for 0)
Error while Installing APKs

I went through similar questions around here but in these cases the error was caused by not enabled debugging, or not accepitng the app instalation. However, I allowed debugging and I also tried to install some other app in Studio and it worked fine.

So the question probably is, what's wrong with the code.

MainActivity.java

package tlacitko.button;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

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

    public void sendMessage(View view) {
        new Thread(new Runnable() {
            public void run() {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            URL url = new URL("http://147.32.186.51:8080");
                           // HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                            InputStream is = url.openStream();
                            BufferedReader br = new BufferedReader(new
                                    InputStreamReader(is));
                            String s = "";
                        }catch(MalformedURLException ex){

                        }catch(IOException e){
                        }
                    }
                });
            }
        }).start();
    }
}

And the xml code:

activity_main.xml

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Try to connect the server."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="7dp"
        android:layout_marginTop="16dp"
        android:onClick="sendMessage"
        android:text="Conncect"
        app:layout_constraintLeft_toRightOf="@+id/editText"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>


问:
Can't enter square brackets in gfsh
When I try to enter square brackets inside gfsh they do not always show on screen and if they are followed by digits the first two are not considered.

If I for example enter connect --locator=somehost[12345] this is shown:

It seems to help when I hit [ twice because then one [ makes it to the screen. But it remains impossible to get the closing square bracket ].

Please note that I use a German setting and thus have to press AltGr + 8 for the opening square bracket [ and AltGr + 9 for the closing square bracket ].
Other characters work, for example { and } which I also have to enter using AltGr + 7. The backslash \ that I have to enter by pressing AltGr + ß doesn't work too.

I posted this problem also on the Geode Jira.

答:
As a workaround it works to enter those special characters using their Ascii value.

On Windows this is:

Alt + 9 + 1 for the opening square
bracket [

Alt + 9 + 2 for the
backslash \

Alt + 9 + 3 for the
closing square bracket ]

Please note that you have to use the numerical keyboard for this.

Title: Can't enter square brackets in gfsh


问:
What's the best way to represent a tree with XML?
I'm implementing some classes to handle the common data structures (Tree, BinaryTree, Search Binary Tree, BTree, AVL, etc). I'd like a way to store tree information in a data source and parse it to one of those classes. The simplest way is to use XML (portability is very important). The thing is that the XML documents that i make are not easy to read. They're not enough "intuitive". For example, i was doing something like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<tree>
    <root>100</root>
    <node>
        <tree>
            <root>50</root>
        </tree>
    </node>
    <node>
        <tree>
            <root>200</root>
        </tree>
    </node>
</tree>
</code>```

There, the tree would be something like this:

```<code>                    100
              50                200
</code>```

What do you say? Do you have any other recommendation?

答: There is no 'best' way to represent a tree in XML. It all depends what you want to optimize your storage for - do you want to be able to track down a specific node quickly? Then a flat(er) representation might be better. If you want to keep the description non-verbose, then the method you outlined will be pretty good (though I would probably turn the 'root' child into an attribute (root/value), that way every node in the xml is actually a tree node).</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm implementing some classes to handle the common data structures (Tree, BinaryTree, Search Binary Tree, BTree, AVL, etc). I'd like a way to store tree information in a data source and parse it to one of those classes. The simplest way is to use XML (portability is very important). The thing is that the XML documents that i make are not easy to read. They're not enough "intuitive". For example, i was doing something like this:

<?xml version="1.0" encoding="UTF-8"?>
<tree>
    <root>100</root>
    <node>
        <tree>
            <root>50</root>
        </tree>
    </node>
    <node>
        <tree>
            <root>200</root>
        </tree>
    </node>
</tree>

There, the tree would be something like this:

                    100
              50                200

What do you say? Do you have any other recommendation?


问:
Get/Set global variable in Class in Laravel
I can't understand how to  make global variable, that I can in future change its value and get it over and over again?
My controller Example:

```<code>public function getProducts()
{
    // some stuff
    $products = SQLquery;
    config(['memoProducts' => $products]);
    $value = config('memoProducts');
    dd($value)//returns what I need

}

public function setProducts()
{
    //here I try to get $products from previous function
    $value = config('memoProducts');
    dd($value)//returns null
}
</code>```

What's my problem?

PS: thanks for thinking that I'm stupid af and minusing my question all day long, even though none of your answers  seem to help. Thanks a lot

答:
You can create constants.php file inside config folder.

```<code>return [

    'country_name' => env('COUNTRY_NAME','Bangladesh'),
    'city_name' => env('CITY_NAME','Dhaka')
];
</code>```

you can access this variable in two-way

```<code>Config::get('constants.country_name')
config('constants.country_name')
</code>```

for blade

```<code>{{ config('constants.country_name') }}
</code>```

Body:
I can't understand how to  make global variable, that I can in future change its value and get it over and over again?
My controller Example:

public function getProducts()
{
    // some stuff
    $products = SQLquery;
    config(['memoProducts' => $products]);
    $value = config('memoProducts');
    dd($value)//returns what I need

}

public function setProducts()
{
    //here I try to get $products from previous function
    $value = config('memoProducts');
    dd($value)//returns null
}

What's my problem?

PS: thanks for thinking that I'm stupid af and minusing my question all day long, even though none of your answers  seem to help. Thanks a lot

Body:
You can create constants.php file inside config folder.

return [

    'country_name' => env('COUNTRY_NAME','Bangladesh'),
    'city_name' => env('CITY_NAME','Dhaka')
];

you can access this variable in two-way

Config::get('constants.country_name')
config('constants.country_name')

for blade

{{ config('constants.country_name') }}


问:
Is it possible to monitor Jboss or apache server using Prometheus?
I'm working on monitoring and I used Prometheus with alertManager to alert user if filesystem is full, I'm looking if it is possible to monitor Jboss and Apache servers using Prometheus.</p>

答:
For Jboss you can use the jmx_exporter.

Apache doesn't produce good metrics, so you can use mtail or the grok_exporter on the logs.


问:
mvc phone number regex "or"
Im trying to make validation for phone number or cellphone number with country prefix (or without)
for ex:

1. 55-123-1234(home num) or 055-123-1234(cell phone) => [2,3][3][4]

2. or +999-55-123-1234 => +[3][2][3][4]

For now Im using the following regex: [RegularExpression(@"^([0-9]{2,3})[-. ]?[0-9]{3}[-. ]?([0-9]{4,6})$" but it covers only 1.

the last [3][4] will always be so my question is if there is a way to write => ([2,3]) or (+[3] [2])

The validation needs to cover (+[3] [2]) [3] [4] or ([2,3]) [3] [4] make it valid

If there is any way to do add "or" between (+[3][2]) to ([2,3])?

or maybe there is other way to it to make it valid?

Thanks in advance

答:
OR in regex is done with the | character.

+[3][2] or [2,3] is then written : \+\d{3}\-\d{2}|\d{2,3}

So for your complete regex, you can try the following :

(?:\+\d{3}[-. ]?\d{2}|\d{2,3})[-. ]?\d{3}[-. ]?\d{4}

Demo here

Title: mvc phone number regex "or"


答:
This needs a correct answer. If you insist on using scanf(), there's only one format string that is safe and will do what you want:

```<code>int main() {
    char a[100] = "";
    char b[100] = "";
    scanf("%99[^\n]%*c", a);
    scanf("%99[^\n]%*c", b);
    printf("%s\n%s", a, b);
}
</code>```

In your original string, you had [^\n]s which is wrong, because [^\n] is a conversion specifier itself, matching anything except a newline. So there shouldn't be an s following it.

The next change is the 99 prepended. This ensures a maximum of 99 characters is converted -- plus one byte for the terminating 0, you have exactly the 100 characters available in your array. Without that, if the user enters more than 99 characters, your buffer would overflow.

The last change is to append %*c: %c will match any character, in this case the newline that is left after matching %[^\n]. But you're not interested in it, you just want to consume it. This is what the * is for, it discards the result of the matching.

If you can, just use fgets() like this, it is much simpler to use for this case:

```<code>int main() {
    char a[100] = "";
    char b[100] = "";
    fgets(a, 100, stdin);
    fgets(b, 100, stdin);

    // if needed, strip newlines, e.g. like this:
    size_t n = strlen(a);
    if (n && a[n-1] == '\n') a[--n] = 0;
    n = strlen(b);
    if (n && b[n-1] == '\n') b[--n] = 0;

    printf("%s\n%s", a, b);
}
</code>```

Title: reading two long sentences using scanf

Body:
This needs a correct answer. If you insist on using scanf(), there's only one format string that is safe and will do what you want:

int main() {
    char a[100] = "";
    char b[100] = "";
    scanf("%99[^\n]%*c", a);
    scanf("%99[^\n]%*c", b);
    printf("%s\n%s", a, b);
}

In your original string, you had [^\n]s which is wrong, because [^\n] is a conversion specifier itself, matching anything except a newline. So there shouldn't be an s following it.

The next change is the 99 prepended. This ensures a maximum of 99 characters is converted -- plus one byte for the terminating 0, you have exactly the 100 characters available in your array. Without that, if the user enters more than 99 characters, your buffer would overflow.

The last change is to append %*c: %c will match any character, in this case the newline that is left after matching %[^\n]. But you're not interested in it, you just want to consume it. This is what the * is for, it discards the result of the matching.

If you can, just use fgets() like this, it is much simpler to use for this case:

int main() {
    char a[100] = "";
    char b[100] = "";
    fgets(a, 100, stdin);
    fgets(b, 100, stdin);

    // if needed, strip newlines, e.g. like this:
    size_t n = strlen(a);
    if (n && a[n-1] == '\n') a[--n] = 0;
    n = strlen(b);
    if (n && b[n-1] == '\n') b[--n] = 0;

    printf("%s\n%s", a, b);
}


问:
Getting "AssertionError("Unknown application type")" when Connecting to DSE 5.1.0 Spark
I am connecting to DSE (Spark) using this:

```<code>new SparkConf()
  .setAppName(name)
  .setMaster("spark://localhost:7077")
</code>```

With DSE 5.0.8 works fine (Spark 1.6.3) but now fails with DSE 5.1.0 getting this error:

```<code>java.lang.AssertionError: Unknown application type
at org.apache.spark.deploy.master.DseSparkMaster.registerApplication(DseSparkMaster.scala:88) ~[dse-spark-5.1.0.jar:2.0.2.6]
</code>```

After checking the use-spark jar, I've come up with this:

```<code>if(rpcendpointref instanceof DseAppProxy)
</code>```

And within spark, seems to be RpcEndpointRef (NettyRpcEndpointRef).

How can I fix this problem?

答:
I found a solution.

First of all, I think is impossible to run a Spark job within an Application within DSE 5.1. Has to be sent with dse spark-submit

Once sent, it works perfectly. In order to do the communications to the job I used Apache Kafka.

If you don't want to use a job, you can always go back to a Apache Spark.

Body:
I am connecting to DSE (Spark) using this:

new SparkConf()
  .setAppName(name)
  .setMaster("spark://localhost:7077")

With DSE 5.0.8 works fine (Spark 1.6.3) but now fails with DSE 5.1.0 getting this error:

java.lang.AssertionError: Unknown application type
at org.apache.spark.deploy.master.DseSparkMaster.registerApplication(DseSparkMaster.scala:88) ~[dse-spark-5.1.0.jar:2.0.2.6]

After checking the use-spark jar, I've come up with this:

if(rpcendpointref instanceof DseAppProxy)

And within spark, seems to be RpcEndpointRef (NettyRpcEndpointRef).

How can I fix this problem?


问:
How to get progress information inside a range based for loop?
I have a very long running for loop and I would like to print out some progress information.

With a normal for loop this is easy, since you can divide the loop-variable by the maximum to get a progress indicator, i.e. do something like this:

```<code>for(int i = 0; i<container.size(); i++) {
  if(i%10==0) System.out.println("Progress " +  Double.toString(i/container.size()*100.0) + "%.")
}
</code>```

Is there a way to do something like this without adding a counter variable (which somehow defeats the purpose of the range based for loop)?

```<code>//... Foreach loop over all elements in arr.
for (type var : arr) {
    body-of-loop
    // print progress info here?
}
</code>```

答:
You have a couple of problems,

an int / int is an int e.g. 5 / 10 = 0 (with 5 remainder)

the format will print 16 digits of accuracy which will look ugly.

I suggest you try

```<code>for (int i = 0; i < container.size(); i++) {
   if (i % 10 == 0)
       System.out.printf("Progress %.1f%%\n", 100.0 * i / container.size());
}
</code>```

By multiplying the 100.0 * first the number becomes a double so when you do the division it is a floating point number.

You could also adjust the fraction

```<code>int logEvery = Math.max(10, container.size() / 100);
for (int i = 0; i < container.size(); i++) {
   if (i % logEvery == 0)
       System.out.println("Progress " + 100 * i / container.size() + "%");
}
</code>```

This doesn't use floating point but by multiply by 100 first the number you are not discarding the portion done.

You can use a combination of integer and floating point

```<code>int logEvery = Math.max(10, container.size() / 1000);
for (int i = 0; i < container.size(); i++) {
   if (i % logEvery == 0)
       System.out.println("Progress " + 1000 * i / container.size() / 10.0 + "%");
}
</code>```

By multiplying by 1000 and dividing by 10.0, you get a percentage but with one decimal place.

Body:
I have a very long running for loop and I would like to print out some progress information.

With a normal for loop this is easy, since you can divide the loop-variable by the maximum to get a progress indicator, i.e. do something like this:

for(int i = 0; i<container.size(); i++) {
  if(i%10==0) System.out.println("Progress " +  Double.toString(i/container.size()*100.0) + "%.")
}

Is there a way to do something like this without adding a counter variable (which somehow defeats the purpose of the range based for loop)?

//... Foreach loop over all elements in arr.
for (type var : arr) {
    body-of-loop
    // print progress info here?
}

Body:
You have a couple of problems,

an int / int is an int e.g. 5 / 10 = 0 (with 5 remainder)

the format will print 16 digits of accuracy which will look ugly.

I suggest you try

for (int i = 0; i < container.size(); i++) {
   if (i % 10 == 0)
       System.out.printf("Progress %.1f%%\n", 100.0 * i / container.size());
}

By multiplying the 100.0 * first the number becomes a double so when you do the division it is a floating point number.

You could also adjust the fraction

int logEvery = Math.max(10, container.size() / 100);
for (int i = 0; i < container.size(); i++) {
   if (i % logEvery == 0)
       System.out.println("Progress " + 100 * i / container.size() + "%");
}

This doesn't use floating point but by multiply by 100 first the number you are not discarding the portion done.

You can use a combination of integer and floating point

int logEvery = Math.max(10, container.size() / 1000);
for (int i = 0; i < container.size(); i++) {
   if (i % logEvery == 0)
       System.out.println("Progress " + 1000 * i / container.size() / 10.0 + "%");
}

By multiplying by 1000 and dividing by 10.0, you get a percentage but with one decimal place.


问:
Understanding migrations in Realm - Swift
I'm trying to understand migrations, can someone describe situations where migrations are required?

For instance let's pretend for a moment that an app has been released and the following Realm objects were used but now version 2 needs to be released and a new Realm object was added to this new version, do I need a migration?

Version 1

```<code>import Foundation
import RealmSwift

class Item:Object{
    dynamic var productName:String = ""
    dynamic var createdAt = NSDate()
}

import Foundation
import RealmSwift

class ItemList: Object {
    dynamic var listName = ""
    dynamic var createdAt = NSDate()
    let items = List<Item>()
}
</code>```

Version 2

Version 2 needs a new object.

```<code>import Foundation
import RealmSwift

class Item:Object{
    dynamic var productName:String = ""
    dynamic var createdAt = NSDate()
}

import Foundation
import RealmSwift

class ItemList: Object {
    dynamic var listName = ""
    dynamic var createdAt = NSDate()
    let items = List<Item>()
}

// New object for version 2
import Foundation
import RealmSwift

class NewObjec:Object{
    dynamic var someString:String = ""
    dynamic var createdAt = NSDate()
}
</code>```

Do I need to create a migration if existing objects didn't change but an extra object was added?

In general, can someone describe the situations where migrations are needed?

Thanks a lot

答:
No, in this case you don't need to perform a migration. You only need to perform a migration in case existing objects need to be changed (adding/removing properties of existing Realm model classes).

If you add a new class to Realm, you don't need to perform a migration.

In most cases, Realm can automatically perform the migration and all you need to do is increase your schema version by 1. However, if you are for example combining two existing properties into a new one, you need to handle that manually in your migration block.

Body:
I'm trying to understand migrations, can someone describe situations where migrations are required?

For instance let's pretend for a moment that an app has been released and the following Realm objects were used but now version 2 needs to be released and a new Realm object was added to this new version, do I need a migration?

Version 1

import Foundation
import RealmSwift

class Item:Object{
    dynamic var productName:String = ""
    dynamic var createdAt = NSDate()
}

import Foundation
import RealmSwift

class ItemList: Object {
    dynamic var listName = ""
    dynamic var createdAt = NSDate()
    let items = List<Item>()
}

Version 2

Version 2 needs a new object.

import Foundation
import RealmSwift

class Item:Object{
    dynamic var productName:String = ""
    dynamic var createdAt = NSDate()
}

import Foundation
import RealmSwift

class ItemList: Object {
    dynamic var listName = ""
    dynamic var createdAt = NSDate()
    let items = List<Item>()
}

// New object for version 2
import Foundation
import RealmSwift

class NewObjec:Object{
    dynamic var someString:String = ""
    dynamic var createdAt = NSDate()
}

Do I need to create a migration if existing objects didn't change but an extra object was added?

In general, can someone describe the situations where migrations are needed?

Thanks a lot


问:
Optimize the for loop in python
Good, I currently have the following code:

```<code>n = 0
with open('/home/user/test.filter') as f:

    lines = f.readlines()

    for l in lines:
        if lines[n].startswith('-A vlan_8'):
            if "-o bond1.8" in lines[n]:
                    f = open('vlan8.filter_in', 'a')
                    f.write(l)
            else:
                f = open('vlan8.filter_out', 'a')
                f.write(l)
        if lines[n].startswith('-A vlan_10'):
            if "-o bond1.10" in lines[n]:
                f = open('vlan10.filter_in', 'a')
                f.write(l)
            else:
                f = open('vlan10.filter_out', 'a')
                f.write(l)
        if lines[n].startswith('-A vlan_15'):
            if "-o bond1.15" in lines[n]:
                f = open('vlan15.filter_in', 'a')
                f.write(l)
            else:
                f = open('vlan15.filter_out', 'a')
                f.write(l)

        # [...]

        n = n + 1
</code>```

I thought about optimizing it with some accumulator or list to not make the script so extensive. Any suggestions?

答:
Sure you can. Maintain a list of these numbers as so:

```<code>numList = [8, 10, 15, ...]
</code>```

Now, all you need is a little string formatting.

```<code>with open('/home/user/test.filter') as f:
    lines = f.readlines()

for i, l in enumerate(lines): # I've used enumerate to eliminate n but really you don't need it
    for num in numList:
        if l.startswith('-A vlan_%d' %num):
            if "-o bond1.%d" %num in l:
                f = open('vlan%d.filter_in' %num, 'a')
            else:
                f = open('vlan%d.filter_out' %num, 'a')

            f.write(l)
            f.close()
            break
</code>```

Title: Optimize the for loop in python

Body:
Good, I currently have the following code:

n = 0
with open('/home/user/test.filter') as f:

    lines = f.readlines()

    for l in lines:
        if lines[n].startswith('-A vlan_8'):
            if "-o bond1.8" in lines[n]:
                    f = open('vlan8.filter_in', 'a')
                    f.write(l)
            else:
                f = open('vlan8.filter_out', 'a')
                f.write(l)
        if lines[n].startswith('-A vlan_10'):
            if "-o bond1.10" in lines[n]:
                f = open('vlan10.filter_in', 'a')
                f.write(l)
            else:
                f = open('vlan10.filter_out', 'a')
                f.write(l)
        if lines[n].startswith('-A vlan_15'):
            if "-o bond1.15" in lines[n]:
                f = open('vlan15.filter_in', 'a')
                f.write(l)
            else:
                f = open('vlan15.filter_out', 'a')
                f.write(l)

        # [...]

        n = n + 1

I thought about optimizing it with some accumulator or list to not make the script so extensive. Any suggestions?

Body:
Sure you can. Maintain a list of these numbers as so:

numList = [8, 10, 15, ...]

Now, all you need is a little string formatting.

with open('/home/user/test.filter') as f:
    lines = f.readlines()

for i, l in enumerate(lines): # I've used enumerate to eliminate n but really you don't need it
    for num in numList:
        if l.startswith('-A vlan_%d' %num):
            if "-o bond1.%d" %num in l:
                f = open('vlan%d.filter_in' %num, 'a')
            else:
                f = open('vlan%d.filter_out' %num, 'a')

            f.write(l)
            f.close()
            break


问:
new Date() doesn't work with canvasjs & rangeBar
I tried to read some datas with AJAX json format from PHP code.

```<code>.../...
    $data[]     = array("label" => $my_label, "y" => array("new Date($yci,$mci,$dci,$hci,$ici)","new Date($yco,$mco,$dco,$hco,$ico)"));
}

return json_encode($data, JSON_NUMERIC_CHECK);
</code>```

Side JS

```<code>var chart = new CanvasJS.Chart("timeline", {
    title: {
        text: "How long an event occurred for on a given day"
    },
    axisY: {
        minimum: (new Date(2017, 5, 1, 00, 01)).getTime(),
        interval: (24 * 60 * 60 * 1000 * 7 ),
        labelFormatter: function(e){
        return CanvasJS.formatDate(e.value, "MM/DD");
        },
        gridThickness: 1
    },

    toolTip:{
        contentFormatter: function ( e ) {
        return "<strong>" + e.entries[0].dataPoint.label + "</strong></br> Start: " +  CanvasJS.formatDate(e.entries[0].dataPoint.y[0], "DD - h:mm TT") + "</br>End : " + CanvasJS.formatDate(e.entries[0].dataPoint.y[1], "DD - h:mm TT");
    }},

    data: [
    {
      type: "rangeBar",
    dataPoints: JSON.parse(json.message),
    }
    ]
});
chart.render();

}
</code>```

The issue is, unable to display the datas.
I think new date is not formated correctely.

```<code>[
{
    "label":"Room 200",
    "y":
         [
            "new Date(2017,5,06,14,20)",
            "new Date(2017,5,08,14,20)"
         ]
 },
 {
    "label":"Room 200",
    "y":
        [
            "new Date(2017,5,08,14,21)",
            "new Date(2017,5,10,14,21)"
        ]
},
{
    "label":"Room 201",
    "y":
        [
            "new Date(2017,5,11,15,59)",
            "new Date(2017,5,13,15,59)"
        ]
}
]
</code>```

Also, something is weird with new date() from canvasjs sample, at the end of each code, there's .getTime() like this : new date().getTime()

http://jsfiddle.net/canvasjs/xqgja576/

Can you help me please?

答:
You should just pass dates from back-end as UTC timestamps, so, you woldn't need any client-side conversions:

```<code>$start = new \DateTime("$yci/$mci/$dci $hci:$ici", new \DateTimeZone("UTC"));
$end = new \DateTime("$yco/$mco/$dco $hco:$ico", new \DateTimeZone("UTC"));
$data[] = array(
    "label" => $my_label,
    "y" => array(
        // don't forget for '*1000 part' to convert
        // from unix timestamp (seconds) to UTC timestamp (milliseconds)
        $start->getTimestamp() * 1000,
        $end->getTimestamp() * 1000,
     ),
);
</code>```

Also, you need to account for proper DateTime object initialization based on your code (maybe, you already have date-time objects somewhere earlier in your's code and just deconstructed them to $yci, $mci, $dci, $hci, $ici variables for convenience). You can use this man page as a reference.

Body:
I tried to read some datas with AJAX json format from PHP code.

.../...
    $data[]     = array("label" => $my_label, "y" => array("new Date($yci,$mci,$dci,$hci,$ici)","new Date($yco,$mco,$dco,$hco,$ico)"));
}

return json_encode($data, JSON_NUMERIC_CHECK);

Side JS

var chart = new CanvasJS.Chart("timeline", {
    title: {
        text: "How long an event occurred for on a given day"
    },
    axisY: {
        minimum: (new Date(2017, 5, 1, 00, 01)).getTime(),
        interval: (24 * 60 * 60 * 1000 * 7 ),
        labelFormatter: function(e){
        return CanvasJS.formatDate(e.value, "MM/DD");
        },
        gridThickness: 1
    },

    toolTip:{
        contentFormatter: function ( e ) {
        return "" + e.entries[0].dataPoint.label + "
 Start: " +  CanvasJS.formatDate(e.entries[0].dataPoint.y[0], "DD - h:mm TT") + "
End : " + CanvasJS.formatDate(e.entries[0].dataPoint.y[1], "DD - h:mm TT");
    }},

    data: [
    {
      type: "rangeBar",
    dataPoints: JSON.parse(json.message),
    }
    ]
});
chart.render();

}

The issue is, unable to display the datas.
I think new date is not formated correctely.

[
{
    "label":"Room 200",
    "y":
         [
            "new Date(2017,5,06,14,20)",
            "new Date(2017,5,08,14,20)"
         ]
 },
 {
    "label":"Room 200",
    "y":
        [
            "new Date(2017,5,08,14,21)",
            "new Date(2017,5,10,14,21)"
        ]
},
{
    "label":"Room 201",
    "y":
        [
            "new Date(2017,5,11,15,59)",
            "new Date(2017,5,13,15,59)"
        ]
}
]

Also, something is weird with new date() from canvasjs sample, at the end of each code, there's .getTime() like this : new date().getTime()

http://jsfiddle.net/canvasjs/xqgja576/

Can you help me please?

Body:
You should just pass dates from back-end as UTC timestamps, so, you woldn't need any client-side conversions:

$start = new \DateTime("$yci/$mci/$dci $hci:$ici", new \DateTimeZone("UTC"));
$end = new \DateTime("$yco/$mco/$dco $hco:$ico", new \DateTimeZone("UTC"));
$data[] = array(
    "label" => $my_label,
    "y" => array(
        // don't forget for '*1000 part' to convert
        // from unix timestamp (seconds) to UTC timestamp (milliseconds)
        $start->getTimestamp() * 1000,
        $end->getTimestamp() * 1000,
     ),
);

Also, you need to account for proper DateTime object initialization based on your code (maybe, you already have date-time objects somewhere earlier in your's code and just deconstructed them to $yci, $mci, $dci, $hci, $ici variables for convenience). You can use this man page as a reference.


问:
Initialize server on startup
I have my multi-module webapp with spring, some servlets and hibernation.
I have 4 modules:

```<code>-model
-Service
-Utils
-Web
</code>```

It works fine, but, I need to run some code only at the start of the server. Is there any way to execute code only when it runs as -> run on the server but not every time a request is made?

答:
The word "server" sometimes is used for the application itself, therefore, I would try to provide an answer for both possible meanings.

If what you mean is: "when the computer starts" (the server holding the application), then there are plenty things you may do, like initHooks or cronjobs

If you mean when your application starts, then you can run some code at the beginning of your application (in java, for example, search for the main() method or the run() method) or in your apache (if you use one) you can do something like this but instead of using the PHP script, use yours :)

Hope it helps!

Title: Initialize server on startup

Body:
I have my multi-module webapp with spring, some servlets and hibernation.
I have 4 modules:

-model
-Service
-Utils
-Web

It works fine, but, I need to run some code only at the start of the server. Is there any way to execute code only when it runs as -> run on the server but not every time a request is made?


问:
How to chop off characters after a space?
I have a variable - 2 words separated by a single space : $var = "xxxx yyyy". In perl, how do i use regular expressions to make $var = "xxxx"

Thanks,
Trinity

答:
You don't!
Okay, you could, but why?

```<code>substr $var, index($var, ' '), length $var, '';
</code>```

It's not quite a premature optimization, but more of an "avoiding the golden hammer" situation.

Body:
You don't!
Okay, you could, but why?

substr $var, index($var, ' '), length $var, '';

It's not quite a premature optimization, but more of an "avoiding the golden hammer" situation.


问:
Excel 2010 - Break Links
I have inherited an Excel 2010 file which, when I click on 'Edit Link', has two links to files I cannot access. These links cannot be updated and are no linger needed....but for the life of me I cannot delete, or break them!

I get the prompt:

'Breaking links permanently converts formulas and external references
  to their existing values. Because this cannot be undone, you may wish
  to save another copy of this file...Are you sure you want to break
  links?'

To which I most vehemently reply by clicking 'Break links'.

Yet they are still there!!!!

Any advice?

Thanks in advance

答:
You could break the links manually by finding the cells with external references and fixing their values.

To find cells with external links, do a find (ctrl-f) on all cells containing '{' (curly bracket).

Once you find a cell with an external link, highlight the cell and click F2 followed by F9 to fix the values (or Copy and Paste Values).

You could also try saving the file in the most current excel format - 'Edit Links' used to be very flakey and would never actually break the links, it has worked ok since 2013 though so perhaps the problem is in the old file format.

Hope that helps.

Title: Excel 2010 - Break Links


问:
Amazon EMR cluster matplotlib error
I'm using an AWS cluster EMR 5.3.1 with Hadoop + Spark + Hive + Zeppelin

When I use Zeppelin and type command:

```<code>%python
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
</code>```

I get error:

```<code>ImportError: Gtk3 backend requires pygobject to be installed.
</code>```

How to solve it?

答:
Before importing pyplot module you need to change matplotlib's backend to Agg

```<code>import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
</code>```

Title: Amazon EMR cluster matplotlib error

Body:
I'm using an AWS cluster EMR 5.3.1 with Hadoop + Spark + Hive + Zeppelin

When I use Zeppelin and type command:

%python
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])

I get error:

ImportError: Gtk3 backend requires pygobject to be installed.

How to solve it?

Body:
Before importing pyplot module you need to change matplotlib's backend to Agg

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])

ContentLicense: CC BY-SA 4.0


问:
How to measure progress of loading json file from axios call?
In order to measure progress, I'm thinking about doing these two things while making axios call:

get file size while making call to json file

get percentage of file downloaded out of the file size from network tab

So far I just have this where I can get the data but I need some way to get the metadata behind it (the information in the network console like file size, amount downloaded so far)

```<code>const request = axios.get('/data');

request.then((response) => {

}
</code>```

Or is there another way of measuring progress?

答:
you just need to pass in a configuration object with the onUploadProgress function:

```<code>let progress = 0;
const request = axios.post('/data', {
    onUploadProgress: function(event) {
       progress = Math.round((event.loaded * 100) / event.total);
    }
});

request.then((response) => {
    //
}
</code>```

then use the progress variable as you wish.

Note: If using a get request use onDownloadProgress as mentioned here

Body:
In order to measure progress, I'm thinking about doing these two things while making axios call:

get file size while making call to json file

get percentage of file downloaded out of the file size from network tab

So far I just have this where I can get the data but I need some way to get the metadata behind it (the information in the network console like file size, amount downloaded so far)

const request = axios.get('/data');

request.then((response) => {

}

Or is there another way of measuring progress?

Body:
you just need to pass in a configuration object with the onUploadProgress function:

let progress = 0;
const request = axios.post('/data', {
    onUploadProgress: function(event) {
       progress = Math.round((event.loaded * 100) / event.total);
    }
});

request.then((response) => {
    //
}

then use the progress variable as you wish.

Note: If using a get request use onDownloadProgress as mentioned here


问:
How to fire once each time on changing directory content with fs.watch?
Is there a way to fire only once on changing directory content with Node.js fs.watch? By changing directory content I mean adding/deleting bunch of files from it ?

In other words I expect fs.watch to fire on the first event of the first file and ignore any other events for particular changing dir content cycle.

I was able to do this only with fs.watchFile But node guys recommend to use fs.watch if possible.

Note: fs.watch() is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.

https://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener

答:
Yury Tarabanko patricianly answered this question earlier, but shortly after
deleted his answer:

You simply stop watching on the first call

```<code>const watcher = fs.watch(somePath, (ev, file) => {
  watcher.close()

  // logic goes here
  console.log(`${ev} ${file}`)
})
</code>```

With resurrecting watcher after closing it, we will have 1 shot recurrent behavior as asked in the question:

```<code>const fs = require('fs')
let dir = './watch1'

function watchOnce()
{
  const watcher = fs.watch(dir, (evt, file) => {
    watcher.close()

    // logic goes here
    console.log(Date(), evt, file)

   // resurrecting watcher after 1 sec
    setTimeout(watchOnce, 1000)
  })
}

watchOnce()
</code>```

Testing

Creating and deleting 10,000 files 5 times in a raw with 1 seconds delay in between:

```<code>$ for i in {1..5}; do touch {1..10000}; sleep 1; rm {1..10000}; sleep 1; done
</code>```

Verifying that watcher fired exactly 10 times (5 for creating 10,000 files and 5 for deleting 10,000 files):

```<code>$ node watchers.js
Wed Jun 07 2017 12:01:44 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:46 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:47 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:49 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:50 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:52 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:53 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:55 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:56 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:58 GMT+0300 (EEST) rename 1
</code>```

I will not marking my answer as accepted, since credits mostly goes to Yury for his watcher.close() idea. And maybe someone else will write more neat solution, since I am not big fun using delay in the function.

Body:
Yury Tarabanko patricianly answered this question earlier, but shortly after
deleted his answer:

You simply stop watching on the first call

const watcher = fs.watch(somePath, (ev, file) => {
  watcher.close()

  // logic goes here
  console.log(`${ev} ${file}`)
})

With resurrecting watcher after closing it, we will have 1 shot recurrent behavior as asked in the question:

const fs = require('fs')
let dir = './watch1'

function watchOnce()
{
  const watcher = fs.watch(dir, (evt, file) => {
    watcher.close()

    // logic goes here
    console.log(Date(), evt, file)

   // resurrecting watcher after 1 sec
    setTimeout(watchOnce, 1000)
  })
}

watchOnce()

Testing

Creating and deleting 10,000 files 5 times in a raw with 1 seconds delay in between:

$ for i in {1..5}; do touch {1..10000}; sleep 1; rm {1..10000}; sleep 1; done

Verifying that watcher fired exactly 10 times (5 for creating 10,000 files and 5 for deleting 10,000 files):

$ node watchers.js
Wed Jun 07 2017 12:01:44 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:46 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:47 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:49 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:50 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:52 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:53 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:55 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:56 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:58 GMT+0300 (EEST) rename 1

I will not marking my answer as accepted, since credits mostly goes to Yury for his watcher.close() idea. And maybe someone else will write more neat solution, since I am not big fun using delay in the function.


答:
There are various ways to pass information through the app. First we can use config() to set and get.

Optionally you can use session() to get and set.

You could also add variables to the request() object such as request()->global_var = 'test'

Title: Get/Set global variable in Class in Laravel

Body:
I can't understand how to  make global variable, that I can in future change its value and get it over and over again?
My controller Example:

public function getProducts()
{
    // some stuff
    $products = SQLquery;
    config(['memoProducts' => $products]);
    $value = config('memoProducts');
    dd($value)//returns what I need

}

public function setProducts()
{
    //here I try to get $products from previous function
    $value = config('memoProducts');
    dd($value)//returns null
}

What's my problem?

PS: thanks for thinking that I'm stupid af and minusing my question all day long, even though none of your answers  seem to help. Thanks a lot


问:
Angular 2+ | ng test environment variable
Problem: I have a service that handles all the errors in my app, I would like to disable the logging in the service in case I am running unit tests. ( since I am testing failures in the unit tests, my consoles gets filled with logging ).

Possible solution: I thought it would make sense to use an environment variable. Ex: a logging variable in my environment.test.ts file, however, I soon realised there is no way of running ng test with a different environment ( it defaults to development ).

Does anyone have another idea to remove logging when running unit tests?

答:
When you say "unit tests" - do you mean unit tests or are you just using a unit testing framework to do integration tests?

If you're doing unit tests and you're not specifically testing the logging/error service, then you should stub (or mock) that service in your tests.

An example. If you want to test a service that has a dependency on the logging service, that dependency should be substituted with a "dummy" service that does not log to your console window. That "dummy" service is either a stub (nothing gets recorded, and probably just returns empty/static values when called), or it can be a mock (it will record how/when/with what it was called, for you to later check in the test).

Either way, when you do a unit test, you should only hit code specifically for that unit (as small a unit as possible - a method, or sometimes several methods if the calling method calls other (perhaps private) methods on the same class). You should never be testing more than one class per unit test. You will often have several tests for one class and even several tests for one method in one class.

If you're in reality doing integration testing - I won't stop you - then you can still stub out functionality that you do not want to be run - replace the logging service in your test setup.

For all this to work - you need a somewhat good architecture. Since you're testing typescript/javascript, replacing services is easier than it would be in a strongly typed language - if your architecture is not prepared for it - more specifically if you're not using dependency injection...


问:
ElasticSearch - Query to filter and aggregate on nested object term
I have nested objects in my elastic search index of the following type

```<code> "_source": {
           "NAME": "MNQ",
           "LAST_MOD_DATE": 1373587200000,
           "ACTIVE_FL": "Y",
           "ID": "1008",
           "USER": [
              {
                 "USR_ID": 499,
                 "STATUS": "INACTV",
                 "NAME": "ABC"
              },
              {
                 "USR_ID": 53,
                 "STATUS": "ACTV",
                 "NAME": "XYZ"
              }
            ]
        }
</code>```

And I have following use cases for querying the index:

Get all active users for a particular id. Eg: I want to get users that are active for id 1008 which in this case would be user XYZ

Get all active users. Eg: I perform a match_all query and I wan to aggregate on term USER.NAME but it should only return me the names of active users.

I am having trouble performing these nested operations as search for active status will return a record which has even one of the users as active. I am unable to specifically filter out inactive users. Any help in this regard is greatly appreciated.

答:
since you are always interested in fetching the users then in that case parent-child relationship will do better than nested documents type for users. As with nested type the response will have unnecessary payload with inner_hits for elastic.

As the provide better navigation and more flexible queries for nested association then nested type.

Also in mappings you may have to select type to keyword or create a custom analyzer to retain the case as you are searching as case sensitive search.

Mappings for parent-child relationship

```<code>PUT parent_child_index
{
    "mappings": {
        "parent_document": {
            "properties": {
                "NAME": {
                    "type": "keyword"
                }
            }
        },
        "user": {
            "_parent": {
                "type": "parent_document"
            },
            "properties": {
                "USER_ID": {
                    "type": "keyword"
                },
                "STATUS": {
                    "type": "keyword"
                },
                "NAME": {
                    "type": "keyword"
                }
            }
        }
    }
}
</code>```

Index parent child documents

```<code>POST parent_child_index/parent_document
{
    "NAME": "MNQ",
    "LAST_MOD_DATE": 1373587200000,
    "ACTIVE_FL": "Y",
    "ID": "1008"
}

POST parent_child_index/user?parent=AVyBzQXmp_hWdUR22wGr
{
    "USR_ID": 53,
    "STATUS": "ACTV",
    "NAME": "XYZ"
}
</code>```

Query

```<code>POST parent_child_index/user/_search
{
    "query": {
        "bool": {
            "must": [{
                    "has_parent": {
                        "parent_type": "parent_document",
                        "query": {
                            "bool": {
                                "must": [{
                                    "term": {
                                        "ID": {
                                            "value": "1008"
                                        }
                                    }
                                }]
                            }
                        }
                    }
                },
                {
                    "term": {
                        "STATUS": {
                            "value": "ACTV"
                        }
                    }
                }
            ]
        }
    }
}

POST parent_child_index/user/_search
{
    "size": 0,
    "aggs": {
        "active_users": {
            "filter": {
                "term": {
                    "STATUS": "ACTV"
                }
            },
            "aggs": {
                "user_name": {
                    "terms": {
                        "field": "NAME",
                        "size": 10
                    }
                }
            }
        }
    }
}
</code>```

Body:
I have nested objects in my elastic search index of the following type

 "_source": {
           "NAME": "MNQ",
           "LAST_MOD_DATE": 1373587200000,
           "ACTIVE_FL": "Y",
           "ID": "1008",
           "USER": [
              {
                 "USR_ID": 499,
                 "STATUS": "INACTV",
                 "NAME": "ABC"
              },
              {
                 "USR_ID": 53,
                 "STATUS": "ACTV",
                 "NAME": "XYZ"
              }
            ]
        }

And I have following use cases for querying the index:

Get all active users for a particular id. Eg: I want to get users that are active for id 1008 which in this case would be user XYZ

Get all active users. Eg: I perform a match_all query and I wan to aggregate on term USER.NAME but it should only return me the names of active users.

I am having trouble performing these nested operations as search for active status will return a record which has even one of the users as active. I am unable to specifically filter out inactive users. Any help in this regard is greatly appreciated.

Body:
since you are always interested in fetching the users then in that case parent-child relationship will do better than nested documents type for users. As with nested type the response will have unnecessary payload with inner_hits for elastic.

As the provide better navigation and more flexible queries for nested association then nested type.

Also in mappings you may have to select type to keyword or create a custom analyzer to retain the case as you are searching as case sensitive search.

Mappings for parent-child relationship

PUT parent_child_index
{
    "mappings": {
        "parent_document": {
            "properties": {
                "NAME": {
                    "type": "keyword"
                }
            }
        },
        "user": {
            "_parent": {
                "type": "parent_document"
            },
            "properties": {
                "USER_ID": {
                    "type": "keyword"
                },
                "STATUS": {
                    "type": "keyword"
                },
                "NAME": {
                    "type": "keyword"
                }
            }
        }
    }
}

Index parent child documents

POST parent_child_index/parent_document
{
    "NAME": "MNQ",
    "LAST_MOD_DATE": 1373587200000,
    "ACTIVE_FL": "Y",
    "ID": "1008"
}

POST parent_child_index/user?parent=AVyBzQXmp_hWdUR22wGr
{
    "USR_ID": 53,
    "STATUS": "ACTV",
    "NAME": "XYZ"
}

Query

POST parent_child_index/user/_search
{
    "query": {
        "bool": {
            "must": [{
                    "has_parent": {
                        "parent_type": "parent_document",
                        "query": {
                            "bool": {
                                "must": [{
                                    "term": {
                                        "ID": {
                                            "value": "1008"
                                        }
                                    }
                                }]
                            }
                        }
                    }
                },
                {
                    "term": {
                        "STATUS": {
                            "value": "ACTV"
                        }
                    }
                }
            ]
        }
    }
}

POST parent_child_index/user/_search
{
    "size": 0,
    "aggs": {
        "active_users": {
            "filter": {
                "term": {
                    "STATUS": "ACTV"
                }
            },
            "aggs": {
                "user_name": {
                    "terms": {
                        "field": "NAME",
                        "size": 10
                    }
                }
            }
        }
    }
}


问:
how to get specific value from array of data coming from modal
I am getting value from modal which contains array as well like this:

```<code>      <?php var_dump( $myaccount);?>
</code>```

Result:

array (size=1)   0 =>
      object(stdClass)[28]

public 'daysselected' => string '["Monday","Tuesday"]'

public 'due' => string '["2017-06-12","2017-06-13"]'

I am trying to access Monday as single and similarly the date. How can i do so?

I am trying this:

```<code> if(!empty($myaccount)){
     foreach($myaccount as $it){
           echo $it->daysselected[0];//i get '[' only
      }
}
</code>```

答:
If your array format like below :

```<code>$myaccount = array('daysselected' => '"Monday","Tuesday"',
                'due' => '"2017-06-12","2017-06-13"');

foreach ($myaccount as $key => $value)
{
     $val = explode(',', $value);
     echo $val[0];
}
</code>```

Please try this may be help you.

Body:
I am getting value from modal which contains array as well like this:

      <?php var_dump( $myaccount);?>

Result:

array (size=1)   0 =>
      object(stdClass)[28]

public 'daysselected' => string '["Monday","Tuesday"]'

public 'due' => string '["2017-06-12","2017-06-13"]'

I am trying to access Monday as single and similarly the date. How can i do so?

I am trying this:

 if(!empty($myaccount)){
     foreach($myaccount as $it){
           echo $it->daysselected[0];//i get '[' only
      }
}

Body:
If your array format like below :

$myaccount = array('daysselected' => '"Monday","Tuesday"',
                'due' => '"2017-06-12","2017-06-13"');

foreach ($myaccount as $key => $value)
{
     $val = explode(',', $value);
     echo $val[0];
}

Please try this may be help you.


问:
How to stop page load in conditionals - c#
i have some ASPX page. I have to check something in the url (in the server side).
If the condition does not exist so i want to stop the page load and give some error message.

I didn't find somthing like: STOP, BREAK.

答:
Well you could always throw an Error.

```<code>throw new Exception("Please use a specific Exception");
</code>```

Or you could do a Response Redirect:

```<code>Response.Redirect("~/SomeErrorPage.aspx",true);
</code>```

The important thing to note is the true Parameter here indicating that the current Response should be ended 'immediately'.

Body:
Well you could always throw an Error.

throw new Exception("Please use a specific Exception");

Or you could do a Response Redirect:

Response.Redirect("~/SomeErrorPage.aspx",true);

The important thing to note is the true Parameter here indicating that the current Response should be ended 'immediately'.


问:
wrap content elements in specific pages differently
All of my content elements are wrapped using stdWrap.wrap.
I am looking for a solution to wrap content elements in the page which i have my ke_search added differently .

答:
I answer my own question:

You can conditionally wrap specific content elements using the following typoscript snippet.

```<code>tt_content {
       stdWrap {
          if.value = tx_kesearch_pi2
                  {
                     wrap = |
                     innerWrap >
                  }
         wrap = <div class="someotherclass">|</div>
              }
         }
</code>```

Body:
I answer my own question:

You can conditionally wrap specific content elements using the following typoscript snippet.

tt_content {
       stdWrap {
          if.value = tx_kesearch_pi2
                  {
                     wrap = |
                     innerWrap >
                  }
         wrap = <div class="someotherclass">|</div>
              }
         }


问:
Firebase can't find databaseURL when separate databases are made using process.env
I wanted to have separate databases; one for testing and one for development and production. So using process.env variables and a little library called node-env-file i put the firebase config variables as process.env variables. But i get this error:

```<code>> Uncaught Error: FIREBASE FATAL ERROR: Can't determine Firebase
> Database URL.  Be sure to include databaseURL option when calling
> firebase.intializeApp().
</code>```

In webpack.config file:

```<code>        var envFile = require('node-env-file');

        process.env.NODE_ENV = process.env.NODE_ENV || 'development';

        try {
          envFile(path.join(__dirname, 'config/' + process.env.NODE_ENV + '.env'));
        } catch (e) {

        }

    // (...)

     plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: JSON.stringify(process.env.NODE_ENV),
            API_KEY: JSON.stringify(process.env.API_KEY),
            AUTH_DOMAIN: JSON.stringify(process.env.AUTH_DOMAIN),
            DATABASE_URL: JSON.stringify(process.env.DATABASE_URL),
            STORAGE_BUCKET: JSON.stringify(process.env.STORAGE_BUCKET),
            MESSAGING_SENDER_ID: JSON.stringify(process.env.MESSAGING_SENDER_ID)

          }
        })
      ],

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

In config/test.env and in config/development.env (those 2 files are similar, but of course the data is different):

```<code>API_KEY=myapikeyhere
AUTH_DOMAIN=myauthdomainhere
DATABASE_URL=mydatabaseurlhere
STORAGE_BUCKET=mystoragebuckethere
MESSAGING_SENDER_ID=memessagingsenderidhere
</code>```

In firebase/index.js:

```<code>import firebase from 'firebase';

try {
  var config = {
    apiKey: process.env.API_KEY,
    authDomain: process.env.AUTH_DOMAIN,
    databaseURL: process.env.DATABASE_URL,
    storageBucket: process.env.STORAGE_BUCKET,
    messagingSenderId: process.env.MESSAGING_SENDER_ID
  };

  firebase.initializeApp(config);
} catch (e) {

}

export var firebaseRef = firebase.database().ref();
export default firebase;
</code>```

I updated firebase and the node-env-file libraries.

答:
In the firebase/index.js file, try

```<code>console.log("NODE_ENV",process.env.NODE_ENV)
console.log("API_KEY",process.env.APP_KEY)
</code>```

If API_KEY result is undefined,

Make sure the config/ folder is in the right location.

Remove any spaces in the .env files

If console.log shows the API_KEY, it should work.

Body:
I wanted to have separate databases; one for testing and one for development and production. So using process.env variables and a little library called node-env-file i put the firebase config variables as process.env variables. But i get this error:

> Uncaught Error: FIREBASE FATAL ERROR: Can't determine Firebase
> Database URL.  Be sure to include databaseURL option when calling
> firebase.intializeApp().

In webpack.config file:

        var envFile = require('node-env-file');

        process.env.NODE_ENV = process.env.NODE_ENV || 'development';

        try {
          envFile(path.join(__dirname, 'config/' + process.env.NODE_ENV + '.env'));
        } catch (e) {

        }

    // (...)

     plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: JSON.stringify(process.env.NODE_ENV),
            API_KEY: JSON.stringify(process.env.API_KEY),
            AUTH_DOMAIN: JSON.stringify(process.env.AUTH_DOMAIN),
            DATABASE_URL: JSON.stringify(process.env.DATABASE_URL),
            STORAGE_BUCKET: JSON.stringify(process.env.STORAGE_BUCKET),
            MESSAGING_SENDER_ID: JSON.stringify(process.env.MESSAGING_SENDER_ID)

          }
        })
      ],

// (...)

In config/test.env and in config/development.env (those 2 files are similar, but of course the data is different):

API_KEY=myapikeyhere
AUTH_DOMAIN=myauthdomainhere
DATABASE_URL=mydatabaseurlhere
STORAGE_BUCKET=mystoragebuckethere
MESSAGING_SENDER_ID=memessagingsenderidhere

In firebase/index.js:

import firebase from 'firebase';

try {
  var config = {
    apiKey: process.env.API_KEY,
    authDomain: process.env.AUTH_DOMAIN,
    databaseURL: process.env.DATABASE_URL,
    storageBucket: process.env.STORAGE_BUCKET,
    messagingSenderId: process.env.MESSAGING_SENDER_ID
  };

  firebase.initializeApp(config);
} catch (e) {

}

export var firebaseRef = firebase.database().ref();
export default firebase;

I updated firebase and the node-env-file libraries.

Body:
In the firebase/index.js file, try

console.log("NODE_ENV",process.env.NODE_ENV)
console.log("API_KEY",process.env.APP_KEY)

If API_KEY result is undefined,

Make sure the config/ folder is in the right location.

Remove any spaces in the .env files

If console.log shows the API_KEY, it should work.


问:
XML Values to retrieve in single Column with Any(,) Delimiter
My Xml file

```<code><Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Tests>
  <Test Name="Test1" TotalMarks="100">95</Test>
  <Test Name="Test2" TotalMarks="200">65</Test>
  <Test Name="Test3" TotalMarks="150">95</Test>
  <Test Name="Test4" TotalMarks="150"></Test>
    </Tests>
</Detials>
</code>```

I want to query it back to view as

```<code>TestName         |TotalMarks     |ScoreObtained**
Test1,Test2,Test3,Test4|100,200,150,150| 95,65,95,|
</code>```

I tried with this ,But not able to get the Result above as i want,I got the error as XQuery [T1.XMLData.query()]: ")" was expected.

```<code>Select

                           TestName  = x.c.query ('STUFF((SELECT
              '','' + fd.v.value(''(.)[1]'', ''varchar(100)'')
           FROM
              XMLwithOpenXML
           CROSS APPLY
              XMLData.nodes(''/Tests/Test/@Name'') AS fd(v)
           FOR XML PATH('''')
          ), 1, 1, ''''')

                        From T1 s
                        Cross Apply s.XMLData.nodes('/Detials') AS x(c)
</code>```

Help me to solve this !

Thanks,Jayendran

答:
```<code>SELECT STUFF(@x.query('for $a in (*:Detials/Tests/Test/@Name) return <a>{concat(",", $a)}</a>').value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS ListOfName
SELECT STUFF(@x.query('for $a in (*:Detials/Tests/Test/@TotalMarks) return <a>{concat(",", $a)}</a>').value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS ListOfTotalMarks
SELECT STUFF(@x.query('for $a in (*:Detials/Tests/Test) return <a>{concat(",", $a)}</a>').value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS ListOfInnerHTML
</code>```

Demo

Note: first SELECT could be formatted like this:

```<code>SELECT STUFF(
    @x.query('for $a in (*:Detials/Tests/Test/@Name)
        return <a>{concat(",", $a)}</a>')
    .value('.', 'NVARCHAR(MAX)'),
    1, 1, '') AS ListOfName
</code>```

Body:
My Xml file

<Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Tests>
  <Test Name="Test1" TotalMarks="100">95</Test>
  <Test Name="Test2" TotalMarks="200">65</Test>
  <Test Name="Test3" TotalMarks="150">95</Test>
  <Test Name="Test4" TotalMarks="150"></Test>
    </Tests>
</Detials>

I want to query it back to view as

TestName         |TotalMarks     |ScoreObtained**
Test1,Test2,Test3,Test4|100,200,150,150| 95,65,95,|

I tried with this ,But not able to get the Result above as i want,I got the error as XQuery [T1.XMLData.query()]: ")" was expected.

Select

                           TestName  = x.c.query ('STUFF((SELECT
              '','' + fd.v.value(''(.)[1]'', ''varchar(100)'')
           FROM
              XMLwithOpenXML
           CROSS APPLY
              XMLData.nodes(''/Tests/Test/@Name'') AS fd(v)
           FOR XML PATH('''')
          ), 1, 1, ''''')

                        From T1 s
                        Cross Apply s.XMLData.nodes('/Detials') AS x(c)

Help me to solve this !

Thanks,Jayendran

Body:
SELECT STUFF(@x.query('for $a in (*:Detials/Tests/Test/@Name) return <a>{concat(",", $a)}</a>').value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS ListOfName
SELECT STUFF(@x.query('for $a in (*:Detials/Tests/Test/@TotalMarks) return <a>{concat(",", $a)}</a>').value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS ListOfTotalMarks
SELECT STUFF(@x.query('for $a in (*:Detials/Tests/Test) return <a>{concat(",", $a)}</a>').value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS ListOfInnerHTML

Demo

Note: first SELECT could be formatted like this:

SELECT STUFF(
    @x.query('for $a in (*:Detials/Tests/Test/@Name)
        return <a>{concat(",", $a)}</a>')
    .value('.', 'NVARCHAR(MAX)'),
    1, 1, '') AS ListOfName


问:
Do you recommend using semicolons after every statement in JavaScript?
In many situations, JavaScript parsers will insert semicolons for you if you leave them out. My question is, do you leave them out?

If you're unfamiliar with the rules, there's a description of semicolon insertion on the Mozilla site. Here's the key point:

If the first through the nth tokens of a JavaScript program form are grammatically valid but the first through the n+1st tokens are not and there is a line break between the nth tokens and the n+1st tokens, then the parser tries to parse the program again after inserting a virtual semicolon token between the nth and the n+1st tokens.

That description may be incomplete, because it doesn't explain @Dreas's example. Anybody have a link to the complete rules, or see why the example gets a semicolon? (I tried it in JScript.NET.)

This stackoverflow question is related, but only talks about a specific scenario.

答: No, only use semicolons when they're required.</p>

OwnerDisplayName: anon

LastEditorDisplayName: anon


问:
reverse colors in colorNumeric()
I am trying to reverse the colors of a choropleth map. I am using the leaflet package and the colorNumeric() function, here is the code that generates the palette function:

```<code>pal <- colorNumeric(palette = "YlGnBu", domain = foo$p)
</code>```

I would like to do something like that:

```<code>pal <- colorNumeric(palette = "YlGnBu", domain = foo$p, trans='reverse')
</code>```

Does anyone knows how to do this?

答:
At least in leaflet 1.1.0+ colorNumeric has an optional "reverse" argument, so you can just do:</p>

```<code>pal <- colorNumeric(palette = "YlGnBu", domain = foo$p, reverse = TRUE)
</code>```

Title: reverse colors in colorNumeric()

Body:
I am trying to reverse the colors of a choropleth map. I am using the leaflet package and the colorNumeric() function, here is the code that generates the palette function:

pal <- colorNumeric(palette = "YlGnBu", domain = foo$p)

I would like to do something like that:

pal <- colorNumeric(palette = "YlGnBu", domain = foo$p, trans='reverse')

Does anyone knows how to do this?

Body:
At least in leaflet 1.1.0+ colorNumeric has an optional "reverse" argument, so you can just do:

pal <- colorNumeric(palette = "YlGnBu", domain = foo$p, reverse = TRUE)


问:
How to re-render an i frame with this.setState using ReactJS?
In a component, I am changing the state each time a button is clicked. The state is the url of the iframe. The fact is, clicking a button does change the state (when printing it out, it works), but does not re-render the iFrame with the new url.
How comes ?

```<code>import React, { Component } from 'react';

class VeryGoodConcept extends Component {

constructor(props) {
    super(props);

    this.state = { url: 'https://www.youtube.com/watch?v=g_ZKq471B2k' };
    this.changeVideo = this.changeVideo.bind(this);
}

changeVideo = (url) => {
    this.setState({ url });
    console.log(this.state.url);
}

render() {
    return (
        <div className="very-good-concept text-center">
            <h2 className="default-title">Le Very Good Concept</h2>
            <div className="row" id="video-row">
                <div className="col">
                    <button onClick={() => this.changeVideo("https://www.youtube.com/watch?v=E_tlTXHAfBs")} className="btn video-btn"><h5><i className="fa fa-handshake-o"></i>   Le caractère caritatif ?</h5></button>
                    <div className="caritative text-right">

                    </div>
                </div>
                <div className="col presentation-video">
                    <iframe src={this.state.url}></iframe>
                </div>
                <div className="col">
                    <button onClick={() => this.changeVideo("https://www.youtube.com/watch?v=FuDv-sPXNoA")} className="btn video-btn"><h5><i className="fa fa-eur"></i>   La réduction fiscale ?</h5></button>
                    <div className="red-fiscale text-left">

                    </div>
                </div>
            </div>
            <button onClick={() => this.changeVideo("https://www.youtube.com/watch?v=g_ZKq471B2k")} className="btn video-btn"><h5><i className="fa fa-users"></i>   Comment ca marche ?</h5></button>
        </div>
    );
}
}

 export default VeryGoodConcept;
</code>```

EDIT : The issue was with the IFrame library I was using, which was not compatible with react ...

答:
Just a add a key which you mutate manually whenever you want the iframe to be re-rendered. Since you want the iframe to re-render on video url change, just use that as the key:</p>

```<code><iframe key={this.state.url} src={this.state.url}></iframe>
</code>```

Body:
In a component, I am changing the state each time a button is clicked. The state is the url of the iframe. The fact is, clicking a button does change the state (when printing it out, it works), but does not re-render the iFrame with the new url.
How comes ?

import React, { Component } from 'react';

class VeryGoodConcept extends Component {

constructor(props) {
    super(props);

    this.state = { url: 'https://www.youtube.com/watch?v=g_ZKq471B2k' };
    this.changeVideo = this.changeVideo.bind(this);
}

changeVideo = (url) => {
    this.setState({ url });
    console.log(this.state.url);
}

render() {
    return (

Le Very Good Concept

                    <button onClick={() => this.changeVideo("https://www.youtube.com/watch?v=E_tlTXHAfBs")} className="btn video-btn">
   Le caractère caritatif ?
</button>

                    <button onClick={() => this.changeVideo("https://www.youtube.com/watch?v=FuDv-sPXNoA")} className="btn video-btn">
   La réduction fiscale ?
</button>

            <button onClick={() => this.changeVideo("https://www.youtube.com/watch?v=g_ZKq471B2k")} className="btn video-btn">
   Comment ca marche ?
</button>

    );
}
}

 export default VeryGoodConcept;

EDIT : The issue was with the IFrame library I was using, which was not compatible with react ...

Body:
Just a add a key which you mutate manually whenever you want the iframe to be re-rendered. Since you want the iframe to re-render on video url change, just use that as the key:

<iframe key={this.state.url} src={this.state.url}></iframe>