问:
How can I bypass this issue? SQL Error ORA-00904
I'm into troubles with this code:

```<code>SELECT
s.codcli,
s.consfin consistenza_iniziale,
s.periodo,
ss.consfin consistenza_finale,
ss.periodo,
(SELECT sum(quanti) somma_bonifici_ingresso
FROM mov WHERE tipope IN ('VE1', 'VE5', 'VE9') AND (datope BETWEEN to_date('01-01-2016', 'DD-MM-YYYY') AND to_date('30-07-2017', 'DD-MM-YYYY')) AND mov.codcli = s.codcli
GROUP BY codcli, tipope) as somma_bonifici_ingresso,
(SELECT sum(quanti) somma_bonifici_ingresso
FROM mov WHERE tipope IN ('PR1', 'PR5', 'PR9') AND (datope BETWEEN to_date('01-01-2016', 'DD-MM-YYYY') AND to_date('30-07-2017', 'DD-MM-YYYY')) AND mov.codcli = s.codcli
GROUP BY codcli, tipope) as somma_bonifici_uscita,
(ss.consfin - (somma_bonifici_ingresso - somma_bonifici_uscita) - s.consfin)/s.consfin as variazione
FROM  sre s
LEFT JOIN sre ss on s.codcli = ss.codcli
WHERE s.periodo=to_date('01-01-2016', 'DD-MM-YYYY')
AND ss.periodo=to_date('30-06-2017', 'DD-MM-YYYY')
AND s.consfin>0
ORDER BY s.codcli
</code>```

I'm getting an 00904 error not a valid identifier. I need to insert a new column arranging the columns somma_bonifici_ingresso and somma_bonifici_uscita. I have to do some calculations but it seems like it isn't able to find those columns I guess for the aliases...

答:
You cannot re-use a column alias in the same select, so use a subquery:

```<code>SELECT s.*,
       (consistenza_iniziale - (somma_bonifici_ingresso - somma_bonifici_uscita) - consistenza_iniziale) / consistenza_iniziale as variazione
FROM (SELECT s.codcli, s.consfin as consistenza_iniziale, s.periodo,
             ss.consfin as consistenza_finale, ss.periodo,
             (SELECT sum(quanti)
              FROM mov
              WHERE tipope IN ('VE1', 'VE5', 'VE9') AND
                    (datope BETWEEN DATE '2016-01-01' AND DATE '2017-07-30') AND
                    mov.codcli = s.codcli
             ) as somma_bonifici_ingresso,
             (SELECT sum(quanti)
              FROM mov
              WHERE tipope IN ('PR1', 'PR5', 'PR9') AND
                    (datope BETWEEN '2016-01-01' AND DATE '2017-07-30') AND
                    mov.codcli = s.codcli
             ) as somma_bonifici_uscita,
      FROM sre s LEFT JOIN
           sre ss
           ON s.codcli = ss.codcli
      WHERE s.periodo = DATE '2016-01-01' AND
            ss.periodo = DATE '2017-07-30' AND
            s.consfin > 0
     ) s
ORDER BY codcli;
</code>```

Other notes:

Use date constants instead of literals.  DATE for dates and TIMESTAMPS if there is a time.

Check your dates.  There are differences between the dates in the subqueries and outer WHERE.

The GROUP BY is unnecessary -- and bad -- in the subqueries.  You could end up with a "too many rows returned" error.

Body:
I'm into troubles with this code:

SELECT
s.codcli,
s.consfin consistenza_iniziale,
s.periodo,
ss.consfin consistenza_finale,
ss.periodo,
(SELECT sum(quanti) somma_bonifici_ingresso
FROM mov WHERE tipope IN ('VE1', 'VE5', 'VE9') AND (datope BETWEEN to_date('01-01-2016', 'DD-MM-YYYY') AND to_date('30-07-2017', 'DD-MM-YYYY')) AND mov.codcli = s.codcli
GROUP BY codcli, tipope) as somma_bonifici_ingresso,
(SELECT sum(quanti) somma_bonifici_ingresso
FROM mov WHERE tipope IN ('PR1', 'PR5', 'PR9') AND (datope BETWEEN to_date('01-01-2016', 'DD-MM-YYYY') AND to_date('30-07-2017', 'DD-MM-YYYY')) AND mov.codcli = s.codcli
GROUP BY codcli, tipope) as somma_bonifici_uscita,
(ss.consfin - (somma_bonifici_ingresso - somma_bonifici_uscita) - s.consfin)/s.consfin as variazione
FROM  sre s
LEFT JOIN sre ss on s.codcli = ss.codcli
WHERE s.periodo=to_date('01-01-2016', 'DD-MM-YYYY')
AND ss.periodo=to_date('30-06-2017', 'DD-MM-YYYY')
AND s.consfin>0
ORDER BY s.codcli

I'm getting an 00904 error not a valid identifier. I need to insert a new column arranging the columns somma_bonifici_ingresso and somma_bonifici_uscita. I have to do some calculations but it seems like it isn't able to find those columns I guess for the aliases...

Body:
You cannot re-use a column alias in the same select, so use a subquery:

SELECT s.*,
       (consistenza_iniziale - (somma_bonifici_ingresso - somma_bonifici_uscita) - consistenza_iniziale) / consistenza_iniziale as variazione
FROM (SELECT s.codcli, s.consfin as consistenza_iniziale, s.periodo,
             ss.consfin as consistenza_finale, ss.periodo,
             (SELECT sum(quanti)
              FROM mov
              WHERE tipope IN ('VE1', 'VE5', 'VE9') AND
                    (datope BETWEEN DATE '2016-01-01' AND DATE '2017-07-30') AND
                    mov.codcli = s.codcli
             ) as somma_bonifici_ingresso,
             (SELECT sum(quanti)
              FROM mov
              WHERE tipope IN ('PR1', 'PR5', 'PR9') AND
                    (datope BETWEEN '2016-01-01' AND DATE '2017-07-30') AND
                    mov.codcli = s.codcli
             ) as somma_bonifici_uscita,
      FROM sre s LEFT JOIN
           sre ss
           ON s.codcli = ss.codcli
      WHERE s.periodo = DATE '2016-01-01' AND
            ss.periodo = DATE '2017-07-30' AND
            s.consfin > 0
     ) s
ORDER BY codcli;

Other notes:

Use date constants instead of literals.  DATE for dates and TIMESTAMPS if there is a time.

Check your dates.  There are differences between the dates in the subqueries and outer WHERE.

The GROUP BY is unnecessary -- and bad -- in the subqueries.  You could end up with a "too many rows returned" error.


来源: stackexchange

问:
SharedPrefenrences not storing boolean value
Am trying save boolean FAVOURITE data in sharedPreferences. when phone is rotated or closed .It is not working it is taking default value. I don't know whats wrong with this code. i am unable to figure out whats the problem is can someone show me the problem with the code</p>

```<code>//Context context =this;

 String FAVOURITE = "selected";

boolean favourite = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState!=null){
        favourite = savedInstanceState.getBoolean(FAVOURITE,false);
        Toast.makeText(this,""+favourite,Toast.LENGTH_SHORT).show();

    }

    final Bundle queryBundle = new Bundle();

    movieObject=(CardsClass)getIntent().getSerializableExtra("movieObject");

    setTitle(movieObject.getmTitle());

    setContentView(R.layout.activity_details);

    final ImageView fav = (ImageView)findViewById(R.id.fav);

    fav.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (favourite == false) {

                favourite = true;

                fav.setImageResource(R.drawable.fav_on);

                Toast.makeText(DetailsActivity.this, favourite + " is added to favourites", Toast.LENGTH_SHORT).show();

                queryBundle.putBoolean(FAVOURITE,favourite);

            }

            else if(favourite){

                favourite=false;

                fav.setImageResource(R.drawable.fav_off);

                queryBundle.putBoolean(FAVOURITE,favourite);

                Toast.makeText(DetailsActivity.this, movieObject.getmTitle() + " is removed from favourites", Toast.LENGTH_SHORT).show();

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

答:
Actually, you're doing the wrong thing. You should do something like:</p>

```<code>@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean(FAVOURITE, favorite); // then you can check the favorite value in onCreate as well.
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    this.favorite = savedInstanceState.getBoolean(FAVOURITE);
    // do something here when restore.
    super.onRestoreInstanceState(savedInstanceState);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Am trying save boolean FAVOURITE data in sharedPreferences. when phone is rotated or closed .It is not working it is taking default value. I don't know whats wrong with this code. i am unable to figure out whats the problem is can someone show me the problem with the code

//Context context =this;

 String FAVOURITE = "selected";

boolean favourite = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState!=null){
        favourite = savedInstanceState.getBoolean(FAVOURITE,false);
        Toast.makeText(this,""+favourite,Toast.LENGTH_SHORT).show();

    }

    final Bundle queryBundle = new Bundle();

    movieObject=(CardsClass)getIntent().getSerializableExtra("movieObject");

    setTitle(movieObject.getmTitle());

    setContentView(R.layout.activity_details);

    final ImageView fav = (ImageView)findViewById(R.id.fav);

    fav.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (favourite == false) {

                favourite = true;

                fav.setImageResource(R.drawable.fav_on);

                Toast.makeText(DetailsActivity.this, favourite + " is added to favourites", Toast.LENGTH_SHORT).show();

                queryBundle.putBoolean(FAVOURITE,favourite);

            }

            else if(favourite){

                favourite=false;

                fav.setImageResource(R.drawable.fav_off);

                queryBundle.putBoolean(FAVOURITE,favourite);

                Toast.makeText(DetailsActivity.this, movieObject.getmTitle() + " is removed from favourites", Toast.LENGTH_SHORT).show();

            }
        }
    });

Body:
Actually, you're doing the wrong thing. You should do something like:

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean(FAVOURITE, favorite); // then you can check the favorite value in onCreate as well.
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    this.favorite = savedInstanceState.getBoolean(FAVOURITE);
    // do something here when restore.
    super.onRestoreInstanceState(savedInstanceState);
}


问:
Better formula for multiple sumproducts
I have the following data in range "A1:E3"

```<code>1   2   12  25  30
3   13  23  28  31
5   14  17  18  35
</code>```

I need to find out how many numbers falls in the range of 1 to 10 in each row. Eg. In Row 1, there are 2 numbers in the range of 1 to 10, in Row 2, there is only 1 and in Row 3, there is 1 so the total is 2+1+1=4. Similarly, I need to find how many numbers falls in the range of 11 to 20, 21 to 30 and 31 to 40 for each row. I wrote a sumproduct formula and added it twice by changing the range.

```<code>1   to  10  4
11  to  20  5
21  to  30  4
31  to  40  2
</code>```

I have the above date in Range G1:J4 where column J has the below formula which is pulled down 2 more rows.

```<code>=SUMPRODUCT((A$1:E$1>=G1)*(A$1:E$1<=I1))+SUMPRODUCT((A$2:E$2>=G1)*(A$2:E$2<=I1))+SUMPRODUCT((A$3:E$3>=G1)*(A$3:E$3<=I1))
</code>```

When my rows increases, the formula grows bigger and bigger. Can anyone suggest a better formula for this?

Thanks

答:
Since you want to find how numbers are distributed in bins of 10 (0~10,11~20,..). It is better to dedicate the header row to form bin limits and then use a formula that can be dragged to right and downwards - this SUMPRODUCT formula does the function:

```<code>=SUMPRODUCT((($A3:$D3>=1*E$1)*($A3:$D3<=E$2))*1)
</code>```

This is the result achieved.

The area between the bins and data gives the distribution of numbers.

Title: Better formula for multiple sumproducts

Body:
I have the following data in range "A1:E3"

1   2   12  25  30
3   13  23  28  31
5   14  17  18  35

I need to find out how many numbers falls in the range of 1 to 10 in each row. Eg. In Row 1, there are 2 numbers in the range of 1 to 10, in Row 2, there is only 1 and in Row 3, there is 1 so the total is 2+1+1=4. Similarly, I need to find how many numbers falls in the range of 11 to 20, 21 to 30 and 31 to 40 for each row. I wrote a sumproduct formula and added it twice by changing the range.

1   to  10  4
11  to  20  5
21  to  30  4
31  to  40  2

I have the above date in Range G1:J4 where column J has the below formula which is pulled down 2 more rows.

=SUMPRODUCT((A$1:E$1>=G1)*(A$1:E$1<=I1))+SUMPRODUCT((A$2:E$2>=G1)*(A$2:E$2<=I1))+SUMPRODUCT((A$3:E$3>=G1)*(A$3:E$3<=I1))

When my rows increases, the formula grows bigger and bigger. Can anyone suggest a better formula for this?

Thanks

Body:
Since you want to find how numbers are distributed in bins of 10 (0~10,11~20,..). It is better to dedicate the header row to form bin limits and then use a formula that can be dragged to right and downwards - this SUMPRODUCT formula does the function:

=SUMPRODUCT((($A3:$D3>=1*E$1)*($A3:$D3<=E$2))*1)

This is the result achieved.

The area between the bins and data gives the distribution of numbers.


问:
find xml element in c#
I'm am trying to find a specific element in my list of citizens but the result is always null. Thanks in advance!
Here is the code I'm trying :

```<code>string filepath = "citizens.xml";
if (!File.Exists(filepath))
{
    CitizensList list = new CitizensList();
    Serializer.SerializeObject(filepath, list);
}

CitizensList citizens = Serializer.DeSerializeObject(filepath);
Console.WriteLine("The File {0} has this data", filepath);
citizens.print();

Console.WriteLine("Chose the name of the citizen from the console");
string name = Console.ReadLine();

CitizensList search = new CitizensList();
var matching = search.Citizen.Find(p => p.FirstName==(name));
if (matching == null)
{
    Console.WriteLine("The Citizen doesn't exists.");
}
else
{
    Serializer.SerializeObject(filepath, citizens);
    citizens = Serializer.DeSerializeObject(filepath);
    search.print();
}
</code>```

Here is my code for the insert of the data in the xml file that works correctly:

```<code>Console.WriteLine("Insert the data of the citizen");
                        Console.WriteLine("Name:");
                        string nm = Console.ReadLine();
                        Console.WriteLine("Surname:");
                        string sn = Console.ReadLine();
                        Console.WriteLine("Email:");
                        string email = Console.ReadLine();
                        Console.WriteLine("Phone:");
                        string no = Console.ReadLine();
                        Citizens citizen = new Citizens();
                        if (citizens.Citizen.Count == 0)
                            citizen.Id = 1;
                        else
                            citizen.Id = Convert.ToInt32(citizens.Citizen.Last<Citizens>().Id) + 1;
                        citizen.FirstName = nm;
                        citizen.Lastname = sn;
                        citizen.Email = email;
                        citizen.PhoneNr = no;
                        citizens.Citizen.Add(citizen);

                        Serializer.SerializeObject(filepath, citizens);
                        citizens = Serializer.DeSerializeObject(filepath);
                        citizens.print();
</code>```

答:
You are searching in search, a newly created (one can only assume) empty list.

```<code>var matching = search.Citizen.Find(p => p.FirstName==(name));
</code>```

You should be searching in citizens, your list read from the file:

```<code>var matching = citizens.Citizen.Find(p => p.FirstName == name);
</code>```

Title: find xml element in c#

Body:
I'm am trying to find a specific element in my list of citizens but the result is always null. Thanks in advance!
Here is the code I'm trying :

string filepath = "citizens.xml";
if (!File.Exists(filepath))
{
    CitizensList list = new CitizensList();
    Serializer.SerializeObject(filepath, list);
}

CitizensList citizens = Serializer.DeSerializeObject(filepath);
Console.WriteLine("The File {0} has this data", filepath);
citizens.print();

Console.WriteLine("Chose the name of the citizen from the console");
string name = Console.ReadLine();

CitizensList search = new CitizensList();
var matching = search.Citizen.Find(p => p.FirstName==(name));
if (matching == null)
{
    Console.WriteLine("The Citizen doesn't exists.");
}
else
{
    Serializer.SerializeObject(filepath, citizens);
    citizens = Serializer.DeSerializeObject(filepath);
    search.print();
}

Here is my code for the insert of the data in the xml file that works correctly:

Console.WriteLine("Insert the data of the citizen");
                        Console.WriteLine("Name:");
                        string nm = Console.ReadLine();
                        Console.WriteLine("Surname:");
                        string sn = Console.ReadLine();
                        Console.WriteLine("Email:");
                        string email = Console.ReadLine();
                        Console.WriteLine("Phone:");
                        string no = Console.ReadLine();
                        Citizens citizen = new Citizens();
                        if (citizens.Citizen.Count == 0)
                            citizen.Id = 1;
                        else
                            citizen.Id = Convert.ToInt32(citizens.Citizen.Last<Citizens>().Id) + 1;
                        citizen.FirstName = nm;
                        citizen.Lastname = sn;
                        citizen.Email = email;
                        citizen.PhoneNr = no;
                        citizens.Citizen.Add(citizen);

                        Serializer.SerializeObject(filepath, citizens);
                        citizens = Serializer.DeSerializeObject(filepath);
                        citizens.print();

Body:
You are searching in search, a newly created (one can only assume) empty list.

var matching = search.Citizen.Find(p => p.FirstName==(name));

You should be searching in citizens, your list read from the file:

var matching = citizens.Citizen.Find(p => p.FirstName == name);


问:
Initializing variables with a compound literal
The following code cannot be compiled when put inside a scope/function, the compiler will produce an error stating something along the lines of initializer element is not constant. This happens on GCC as well as MSVC.

```<code>static const char * const * const list = (const char *const[]){ "abc", "def", "xyz" };
</code>```

But when the code is put outside of any function and list is initialized as a global variable with static storage duration, the code compiles fine and doesn't produce any warnings or errors. Only when list is non-static, it can be initialized within a scope/function as well.

The following quote from the cppreference docs has caught my eye:

The unnamed object to which the compound literal evaluates has static
storage duration if the compound literal occurs at file scope and
automatic storage duration if the compound literal occurs at block
scope (in which case the object's lifetime ends at the end of the
enclosing block).

Does this mean that it's safe to say that local variables with a static storage duration cannot be initialized with a compound literal?

答: Objects with static storage duration can be initialized by constant expressions. Compound literals are not constants (in fact they are lvalues). You can't initialize objects with static storage duration with compound literals (though GCC allow it as extension).</p>

ContentLicense: CC BY-SA 4.0

Body:
The following code cannot be compiled when put inside a scope/function, the compiler will produce an error stating something along the lines of initializer element is not constant. This happens on GCC as well as MSVC.

static const char * const * const list = (const char *const[]){ "abc", "def", "xyz" };

But when the code is put outside of any function and list is initialized as a global variable with static storage duration, the code compiles fine and doesn't produce any warnings or errors. Only when list is non-static, it can be initialized within a scope/function as well.

The following quote from the cppreference docs has caught my eye:

The unnamed object to which the compound literal evaluates has static
storage duration if the compound literal occurs at file scope and
automatic storage duration if the compound literal occurs at block
scope (in which case the object's lifetime ends at the end of the
enclosing block).

Does this mean that it's safe to say that local variables with a static storage duration cannot be initialized with a compound literal?


问:
How do I Parse the google result to just get the names, latitudes and longitudes in a readable format?
Please help,

I am running a query to find all the bars within a radius of a particular location. The code works to produce this result.
However, this result is too difficult to actually get any information from.
I need the geometry (lat and long) for each result and preferably the name too. I'd like this information to be automatically populated in a new dataframe, but even printing it would be perfect right now.

```<code>import googlemaps
from datetime import datetime
from googlemaps import convert

gmaps = googlemaps.Client(key='my_api_key_is_here')

query = 'bar'
location = (54.584520, -5.935232)
radius = 500

local = gmaps.places('bar', location = location, radius = radius)

#This is what I attempted
#print local['local']['results'][0]['titleNoFormatting']

print local
.... {u'results': {u'geometry': {u'location' {u'lat' 54.343434, u'lng': -5.23423423}}....} }
</code>```

When I print it, it looks like the below image. How do I access the particular lat and long for each bar?

How do I access the following:

```<code>{u'geometry': {u'location' {u'lat' 54.343434, u'lng': -5.23423423}}....}
</code>```

I'm very new to python so any extremely obvious help is appreciated!

答:
It seems that what you're getting is a JSON object. It's data that's been structured into text; that means that it's a string until you actually parse it out into a Python object.

To turn it into to a Python dictionary, try the following:

```<code>import json

my_data = json.loads(local)
print(my_data['results'])
</code>```

Body:
Please help,

I am running a query to find all the bars within a radius of a particular location. The code works to produce this result.
However, this result is too difficult to actually get any information from.
I need the geometry (lat and long) for each result and preferably the name too. I'd like this information to be automatically populated in a new dataframe, but even printing it would be perfect right now.

import googlemaps
from datetime import datetime
from googlemaps import convert

gmaps = googlemaps.Client(key='my_api_key_is_here')

query = 'bar'
location = (54.584520, -5.935232)
radius = 500

local = gmaps.places('bar', location = location, radius = radius)

#This is what I attempted
#print local['local']['results'][0]['titleNoFormatting']

print local
.... {u'results': {u'geometry': {u'location' {u'lat' 54.343434, u'lng': -5.23423423}}....} }

When I print it, it looks like the below image. How do I access the particular lat and long for each bar?

How do I access the following:

{u'geometry': {u'location' {u'lat' 54.343434, u'lng': -5.23423423}}....}

I'm very new to python so any extremely obvious help is appreciated!

Body:
It seems that what you're getting is a JSON object. It's data that's been structured into text; that means that it's a string until you actually parse it out into a Python object.

To turn it into to a Python dictionary, try the following:

import json

my_data = json.loads(local)
print(my_data['results'])


问:
WebDriver -- Selenium I can not select the dropdown option
I can not understand what the problem is, tried different ways of choosing, I give examples below...
1. You must select or click a selection.
2. Select or click the desired language.
But WebDriver does not see, does not find these elements, but in DOM they are.
You need to go to LinkedIn profile, settings, language selection.</p>

```<code>//Before select dropdown.
WebElement language = driver.findElement(By.id("setting-select-language"));
language.click();
//Select dropdown.
Select make = new Select(driver.findElement(By.name("selectLanguage")));
make.selectByValue("en_US");
//Or
Actions act = new Actions(driver);
//XPath of dropdown.
act.moveToElement(driver.findElement(By.name("selectLanguage"))).click().perform();
//XPath of option in the dropdown.
act.moveToElement(driver.findElement(By.xpath("//*[@id='setting-select-language-content']/form/div/select/option[16]"))).click().perform();
</code>```

答:
focus = true  focus = false

When you click on select it changes focus = true

Body:
I can not understand what the problem is, tried different ways of choosing, I give examples below...
1. You must select or click a selection.
2. Select or click the desired language.
But WebDriver does not see, does not find these elements, but in DOM they are.
You need to go to LinkedIn profile, settings, language selection.

//Before select dropdown.
WebElement language = driver.findElement(By.id("setting-select-language"));
language.click();
//Select dropdown.
Select make = new Select(driver.findElement(By.name("selectLanguage")));
make.selectByValue("en_US");
//Or
Actions act = new Actions(driver);
//XPath of dropdown.
act.moveToElement(driver.findElement(By.name("selectLanguage"))).click().perform();
//XPath of option in the dropdown.
act.moveToElement(driver.findElement(By.xpath("//*[@id='setting-select-language-content']/form/div/select/option[16]"))).click().perform();


问:
JS Copy command in IE11
I am using the following js code for copy the selection to clipboard.

```<code>document.execCommand('copy');
</code>```

It works fine for chrome and firefox but in IE it prompts me to allow access to copy command then i able to copy. I want this prompt should not show just copy the text. Anyway to suppress this popup?

```<code>function clip(text) {
  var copyElement = document.createElement('input');
  copyElement.setAttribute('type', 'text');
  copyElement.setAttribute('value', text);
  copyElement = document.body.appendChild(copyElement);
  copyElement.select();
  document.execCommand('copy');
  copyElement.remove();
}
</code>```

You can try this on IE
https://clipboardjs.com/

答:
var copyElement = document.createElement('input');
copyElement.setAttribute('type', 'text');
copyElement.setAttribute('value',' ' );
document.body.appendChild(copyElement);
var btn = document.createElement("button");
btn.textContent = "copy";
document.body.appendChild(btn)
btn.addEventListener('click', function(event) {
  var copyText = document.querySelector('input');
  copyText.select();
    document.execCommand('copy');
});```

Title: JS Copy command in IE11

Body:
I am using the following js code for copy the selection to clipboard.

document.execCommand('copy');

It works fine for chrome and firefox but in IE it prompts me to allow access to copy command then i able to copy. I want this prompt should not show just copy the text. Anyway to suppress this popup?

function clip(text) {
  var copyElement = document.createElement('input');
  copyElement.setAttribute('type', 'text');
  copyElement.setAttribute('value', text);
  copyElement = document.body.appendChild(copyElement);
  copyElement.select();
  document.execCommand('copy');
  copyElement.remove();
}

You can try this on IE
https://clipboardjs.com/


问:
Avoiding comma separator for the last value
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

```<code>Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");
</code>```

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)

答:
Depending on the number of iterations and how often this happens use StringBuilder instead.

```<code>StringBuilder sb = new StringBuilder();

for (Int32 i = 0; i < k.Length; i++)
{
    sb.Append(",");
    sb.Append(Convert.ToString(k.GetValue(i)));
}
if (sb.Length > 0)  {
    sb.Remove(0,1);
}
Response.Write(String.Format("({{{0}}})", sb.ToString()));
</code>```

Another way is:  However, it has to check every iteration.

```<code>StringBuilder sb = new StringBuilder();

for (Int32 i = 0; i < k.Length; i++)
{
    if (sb.Length > 0) {
      sb.Append(",");
    }
    sb.Append(Convert.ToString(k.GetValue(i)));
}
Response.Write(String.Format("({{{0}}})", sb.ToString()));
</code>```

Body:
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)

Body:
Depending on the number of iterations and how often this happens use StringBuilder instead.

StringBuilder sb = new StringBuilder();

for (Int32 i = 0; i < k.Length; i++)
{
    sb.Append(",");
    sb.Append(Convert.ToString(k.GetValue(i)));
}
if (sb.Length > 0)  {
    sb.Remove(0,1);
}
Response.Write(String.Format("({{{0}}})", sb.ToString()));

Another way is:  However, it has to check every iteration.

StringBuilder sb = new StringBuilder();

for (Int32 i = 0; i < k.Length; i++)
{
    if (sb.Length > 0) {
      sb.Append(",");
    }
    sb.Append(Convert.ToString(k.GetValue(i)));
}
Response.Write(String.Format("({{{0}}})", sb.ToString()));

ContentLicense: CC BY-SA 2.5


问:
Dynamically Swap Components at Mount Results in Uncaught Error
I'm working on a React app that at the either needs to load a View Only Form Component or a Edit Component.  In order to solve this I have the following code...

Index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import App from './app.js';

ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>), document.getElementById('main')
);
</code>```

App.Js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import  '../scss/custom.scss';
import Patient from './components/patient.js';

export default class App extends React.Component {
  render() {
    return (
      <Patient />
    );
  }
};
</code>```

Patient.js: PATIENT contains Overview and COMPPROPS contains compState being passed to OverviewWrapper

```<code>import React from 'react';
import ReactDOM from 'react-dom';
...
import OverviewWrapper from '../components/patientoverviewwrapper.js';

export default class Patient extends React.Component {
  constructor(props) {
    super(props);
    autoBind(this);

    this.state = {
      PATIENT: [],
      COMPPROPS: [],
    };
   }

componentDidMount() {

//this function gets the data that will load in either the View or Edit Form
getPatient().then((result) => {
    this.setState({PATIENT: result});
});
//this function gets the data to determine if either the edit or view form should load
loadOverviewEditPane(activity);
}
render() {
  return (
  ...
 <Box colorIndex='light-2'  direction='row' flex={false}>
                             return (
                               <OverviewWrapper overview={this.state.overview} state={this.state.compState} />
                             );
                      </Box>
</code>```

OverviewWrapper.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import autoBind from 'react-autobind';
import OverviewPane from '../components/patientoverview.js';
import OverviewEditPane from '../components/patientoverviewedit.js';

export default class OverviewWrapper extends React.Component {

constructor(props) {
    super(props);
    autoBind(this);
  }

render() {
    const ov = this.props.overview
    const type = this.props.compState

    let OverviewWrapper = null
    switch (type) {
        case "Edit" : OverviewWrapper = <OverviewEditPane overview={ov} />
        break
        default: OverviewWrapper = <OverviewPane overview={ov} />
        break
    }

    return (
        React.createElement(OverviewWrapper, this.props, null)
    )
}
}
</code>```

When I run the application I get the following error in the console.

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of OverviewWrapper.

My first time doing this and it appears that I should be using a Wrapping design which is what I'm employing here but any suggestions would be appreciated.

答:
Maybe change your approach a little bit and set component type first and later set its props:

```<code>render() {
  const ov = this.props.overview
  const type = this.props.compState

  let OverviewWrapper = null
  switch (type) {
    case "Edit":
      OverviewWrapper = OverviewEditPane
      break
    default:
      OverviewWrapper = OverviewPane
      break
  }

  return <OverviewWrapper {...this.props} overview={ov} />
}
</code>```

Working sample:

const OverviewEditPane = ({ overview }) =>

    OverviewEditPane: {overview.name}

const OverviewPane = ({ overview }) =>

    OverviewPane: {overview.name}

class App extends React.Component {
  render() {
    const Component = this.props.type === 0 ? OverviewEditPane: OverviewPane
    return (

        <Component {...this.props} />

    )
  }
}

const overview = { name: 'test' }

ReactDOM.render(

    <App type={0} overview={overview} />
    <App type={1} overview={overview} />

,
  document.getElementById('root')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div></code>```

Body:
I'm working on a React app that at the either needs to load a View Only Form Component or a Edit Component.  In order to solve this I have the following code...

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import App from './app.js';

ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>), document.getElementById('main')
);

App.Js

import React from 'react';
import ReactDOM from 'react-dom';
import  '../scss/custom.scss';
import Patient from './components/patient.js';

export default class App extends React.Component {
  render() {
    return (
      <Patient />
    );
  }
};

Patient.js: PATIENT contains Overview and COMPPROPS contains compState being passed to OverviewWrapper

import React from 'react';
import ReactDOM from 'react-dom';
...
import OverviewWrapper from '../components/patientoverviewwrapper.js';

export default class Patient extends React.Component {
  constructor(props) {
    super(props);
    autoBind(this);

    this.state = {
      PATIENT: [],
      COMPPROPS: [],
    };
   }

componentDidMount() {

//this function gets the data that will load in either the View or Edit Form
getPatient().then((result) => {
    this.setState({PATIENT: result});
});
//this function gets the data to determine if either the edit or view form should load
loadOverviewEditPane(activity);
}
render() {
  return (
  ...
 <Box colorIndex='light-2'  direction='row' flex={false}>
                             return (
                               <OverviewWrapper overview={this.state.overview} state={this.state.compState} />
                             );
                      </Box>

OverviewWrapper.js

import React from 'react';
import ReactDOM from 'react-dom';
import autoBind from 'react-autobind';
import OverviewPane from '../components/patientoverview.js';
import OverviewEditPane from '../components/patientoverviewedit.js';

export default class OverviewWrapper extends React.Component {

constructor(props) {
    super(props);
    autoBind(this);
  }

render() {
    const ov = this.props.overview
    const type = this.props.compState

    let OverviewWrapper = null
    switch (type) {
        case "Edit" : OverviewWrapper = <OverviewEditPane overview={ov} />
        break
        default: OverviewWrapper = <OverviewPane overview={ov} />
        break
    }

    return (
        React.createElement(OverviewWrapper, this.props, null)
    )
}
}

When I run the application I get the following error in the console.

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of OverviewWrapper.

My first time doing this and it appears that I should be using a Wrapping design which is what I'm employing here but any suggestions would be appreciated.

Body:
Maybe change your approach a little bit and set component type first and later set its props:

render() {
  const ov = this.props.overview
  const type = this.props.compState

  let OverviewWrapper = null
  switch (type) {
    case "Edit":
      OverviewWrapper = OverviewEditPane
      break
    default:
      OverviewWrapper = OverviewPane
      break
  }

  return <OverviewWrapper {...this.props} overview={ov} />
}

Working sample:

const OverviewEditPane = ({ overview }) =>
  <div>
    OverviewEditPane: {overview.name}
  </div>

const OverviewPane = ({ overview }) =>
  <div>
    OverviewPane: {overview.name}
  </div>

class App extends React.Component {
  render() {
    const Component = this.props.type === 0 ? OverviewEditPane: OverviewPane
    return (
      <div>
        <Component {...this.props} />
      </div>
    )
  }
}

const overview = { name: 'test' }

ReactDOM.render(
  <div>
    <App type={0} overview={overview} />
    <App type={1} overview={overview} />
  </div>,
  document.getElementById('root')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>


问:
android studio 3.0 version showing following error while adding recyclerview dependency in bulild.gradle
Error image

I recently updated my android studio to 3.0 and while i was adding dependency for recycler view in build.gradle(module.app) whereas card view is working fine.It's showing the shown error.Below is my dependency code.

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.m.listviewslow"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-v4:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

答:
Edit your build.gradle file like this</p>

```<code>allprojects {
    repositories {
        jcenter()
        google()
    }
}
</code>```

Body:
Error image

I recently updated my android studio to 3.0 and while i was adding dependency for recycler view in build.gradle(module.app) whereas card view is working fine.It's showing the shown error.Below is my dependency code.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.m.listviewslow"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-v4:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

Body:
Edit your build.gradle file like this

allprojects {
    repositories {
        jcenter()
        google()
    }
}


问:
Looking for SQL query to split the value into another column
I'm using the below SQL code in order to split the value of a column into another column but it is not working the way I expected. please find the below code along with the output which I'm getting.

Query:

```<code>select
upper(regexp_replace(regexp_substr(db_attributes,'.([^\.-]+),([^\,-]+), ([^\,-]+)[so]?[\,-]',1,1,'i',1),'[so]$','') ) AS servername, db_attributes
from table_name
</code>```

Current Output:

```<code>servername                  db_attributes
HSBC                        bsprod04.hbtr.adroot.hsbc, 49465, BSPROD04\PTRFRDS01
NULL                        hkw00100308c01.hbap.adroot.hsbc, 2433, HKW00100308C01
NULL                        ora-abacogp.de.hsbc, 1626, ABACOGP
</code>```

Desired Output:

```<code>servername                  db_attributes
BSPROD04\PTRFRDS01          bsprod04.hbtr.adroot.hsbc, 49465, BSPROD04\PTRFRDS01
HKW00100308C01              hkw00100308c01.hbap.adroot.hsbc, 2433, HKW00100308C01
ABACOGP                     ora-abacogp.de.hsbc, 1626, ABACOGP
</code>```

Regards.

答:
SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE table_name ( db_attributes ) AS
SELECT 'bsprod04.hbtr.adroot.hsbc, 49465, BSPROD04\PTRFRDS01' FROM DUAL UNION ALL
SELECT 'hkw00100308c01.hbap.adroot.hsbc, 2433, HKW00100308C01' FROM DUAL UNION ALL
SELECT 'ora-abacogp.de.hsbc, 1626, ABACOGP' FROM DUAL
</code>```

Query 1:

```<code>SELECT REGEXP_SUBSTR( db_attributes, '\S+$' ) AS servername,
       db_attributes
FROM   table_name
</code>```

Results:

```<code>|         SERVERNAME |                                         DB_ATTRIBUTES |
|--------------------|-------------------------------------------------------|
| BSPROD04\PTRFRDS01 |  bsprod04.hbtr.adroot.hsbc, 49465, BSPROD04\PTRFRDS01 |
|     HKW00100308C01 | hkw00100308c01.hbap.adroot.hsbc, 2433, HKW00100308C01 |
|            ABACOGP |                    ora-abacogp.de.hsbc, 1626, ABACOGP |
</code>```

Query 2:

```<code>SELECT SUBSTR( db_attributes, INSTR( db_attributes, ' ', -1 ) + 1 ) AS servername,
       db_attributes
FROM   table_name
</code>```

Results:

```<code>|         SERVERNAME |                                         DB_ATTRIBUTES |
|--------------------|-------------------------------------------------------|
| BSPROD04\PTRFRDS01 |  bsprod04.hbtr.adroot.hsbc, 49465, BSPROD04\PTRFRDS01 |
|     HKW00100308C01 | hkw00100308c01.hbap.adroot.hsbc, 2433, HKW00100308C01 |
|            ABACOGP |                    ora-abacogp.de.hsbc, 1626, ABACOGP |
</code>```

Body:
I'm using the below SQL code in order to split the value of a column into another column but it is not working the way I expected. please find the below code along with the output which I'm getting.

Query:

select
upper(regexp_replace(regexp_substr(db_attributes,'.([^\.-]+),([^\,-]+), ([^\,-]+)[so]?[\,-]',1,1,'i',1),'[so]$','') ) AS servername, db_attributes
from table_name

Current Output:

servername                  db_attributes
HSBC                        bsprod04.hbtr.adroot.hsbc, 49465, BSPROD04\PTRFRDS01
NULL                        hkw00100308c01.hbap.adroot.hsbc, 2433, HKW00100308C01
NULL                        ora-abacogp.de.hsbc, 1626, ABACOGP

Desired Output:

servername                  db_attributes
BSPROD04\PTRFRDS01          bsprod04.hbtr.adroot.hsbc, 49465, BSPROD04\PTRFRDS01
HKW00100308C01              hkw00100308c01.hbap.adroot.hsbc, 2433, HKW00100308C01
ABACOGP                     ora-abacogp.de.hsbc, 1626, ABACOGP

Regards.

Body:
SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE table_name ( db_attributes ) AS
SELECT 'bsprod04.hbtr.adroot.hsbc, 49465, BSPROD04\PTRFRDS01' FROM DUAL UNION ALL
SELECT 'hkw00100308c01.hbap.adroot.hsbc, 2433, HKW00100308C01' FROM DUAL UNION ALL
SELECT 'ora-abacogp.de.hsbc, 1626, ABACOGP' FROM DUAL

Query 1:

SELECT REGEXP_SUBSTR( db_attributes, '\S+$' ) AS servername,
       db_attributes
FROM   table_name

Results:

|         SERVERNAME |                                         DB_ATTRIBUTES |
|--------------------|-------------------------------------------------------|
| BSPROD04\PTRFRDS01 |  bsprod04.hbtr.adroot.hsbc, 49465, BSPROD04\PTRFRDS01 |
|     HKW00100308C01 | hkw00100308c01.hbap.adroot.hsbc, 2433, HKW00100308C01 |
|            ABACOGP |                    ora-abacogp.de.hsbc, 1626, ABACOGP |

Query 2:

SELECT SUBSTR( db_attributes, INSTR( db_attributes, ' ', -1 ) + 1 ) AS servername,
       db_attributes
FROM   table_name

Results:

|         SERVERNAME |                                         DB_ATTRIBUTES |
|--------------------|-------------------------------------------------------|
| BSPROD04\PTRFRDS01 |  bsprod04.hbtr.adroot.hsbc, 49465, BSPROD04\PTRFRDS01 |
|     HKW00100308C01 | hkw00100308c01.hbap.adroot.hsbc, 2433, HKW00100308C01 |
|            ABACOGP |                    ora-abacogp.de.hsbc, 1626, ABACOGP |


问:
HTML input tag passing placeholder as value to PHP
I'm trying to implement the 'placeholder' attribute on a new mobile web site. Running into an issue where if a user leaves the field blank (showing the placeholder) then that placeholder is submitted as the field value for PHP to receive and place in the database. Instead it should (I assume) be sending an empty value. This causes problems with server side validation - the receiving PHP script thinks a legitimate value has been submitted instead of an empty value which would throw an error back to the user.

I am hoping there is a quick fix to this issue.

Sample code below:

```<code><form action="somepage.php" method="post">

<input type="text" name="yourName" placeholder="Enter your name here">

<input type="submit">

</form>
</code>```

PHP sees:

```<code>$_POST['yourName'] = 'Enter your name here';
</code>```

instead of:

```<code>$_POST['yourName'] = '';
</code>```

The latter is what I want it to see.

Any help would be greatly appreciated!!!

* EDIT **

Here is an example form with the problem:

https://www.badgleymischka.com/mobileTest.php

Leave all fields as is (note in the source these are filled in by the placeholders, not the values). Click the "CONTINUE" button and you will see the _POST variables with the placeholder values.

答:
Just stumbled across this in my own search, so if anyone else is looking for an answer to this try this:

```<code><input type="text" name="yourName" placeholder="Enter your name here" required>
</code>```

By adding "required" to the input tag the user must fill out this field before submitting.

Body:
I'm trying to implement the 'placeholder' attribute on a new mobile web site. Running into an issue where if a user leaves the field blank (showing the placeholder) then that placeholder is submitted as the field value for PHP to receive and place in the database. Instead it should (I assume) be sending an empty value. This causes problems with server side validation - the receiving PHP script thinks a legitimate value has been submitted instead of an empty value which would throw an error back to the user.

I am hoping there is a quick fix to this issue.

Sample code below:

<form action="somepage.php" method="post">

<input type="text" name="yourName" placeholder="Enter your name here">

<input type="submit">

</form>

PHP sees:

$_POST['yourName'] = 'Enter your name here';

instead of:

$_POST['yourName'] = '';

The latter is what I want it to see.

Any help would be greatly appreciated!!!

* EDIT **

Here is an example form with the problem:

https://www.badgleymischka.com/mobileTest.php

Leave all fields as is (note in the source these are filled in by the placeholders, not the values). Click the "CONTINUE" button and you will see the _POST variables with the placeholder values.

Body:
Just stumbled across this in my own search, so if anyone else is looking for an answer to this try this:

<input type="text" name="yourName" placeholder="Enter your name here" required>

By adding "required" to the input tag the user must fill out this field before submitting.


问:
LiveSASS failed to start
I've been trying to use liveSass in Google Chrome but getting stuck</p>

```<code>LiveSASS failed to start: http://../screen.css.map
SourceMap is misaligned: color != #fff
</code>```

答:
LiveSASS experiment has been removed from DevTools

https://bugs.chromium.org/p/chromium/issues/detail?id=782935

Title: LiveSASS failed to start

Body:
I've been trying to use liveSass in Google Chrome but getting stuck

LiveSASS failed to start: http://../screen.css.map
SourceMap is misaligned: color != #fff


问:
Datatable title column ajax
I fill a datatable via ajax with the code below, but I need to rename the columns with the ajax return as well. How to do to rename the columns of the datatable with return json?</p>

```<code>var table = $('#my_table').dataTable({
    serverSide: true,
    searching: false,
    bAutoWidth:false,
    bFilter: true,
    bLengthChange: false,
    responsive: true,
    ajax: 'clientes.php',
    dataSrc: 'data',
    columns: [ {"sTitle":"#", "data":"client_id"},{"sTitle":"Name", "data":"client_name"},{"sTitle":"Contact", "data":"client"} ]
});
</code>```

答:
Resolved, thanks to @davidkonrad

```<code>   $.getJSON("clients.php, function(json) {
        var keys = Object.keys(json['data'][0]),
            columns = [];
        for (var i=0;i<keys.length;i++) {
            columns.push(
                { data: keys[i], title: keys[i] }
            );
        }
        var table = $('#my_table').DataTable({
            searching: false,
            bAutoWidth:false,
            bFilter: true,
            bLengthChange: false,
            responsive: true,
            data : json.data,
            columns : columns
        });
    });
</code>```

PHP

```<code>        $clients_sql =
        "
            SELECT
                *
            FROM
                client
        ";
    $data = array();

    $result = mysqli_query($mysqli, $clients_sql);
    while($row = $result->fetch_array(MYSQLI_ASSOC))
    {
        $id         = $row['client_id'];
        $name       = $row['client_name'];
        $phone      = $row['client_phone'];
        $data[]    = array('ID'=> $id, 'Name'=> $name, 'Phone'=> $phone);
    }

    $results['data'] = $data;
    echo json_encode($results);
</code>```

Title: Datatable title column ajax

Body:
I fill a datatable via ajax with the code below, but I need to rename the columns with the ajax return as well. How to do to rename the columns of the datatable with return json?

var table = $('#my_table').dataTable({
    serverSide: true,
    searching: false,
    bAutoWidth:false,
    bFilter: true,
    bLengthChange: false,
    responsive: true,
    ajax: 'clientes.php',
    dataSrc: 'data',
    columns: [ {"sTitle":"#", "data":"client_id"},{"sTitle":"Name", "data":"client_name"},{"sTitle":"Contact", "data":"client"} ]
});

Body:
Resolved, thanks to @davidkonrad

   $.getJSON("clients.php, function(json) {
        var keys = Object.keys(json['data'][0]),
            columns = [];
        for (var i=0;i<keys.length;i++) {
            columns.push(
                { data: keys[i], title: keys[i] }
            );
        }
        var table = $('#my_table').DataTable({
            searching: false,
            bAutoWidth:false,
            bFilter: true,
            bLengthChange: false,
            responsive: true,
            data : json.data,
            columns : columns
        });
    });

PHP

        $clients_sql =
        "
            SELECT
                *
            FROM
                client
        ";
    $data = array();

    $result = mysqli_query($mysqli, $clients_sql);
    while($row = $result->fetch_array(MYSQLI_ASSOC))
    {
        $id         = $row['client_id'];
        $name       = $row['client_name'];
        $phone      = $row['client_phone'];
        $data[]    = array('ID'=> $id, 'Name'=> $name, 'Phone'=> $phone);
    }

    $results['data'] = $data;
    echo json_encode($results);


问:
How do I set hostname in docker-compose?
In my docker-compose.yml file, I have the following. However the container does not pick up the hostname value. Any ideas?

dns:
  image: phensley/docker-dns
  hostname: affy
  domainname: affy.com
  volumes:
    - /var/run/docker.sock:/docker.sock
```

When I check the hostname in the container it does not pick up affy.

答:
I found that the hostname was not visible to other containers when using docker run. This turns out to be a known issue (perhaps more a known feature), with part of the discussion being:

We should probably add a warning to the docs about using hostname. I think it is rarely useful.

The correct way of assigning a hostname - in terms of container networking - is to define an alias like so:

```<code>services:
  some-service:
    networks:
      some-network:
        aliases:
          - alias1
          - alias2
</code>```

Unfortunately this still doesn't work with docker run. The workaround is to assign the container a name:

```<code>docker-compose run --name alias1 some-service
</code>```

And alias1 can then be pinged from the other containers.

UPDATE: As @grilix points out, you should use docker-compose run --use-aliases to make the defined aliases available.

Body:
In my docker-compose.yml file, I have the following. However the container does not pick up the hostname value. Any ideas?

dns:
  image: phensley/docker-dns
  hostname: affy
  domainname: affy.com
  volumes:
    - /var/run/docker.sock:/docker.sock

When I check the hostname in the container it does not pick up affy.

Body:
I found that the hostname was not visible to other containers when using docker run. This turns out to be a known issue (perhaps more a known feature), with part of the discussion being:

We should probably add a warning to the docs about using hostname. I think it is rarely useful.

The correct way of assigning a hostname - in terms of container networking - is to define an alias like so:

services:
  some-service:
    networks:
      some-network:
        aliases:
          - alias1
          - alias2

Unfortunately this still doesn't work with docker run. The workaround is to assign the container a name:

docker-compose run --name alias1 some-service

And alias1 can then be pinged from the other containers.

UPDATE: As @grilix points out, you should use docker-compose run --use-aliases to make the defined aliases available.


问:
Please help me learn UML by analysis and design of a simple example, and then develop based on them
I'm currently studying UML....

Actualy need a simple example that start using UML for analysis and design it and then based on them start developing it by using .net.

Do you know any downloadable tutorial package which has analysis and design documentations beside its .net code?

答:
I have been using Sparx's Enterprise Architect tool for a long time. They have a great UML 2.0 tutorial on their site: http://www.sparxsystems.com/resources/uml2_tutorial/index.html. Their tool is one of the best in the market, and it is not very expensive (I am not working at Sparx :)). You can download the trial version for 30 days. </p>

<p>For the .NET code? UML and .NET are two different things, there is no such a thing UML for .NET. </p>

Body:
I have been using Sparx's Enterprise Architect tool for a long time. They have a great UML 2.0 tutorial on their site: http://www.sparxsystems.com/resources/uml2_tutorial/index.html. Their tool is one of the best in the market, and it is not very expensive (I am not working at Sparx :)). You can download the trial version for 30 days.

For the .NET code? UML and .NET are two different things, there is no such a thing UML for .NET.


问:
Display shipping methods to frontend as in the admin panel?
In WooCommerce, I'm doing the form of adding / changing product (at the front-end). I need to display the fields for changing the cost of delivery of the installed methods as  in the admin panel.

How can I do it?

Here is my code:

```<code><form>
<!-- Various input fields -->

<?php foreach ($shipping_methods as $method) { ?>
  <lebel>
    <h3><?php echo $method ?></h3>
    <input type="number" value="<?php //hook for input - output to make changes of shipping price of this method??Which one ?>">
  </lebel>
<?php } ?>

<input type="submit" value="<?php echo $edit_action ? "Save" : "Add"; ?> Product">
</form>
</code>```

答:
As Shipping Methods are connected to a Shipping Zone, WooCommerce need to know which is the customer shipping zone. So your script will not work in a correct way until you get that information.

To get that information, customer needs to logged in or if is not logged in it should need to add a product in cart…

Now the correct code to make your script working is:

```<code>// (temporary defining $edit_action for test purpose)
// To be removed and replaced by yours
$edit_action = true;
?>
<form>
    <!-- Various input fields -->

    <?php

    // Get the active shipping methods (Customer is logged in or cart is not empty)
    $rates = WC()->session->get("shipping_for_package_0")['rates'];
    if( ! empty($rates) ){
        foreach( $rates as $rate_key => $rate ){
            $method_id = $rate->method_id; // The method ID slug
            $instance_id = $rate->instance_id;
            $rate_id = $rate_key; // The rate ID (made of: $method_id + ':' + $instance_id)
            // Or $rate_id = $rate->id;
            $label = $rate->label; // The method ID Label
            $cost = $rate->cost;
            $taxes_array = $rate->taxes;
        ?>
        <label>
            <h3><?php echo $label ?></h3>
            <input type="number" value="<?php echo number_format($cost, 2); ?>">
        </label>
        <?php
        }
    }
    ?>

    <input type="submit" value="<?php echo $edit_action ? "Save" : "Add"; ?> Product">
</form>

</code>```

Tested and works (only when the customer shipping zone is defined)…

Now if you want to get everything like in shipping backend settings, you will need to:

Get the shipping zones

For each shipping zone you will get the available Shipping methods

For each shipping method you can have shipping classes rates

So this is quite much more complicated…

Here is the way to start, but I didn't find the way to get/set cost as it's different for each shipping method type…

```<code>// Initializing variable
$zones = array();

// Rest of the World zone
$zone                                              = new \WC_Shipping_Zone(0);
$zones[$zone->get_id()]                            = $zone->get_data();
$zones[$zone->get_id()]['formatted_zone_location'] = $zone->get_formatted_location();
$zones[$zone->get_id()]['shipping_methods']        = $zone->get_shipping_methods();

// Merging shipping zones
$shipping_zones = array_merge( $zones, WC_Shipping_Zones::get_zones() );

foreach ( $shipping_zones as $shipping_zone ) {
    // Row output (for testing)
    // echo '```'; print_r($shipping_zone); echo '```';

    $zone_id = $shipping_zone['id'];

    $zone_name = $zone_id == '0' ? __('Rest of the word', 'woocommerce') : $shipping_zone['zone_name'];
    $zone_locations = $shipping_zone['zone_locations']; // (It's an array)
    $zone_location_name = $shipping_zone['formatted_zone_location'];
    $zone_shipping_methods = $shipping_zone['shipping_methods'];

    foreach ( $zone_shipping_methods as $shipping_method_obj ) {
        // Row output (for testing)
        // echo '```'; print_r($shipping_method_obj); echo '```';

        echo $shipping_method_obj->id.'<br>';
        echo $shipping_method_obj->get_instance_id().'<br>';
        echo $shipping_method_obj->get_rate_id().'<br>';
        echo $shipping_method_obj->get_method_title().'<br>'; // Generic name
        echo $shipping_method_obj->get_title().'<br>'; // Customized name
    }
}
</code>```

The class that make the Shipping cost is WC_Shipping_Rate

Other related recent answer: Display shipping cost on product page - WooCommerce

Body:
In WooCommerce, I'm doing the form of adding / changing product (at the front-end). I need to display the fields for changing the cost of delivery of the installed methods as  in the admin panel.

How can I do it?

Here is my code:

<form>

<?php foreach ($shipping_methods as $method) { ?>
  <lebel>

<?php echo $method ?>

    <input type="number" value="<?php //hook for input - output to make changes of shipping price of this method??Which one ?>">
  </lebel>
<?php } ?>

<input type="submit" value="<?php echo $edit_action ? "Save" : "Add"; ?> Product">
</form>

Body:
As Shipping Methods are connected to a Shipping Zone, WooCommerce need to know which is the customer shipping zone. So your script will not work in a correct way until you get that information.

To get that information, customer needs to logged in or if is not logged in it should need to add a product in cart…

Now the correct code to make your script working is:

// (temporary defining $edit_action for test purpose)
// To be removed and replaced by yours
$edit_action = true;
?>
<form>
    <!-- Various input fields -->

    <?php

    // Get the active shipping methods (Customer is logged in or cart is not empty)
    $rates = WC()->session->get("shipping_for_package_0")['rates'];
    if( ! empty($rates) ){
        foreach( $rates as $rate_key => $rate ){
            $method_id = $rate->method_id; // The method ID slug
            $instance_id = $rate->instance_id;
            $rate_id = $rate_key; // The rate ID (made of: $method_id + ':' + $instance_id)
            // Or $rate_id = $rate->id;
            $label = $rate->label; // The method ID Label
            $cost = $rate->cost;
            $taxes_array = $rate->taxes;
        ?>
        <label>
            <h3><?php echo $label ?></h3>
            <input type="number" value="<?php echo number_format($cost, 2); ?>">
        </label>
        <?php
        }
    }
    ?>

    <input type="submit" value="<?php echo $edit_action ? "Save" : "Add"; ?> Product">
</form>

Tested and works (only when the customer shipping zone is defined)…

Now if you want to get everything like in shipping backend settings, you will need to:

Get the shipping zones

For each shipping zone you will get the available Shipping methods

For each shipping method you can have shipping classes rates

So this is quite much more complicated…

Here is the way to start, but I didn't find the way to get/set cost as it's different for each shipping method type…

// Initializing variable
$zones = array();

// Rest of the World zone
$zone                                              = new \WC_Shipping_Zone(0);
$zones[$zone->get_id()]                            = $zone->get_data();
$zones[$zone->get_id()]['formatted_zone_location'] = $zone->get_formatted_location();
$zones[$zone->get_id()]['shipping_methods']        = $zone->get_shipping_methods();

// Merging shipping zones
$shipping_zones = array_merge( $zones, WC_Shipping_Zones::get_zones() );

foreach ( $shipping_zones as $shipping_zone ) {
    // Row output (for testing)
    // echo '<pre>'; print_r($shipping_zone); echo '</pre>';

    $zone_id = $shipping_zone['id'];

    $zone_name = $zone_id == '0' ? __('Rest of the word', 'woocommerce') : $shipping_zone['zone_name'];
    $zone_locations = $shipping_zone['zone_locations']; // (It's an array)
    $zone_location_name = $shipping_zone['formatted_zone_location'];
    $zone_shipping_methods = $shipping_zone['shipping_methods'];

    foreach ( $zone_shipping_methods as $shipping_method_obj ) {
        // Row output (for testing)
        // echo '<pre>'; print_r($shipping_method_obj); echo '</pre>';

        echo $shipping_method_obj->id.'<br>';
        echo $shipping_method_obj->get_instance_id().'<br>';
        echo $shipping_method_obj->get_rate_id().'<br>';
        echo $shipping_method_obj->get_method_title().'<br>'; // Generic name
        echo $shipping_method_obj->get_title().'<br>'; // Customized name
    }
}

The class that make the Shipping cost is WC_Shipping_Rate

Other related recent answer: Display shipping cost on product page - WooCommerce


问:
bind image uri to flatlist react-native
I'm trying to bind image uri to flatlist. But it's not. rendering ..

```<code>this.state = {
        data: [

            {
                avatar: 'require(../../resources/icons/MyAccount/rounduser.png)', text: 'Bank Accounts', val: ''
            },
            {
                avatar: 'require(../../resources/icons/MyAccount/rounduser.png)', text: 'PrePaid-Cards', val: ''
            },
            {
                avatar: 'require(../../resources/icons/MyAccount/rounduser.png)', text: 'Other Wallets', val: ''
            },
            {
                avatar: 'require(../../resources/icons/MyAccount/rounduser.png)', text: 'Help', val: ''
            },
            {
                avatar: 'require(../../resources/icons/MyAccount/rounduser.png)', text: 'About App', val: ''
            }
        ]
    }
}
</code>```

I'm using this method. to render  RenderItem for flatlist

```<code>_renderList = ({ item }) => {
    return (
        <View style={styles.listContainer}  >
            <Image style={styles.listImage}  source={item.avatar}  />
            <Text style={styles.listText} >{item.text}</Text>
            <Text style={styles.listVal} >{item.val}</Text>
            <Image style={styles.listImage} source={require('../../resources/icons/MyAccount/arrowright.png')} />
        </View>
    );

}
</code>```

It's rendering  empty space. Is there something I'm missing ?

答:
You have require inside string. It should be plain require:

avatar: require('../../resources/icons/MyAccount/rounduser.png')

Title: bind image uri to flatlist react-native

Body:
I'm trying to bind image uri to flatlist. But it's not. rendering ..

this.state = {
        data: [

            {
                avatar: 'require(../../resources/icons/MyAccount/rounduser.png)', text: 'Bank Accounts', val: ''
            },
            {
                avatar: 'require(../../resources/icons/MyAccount/rounduser.png)', text: 'PrePaid-Cards', val: ''
            },
            {
                avatar: 'require(../../resources/icons/MyAccount/rounduser.png)', text: 'Other Wallets', val: ''
            },
            {
                avatar: 'require(../../resources/icons/MyAccount/rounduser.png)', text: 'Help', val: ''
            },
            {
                avatar: 'require(../../resources/icons/MyAccount/rounduser.png)', text: 'About App', val: ''
            }
        ]
    }
}

I'm using this method. to render  RenderItem for flatlist

_renderList = ({ item }) => {
    return (
        <View style={styles.listContainer}  >
            <Image style={styles.listImage}  source={item.avatar}  />
            <Text style={styles.listText} >{item.text}</Text>
            <Text style={styles.listVal} >{item.val}</Text>
            <Image style={styles.listImage} source={require('../../resources/icons/MyAccount/arrowright.png')} />
        </View>
    );

}

It's rendering  empty space. Is there something I'm missing ?


问:
Division/RegExp conflict while tokenizing Javascript
I'm writing a simple javascript tokenizer which detects basic types: Word, Number, String, RegExp, Operator, Comment and Newline. Everything is going fine but I can't understand how to detect if the current character is RegExp delimiter or division operator. I'm not using regular expressions because they are too slow. Does anybody know the mechanism of detecting it? Thanks.</p>

答:
You can tell by what the preceding token is is in the stream. Go through each token that your lexer emits and ask whether it can reasonably be followed by a division sign or a regexp; you'll find that the two resulting sets of tokens are disjoint. For example, (, [, {, ;, and all of the binary operators can only be followed by a regexp. Likewise, ), ], }, identifiers, and string/number literals can only be followed by a division sign.

See Section 7 of the ECMAScript spec for more details.


问:
Reading property file in Spring MVC app
I'm trying to read a property file using below code, basically I'm having a Spring Boot app and I'm trying to read the below non spring bean class.The property file is in src/main/resource directory.

```<code>public class VisaProperties {

    static Properties properties;

    static {
        try {
            properties = new Properties();
            String propertiesFile = System.getProperty("ftproperties");
            if (propertiesFile == null) {
                properties.load(VisaProperties.class.getResourceAsStream("motoconfig.cybersource.properties"));
            } else {
                properties.load(new FileReader(propertiesFile));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getProperty(Property property) {
        return (String) properties.get(property.getValue());
    }
}
</code>```

and trying call the end point property using below code getting null. How can I call the property?

```<code>VisaProperties.getProperty(Property.END_POINT)
</code>```

答:
You can simplify the code as:

```<code>final Properties properties = new Properties();
try (final InputStream stream =
       this.getClass().getResourceAsStream("config.properties")) {
       properties.load(stream);
}
</code>```

Note: Use "try with resources" so that stream will be automatically
  closed when the try {} block exits.

Title: Reading property file in Spring MVC app

Body:
I'm trying to read a property file using below code, basically I'm having a Spring Boot app and I'm trying to read the below non spring bean class.The property file is in src/main/resource directory.

public class VisaProperties {

    static Properties properties;

    static {
        try {
            properties = new Properties();
            String propertiesFile = System.getProperty("ftproperties");
            if (propertiesFile == null) {
                properties.load(VisaProperties.class.getResourceAsStream("motoconfig.cybersource.properties"));
            } else {
                properties.load(new FileReader(propertiesFile));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getProperty(Property property) {
        return (String) properties.get(property.getValue());
    }
}

and trying call the end point property using below code getting null. How can I call the property?

VisaProperties.getProperty(Property.END_POINT)

Body:
You can simplify the code as:

final Properties properties = new Properties();
try (final InputStream stream =
       this.getClass().getResourceAsStream("config.properties")) {
       properties.load(stream);
}

Note: Use "try with resources" so that stream will be automatically
  closed when the try {} block exits.


问:
Is it recommended to use recursive IO actions in the tail recursive form?
Consider the two following variations:

```<code>myReadListTailRecursive :: IO [String]
myReadListTailRecursive = go []
    where
    go :: [String] -> IO [String]
    go l = do {
                 inp <- getLine;
                 if (inp == "") then
                     return l;
                 else go (inp:l);
                }

myReadListOrdinary :: IO [String]
myReadListOrdinary = do
        inp <- getLine
        if inp == "" then
            return []
        else
            do
                moreInps <- myReadListOrdinary
                return (inp:moreInps)
</code>```

In ordinary programming languages, one would know that the tail recursive variant is a better choice.

However, going through this answer, it is apparent that haskell's implementation of recursion is not similar to that of using the recursion stack repeatedly.

But because in this case the program in question involves actions, and a strict monad, I am not sure if the same reasoning applies. In fact, I think in the IO case, the tail recursive form is indeed better. I am not sure how to correctly reason about this.

EDIT: David Young pointed out that the outermost call here is to (>>=). Even in that case, does one of these styles have an advantage over the other?

答:
That’s really not how I would write it, but it’s clear enough what you’re doing.  (By the way, if you want to be able to efficiently insert arbitrary output from any function in the chain, without using monads, you might try a Data.ByteString.Builder.)

Your first implementation is very similar to a left fold, and your second very similar to a right fold or map.  (You might try actually writing them as such!)  The second one has several advantages for I/O.  One of the most important, for handling input and output, is that it can be interactive.

You’ll notice that the first builds the entire list from the outside in: in order to determine what the first element of the list is, the program needs to compute the entire structure to get to the innermost thunk, which is return l.  The program generates the entire data structure first, then starts to process it.  That’s useful when you’re reducing a list, because tail-recursive functions and strict left folds are efficient.

With the second, the outermost thunk contains the head and tail of the list, so you can grab the tail, then call the thunk to generate the second list.  This can work with infinite lists, and it can produce and return partial results.

Here’s a contrived example: a program that reads in one integer per line and prints the sums so far.

```<code>main :: IO ()
main = interact( display . compute 0 . parse . lines )
  where parse :: [String] -> [Int]
        parse [] = []
        parse (x:xs) = (read x):(parse xs)

        compute :: Int -> [Int] -> [Int]
        compute _ [] = []
        compute accum (x:xs) = let accum' = accum + x
                               in accum':(compute accum' xs)

        display = unlines . map show
</code>```

If you run this interactively, you’ll get something like:

```<code>$ 1
1
$ 2
3
$ 3
6
$ 4
10
</code>```

But you could also write compute tail-recursively, with an accumulating parameter:

```<code>main :: IO ()
main = interact( display . compute [] . parse . lines )
  where parse :: [String] -> [Int]
        parse = map read

        compute :: [Int] -> [Int] -> [Int]
        compute xs [] = reverse xs
        compute [] (y:ys) = compute [y] ys
        compute (x:xs) (y:ys) = compute (x+y:x:xs) ys

        display = unlines . map show
</code>```

This is an artificial example, but strict left folds are a common pattern. If, however, you write either compute or parse with an accumulating parameter, this is what you get when you try to run interactively, and hit EOF (control-D on Unix, control-Z on Windows) after the number 4:

```<code>$ 1
$ 2
$ 3
$ 4
1
3
6
10
</code>```

This left-folded version needs to compute the entire data structure before it can read any of it.  That can’t ever work on an infinite list (When would you reach the base case?  How would you even reverse an infinite list if you did?) and an application that can’t respond to user input until it quits is a deal-breaker.

On the other hand, the tail-recursive version can be strict in its accumulating parameter, and will run more efficiently, especially when it’s not being consumed immediately.  It doesn’t need to keep any thunks or context around other than its parameters, and it can even re-use the same stack frame.  A strict accumulating function, such as Data.List.foldl', is a great choice whenver you’re reducing a list to a value, not building an eagerly-evaluated list of output.  Functions such as sum, product or any can’t return any useful intermediate value.  They inherently have to finish the computation first, then return the final result.

Body:
Consider the two following variations:

myReadListTailRecursive :: IO [String]
myReadListTailRecursive = go []
    where
    go :: [String] -> IO [String]
    go l = do {
                 inp <- getLine;
                 if (inp == "") then
                     return l;
                 else go (inp:l);
                }

myReadListOrdinary :: IO [String]
myReadListOrdinary = do
        inp <- getLine
        if inp == "" then
            return []
        else
            do
                moreInps <- myReadListOrdinary
                return (inp:moreInps)

In ordinary programming languages, one would know that the tail recursive variant is a better choice.

However, going through this answer, it is apparent that haskell's implementation of recursion is not similar to that of using the recursion stack repeatedly.

But because in this case the program in question involves actions, and a strict monad, I am not sure if the same reasoning applies. In fact, I think in the IO case, the tail recursive form is indeed better. I am not sure how to correctly reason about this.

EDIT: David Young pointed out that the outermost call here is to (>>=). Even in that case, does one of these styles have an advantage over the other?

Body:
That’s really not how I would write it, but it’s clear enough what you’re doing.  (By the way, if you want to be able to efficiently insert arbitrary output from any function in the chain, without using monads, you might try a Data.ByteString.Builder.)

Your first implementation is very similar to a left fold, and your second very similar to a right fold or map.  (You might try actually writing them as such!)  The second one has several advantages for I/O.  One of the most important, for handling input and output, is that it can be interactive.

You’ll notice that the first builds the entire list from the outside in: in order to determine what the first element of the list is, the program needs to compute the entire structure to get to the innermost thunk, which is return l.  The program generates the entire data structure first, then starts to process it.  That’s useful when you’re reducing a list, because tail-recursive functions and strict left folds are efficient.

With the second, the outermost thunk contains the head and tail of the list, so you can grab the tail, then call the thunk to generate the second list.  This can work with infinite lists, and it can produce and return partial results.

Here’s a contrived example: a program that reads in one integer per line and prints the sums so far.

main :: IO ()
main = interact( display . compute 0 . parse . lines )
  where parse :: [String] -> [Int]
        parse [] = []
        parse (x:xs) = (read x):(parse xs)

        compute :: Int -> [Int] -> [Int]
        compute _ [] = []
        compute accum (x:xs) = let accum' = accum + x
                               in accum':(compute accum' xs)

        display = unlines . map show

If you run this interactively, you’ll get something like:

$ 1
1
$ 2
3
$ 3
6
$ 4
10

But you could also write compute tail-recursively, with an accumulating parameter:

main :: IO ()
main = interact( display . compute [] . parse . lines )
  where parse :: [String] -> [Int]
        parse = map read

        compute :: [Int] -> [Int] -> [Int]
        compute xs [] = reverse xs
        compute [] (y:ys) = compute [y] ys
        compute (x:xs) (y:ys) = compute (x+y:x:xs) ys

        display = unlines . map show

This is an artificial example, but strict left folds are a common pattern. If, however, you write either compute or parse with an accumulating parameter, this is what you get when you try to run interactively, and hit EOF (control-D on Unix, control-Z on Windows) after the number 4:

$ 1
$ 2
$ 3
$ 4
1
3
6
10

This left-folded version needs to compute the entire data structure before it can read any of it.  That can’t ever work on an infinite list (When would you reach the base case?  How would you even reverse an infinite list if you did?) and an application that can’t respond to user input until it quits is a deal-breaker.

On the other hand, the tail-recursive version can be strict in its accumulating parameter, and will run more efficiently, especially when it’s not being consumed immediately.  It doesn’t need to keep any thunks or context around other than its parameters, and it can even re-use the same stack frame.  A strict accumulating function, such as Data.List.foldl', is a great choice whenver you’re reducing a list to a value, not building an eagerly-evaluated list of output.  Functions such as sum, product or any can’t return any useful intermediate value.  They inherently have to finish the computation first, then return the final result.


问:
Grouping Rows as Dictionary in Python
I have an input file as this :

```<code>5181        zzzzzzzzzzzzzzzz
6220        aaaaaaaa
1498        bbbbbbbbb
1498        ccccccccccc
</code>```

I want to group the lines which has same id number. So it will be like this:

```<code>5181        zzzzzzzzzzzzzzzz
6220        aaaaaaaa
1498        bbbbbbbbbb
1498        ccccccccccc
</code>```

I tried to create a dictionary with 3 keys but couldnt append all values.

This is what i wrote:

```<code>for i in package_ids:
    dict2[i] = (x for x in textt if int(i) in textt is True)
</code>```

答:
Assuming that id number and line's text are separated with tab(s) \t, simple sorting:

```<code>with open('yourfile.txt', 'r') as f:
    lines = f.read().splitlines()
    result = sorted(lines, key=lambda x: x[:x.find('\t')])
    for l in result:
        print(l)
</code>```

The output:

```<code>1498        Pursuing it with eager feet,
1498        And I must follow, if I can,
1498        Until it joins some larger way
1498        The Road goes ever on and on
5181        not a penny-piece or a glass bead was given away.
5181        as well as the books, pictures were left in his possession.
6220        written in golden ink.
6220        There were many Bagginses and Boffins,
6220        of them had hardly ever been in Hobbiton before.
</code>```

Title: Grouping Rows as Dictionary in Python

Body:
I have an input file as this :

5181        zzzzzzzzzzzzzzzz
6220        aaaaaaaa
1498        bbbbbbbbb
1498        ccccccccccc

I want to group the lines which has same id number. So it will be like this:

5181        zzzzzzzzzzzzzzzz
6220        aaaaaaaa
1498        bbbbbbbbbb
1498        ccccccccccc

I tried to create a dictionary with 3 keys but couldnt append all values.

This is what i wrote:

for i in package_ids:
    dict2[i] = (x for x in textt if int(i) in textt is True)

Body:
Assuming that id number and line's text are separated with tab(s) \t, simple sorting:

with open('yourfile.txt', 'r') as f:
    lines = f.read().splitlines()
    result = sorted(lines, key=lambda x: x[:x.find('\t')])
    for l in result:
        print(l)

The output:

1498        Pursuing it with eager feet,
1498        And I must follow, if I can,
1498        Until it joins some larger way
1498        The Road goes ever on and on
5181        not a penny-piece or a glass bead was given away.
5181        as well as the books, pictures were left in his possession.
6220        written in golden ink.
6220        There were many Bagginses and Boffins,
6220        of them had hardly ever been in Hobbiton before.


问:
Webpack not rewriting asset urls (stylus)
I am trying to rewrite my assets paths from a certain path (~assets/myimage.png) to the correct directory (in my case /assets/).

I told my webpack to write all images to a folder inside public. The images are correctly written, however the url in the build css is not adjusted accordingly.

This is the rule i am using for my stylus files

```<code>use: ExtractTextPlugin.extract({
  fallback: {
    loader: require.resolve("style-loader"),
    options: {
      hmr: false
    }
  },
  use: [
    {
      loader: require.resolve("css-loader")
    },
    {
      loader: require.resolve("stylus-loader")
    }
  ]
})
</code>```

and the one i am using for the assets

```<code>{
    test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
    loader: require.resolve("url-loader"),
    options: {
      limit: 100,
      name: "static/media/[name].[hash:8].[ext]"
    }
},
</code>```

My alias that resolves to the correct directory:

```<code>assets: path.resolve(__dirname, "../public")
</code>```

and the public path is set as /assets/

```<code>publicPath: publicPath + "assets/",
</code>```

Since i use ExtractTextPlugin, the style loader can not be used. When using style loader only it works, however in my use case i need a css file as /style.css

Any ideas on this?

答:
Before passing your CSS to file-loader/url-loader, it might be necessary to resolve relative assets urls.

I never used stylus-loader, but I would try the trying approach as any other CSS preprocessor and use resolve-url-loader:

```<code>module.exports = {
  module: {
    loaders: [
      {
        test   : /\.css$/,
        loaders: ['style-loader', 'css-loader', 'resolve-url-loader']
      }, {
        test   : /\.styl$/,
        loaders: ['style-loader', 'css-loader', 'resolve-url-loader', 'stylus-loader?sourceMap']
      }
    ]
  }
};
</code>```

Body:
I am trying to rewrite my assets paths from a certain path (~assets/myimage.png) to the correct directory (in my case /assets/).

I told my webpack to write all images to a folder inside public. The images are correctly written, however the url in the build css is not adjusted accordingly.

This is the rule i am using for my stylus files

use: ExtractTextPlugin.extract({
  fallback: {
    loader: require.resolve("style-loader"),
    options: {
      hmr: false
    }
  },
  use: [
    {
      loader: require.resolve("css-loader")
    },
    {
      loader: require.resolve("stylus-loader")
    }
  ]
})

and the one i am using for the assets

{
    test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
    loader: require.resolve("url-loader"),
    options: {
      limit: 100,
      name: "static/media/[name].[hash:8].[ext]"
    }
},

My alias that resolves to the correct directory:

assets: path.resolve(__dirname, "../public")

and the public path is set as /assets/

publicPath: publicPath + "assets/",

Since i use ExtractTextPlugin, the style loader can not be used. When using style loader only it works, however in my use case i need a css file as /style.css

Any ideas on this?

Body:
Before passing your CSS to file-loader/url-loader, it might be necessary to resolve relative assets urls.

I never used stylus-loader, but I would try the trying approach as any other CSS preprocessor and use resolve-url-loader:

module.exports = {
  module: {
    loaders: [
      {
        test   : /\.css$/,
        loaders: ['style-loader', 'css-loader', 'resolve-url-loader']
      }, {
        test   : /\.styl$/,
        loaders: ['style-loader', 'css-loader', 'resolve-url-loader', 'stylus-loader?sourceMap']
      }
    ]
  }
};


答:
Assuming k is an array of strings

```<code>List<string> tokens = k.ToList<string>();
Response.Write("({" + String.join<string>(",", tokens) + "})");
</code>```

Title: Avoiding comma separator for the last value

Body:
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)

Body:
Assuming k is an array of strings

List<string> tokens = k.ToList<string>();
Response.Write("({" + String.join<string>(",", tokens) + "})");


问:
How to send multiple parameters in ajax call using post request in Yii2
I have a view in which I have a detailview and a gridview. In my grid view there are check-boxes against all the columns. The detail view contains the model id. Now the case is simple, I want to select any column from the grid view and then on click of the a link button I want to send the ajax call, which includes the value of selected column and the model id, to my controller. Below is my view

```<code><?= GridView::widget([
         'dataProvider' => $dataProvider,
          /*'filterModel' => $searchModel,*/

          'columns' => [

         ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
             return ['value' => $d['meter_id']];
         }],

         'Meter_Serial_Number',

         'Issued_To',
         'Store',
       ],
]); ?>
 <a href="<?= URL::toRoute(['ogpheader/viewsetpdf', 'id'=>$model->id])?>"  name="redirect" class="btn btn-primary" id="myid">Set PDF</a>
</code>```

Now the javascript and the ajax call

```<code><?php
$url = Url::toRoute(['/ogpheader/viewsetpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {

$('#myid').on('click',function() {

 var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

});
   // alert(strValue);
$.ajax({
     url: '$url',
     type: 'POST',
     data: {
           data: strValue,// also tired with {strValue:strValue id:id} but it did not worked for me as well
     },
     success: function(data) {
        alert(data);
     },
   });
  })
});
JS;
$this->registerJs($script, static::POS_END);
?>
</code>```

Action Controller

```<code>public function actionViewsetpdf($id)
{
    $model = $this->findModel($id);
    print_r($_POST);
    $data = "";
    if(Yii::$app->request->isAjax)
    {
        $data = json_decode($_POST['data']);
        print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();

}
</code>```

The response i always got is Array ( ) no data. I have also looked into Passing two parameters in yii2 ajax request using jquery to a controller and Yii2 extra parameter ajax in controller but both seems to be helpful in my case.

Note:

As per my understanding the id is a get and strValue is post. So I am confused in both of them. May be I am wrong.

Update 1

Image quality is not that good

The response in Xhr is

```<code>array(1) {
  ["data"]=>
   array(1) {
     ["data"]=>
     string(26) "99 , 100 , 101 , 102 , 103"
    }
 }
</code>```

Any help would be highly appreciated.

答:
Prevent the default click event   </p>

```<code>$('#myid').on('click',function(e) {
  e.preventDefault();
</code>```

Body:
I have a view in which I have a detailview and a gridview. In my grid view there are check-boxes against all the columns. The detail view contains the model id. Now the case is simple, I want to select any column from the grid view and then on click of the a link button I want to send the ajax call, which includes the value of selected column and the model id, to my controller. Below is my view

<?= GridView::widget([
         'dataProvider' => $dataProvider,
          /*'filterModel' => $searchModel,*/

          'columns' => [

         ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
             return ['value' => $d['meter_id']];
         }],

         'Meter_Serial_Number',

         'Issued_To',
         'Store',
       ],
]); ?>
 <a href="<?= URL::toRoute(['ogpheader/viewsetpdf', 'id'=>$model->id])?>"  name="redirect" class="btn btn-primary" id="myid">Set PDF

Now the javascript and the ajax call

<?php
$url = Url::toRoute(['/ogpheader/viewsetpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {

$('#myid').on('click',function() {

 var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

});
   // alert(strValue);
$.ajax({
     url: '$url',
     type: 'POST',
     data: {
           data: strValue,// also tired with {strValue:strValue id:id} but it did not worked for me as well
     },
     success: function(data) {
        alert(data);
     },
   });
  })
});
JS;
$this->registerJs($script, static::POS_END);
?>

Action Controller

public function actionViewsetpdf($id)
{
    $model = $this->findModel($id);
    print_r($_POST);
    $data = "";
    if(Yii::$app->request->isAjax)
    {
        $data = json_decode($_POST['data']);
        print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();

}

The response i always got is Array ( ) no data. I have also looked into Passing two parameters in yii2 ajax request using jquery to a controller and Yii2 extra parameter ajax in controller but both seems to be helpful in my case.

Note:

As per my understanding the id is a get and strValue is post. So I am confused in both of them. May be I am wrong.

Update 1

Image quality is not that good

The response in Xhr is

array(1) {
  ["data"]=>
   array(1) {
     ["data"]=>
     string(26) "99 , 100 , 101 , 102 , 103"
    }
 }

Any help would be highly appreciated.

Body:
Prevent the default click event

$('#myid').on('click',function(e) {
  e.preventDefault();


问:
load JS function before PHP validation
I'm trying to (echo) call a javascript function from PHP when the form is submitted. I have an error that function is not defined. I do understand that PHP is loaded before Javascript, therefore, the function is not defined in PHP call.

I could create onclick even in the HTML section but the example below is part of a bigger program and PHP script is in a separate file which is included at the top of the HTML page, the function will also receive different parameters and perform different operations when called and it will be an AJAX function. Also, I have some variables loaded as page renders and I only want to call the JS function at a certain point in the program. Moving PHP to the bottom is not elegant as I would have to add some PHP at the top some at the bottom to have all variables included.

Is there a way to include the PHP part at the top and still call an AJAX function whenever required with a range of parameters? Or even better what is the best way of doing this sort of thing? I believe echo'ing javascript through PHP is not the best practice.

```<code><?php

if (isset($_POST['a'])) {
  echo "<script type='text/javascript'>example('hello');</script>";
  echo "<script type='text/javascript'>printSome(0,0);</script>";
}

?>

<!DOCTYPE html>
<html>
<body>

<form method="post">
  <input type="text">
  <input type="submit" name="a">
</form>

</body>

<script type='text/javascript'>
  function example(variable)
  {
    window.alert(variable);
  }

  function printSome(type, quantity)
  {
   return $.ajax({
   url                   : 'http://localhost/printDoc.php',
   type                  : 'POST',
   dataType              : 'json',
   data                  : {
                              DTStype      : type,
                              DTSquantity  : quantity
                           },
   cache                 : false
});
}

</script>
</html>
</code>```

答:
Try this</p>

```<code><!DOCTYPE html>
<html>
<body>

<form method="post">
  <input type="text">
  <input type="submit" name="a">
</form>

</body>

<script type='text/javascript'>
  function example(variable)
  {
    window.alert(variable);
  }

</script>
<?php

if (isset($_POST['a'])) {
  echo "<script type='text/javascript'>example('hello');</script>";
}

?>
</html>
</code>```

Title: load JS function before PHP validation

Body:
I'm trying to (echo) call a javascript function from PHP when the form is submitted. I have an error that function is not defined. I do understand that PHP is loaded before Javascript, therefore, the function is not defined in PHP call.

I could create onclick even in the HTML section but the example below is part of a bigger program and PHP script is in a separate file which is included at the top of the HTML page, the function will also receive different parameters and perform different operations when called and it will be an AJAX function. Also, I have some variables loaded as page renders and I only want to call the JS function at a certain point in the program. Moving PHP to the bottom is not elegant as I would have to add some PHP at the top some at the bottom to have all variables included.

Is there a way to include the PHP part at the top and still call an AJAX function whenever required with a range of parameters? Or even better what is the best way of doing this sort of thing? I believe echo'ing javascript through PHP is not the best practice.

<?php

if (isset($_POST['a'])) {
  echo "";
  echo "";
}

?>

<!DOCTYPE html>

<form method="post">
  <input type="text">
  <input type="submit" name="a">
</form>

Body:
Try this

<!DOCTYPE html>
<html>
<body>

<form method="post">
  <input type="text">
  <input type="submit" name="a">
</form>

</body>

<script type='text/javascript'>
  function example(variable)
  {
    window.alert(variable);
  }

</script>
<?php

if (isset($_POST['a'])) {
  echo "<script type='text/javascript'>example('hello');</script>";
}

?>
</html>