问:
How to assign sequence number for a column with duplicated rows
I have a dataset where I want to assign sequence number to a column with duplicated rows, for example:

```<code>variable_1
   x
   x
   y
   y
   x
   x
   x
   z
   z
   z
</code>```

How do I get the result like this:

```<code>variable_1   sequence
     x          1
     y          2
     x          3
     z          4
</code>```

I tried using unique, but I would miss the sequence number for x showing up the second time.

答:
In base R </p>

```<code>v=(df$variable_1!=lag(df$variable_1))
v[is.na(v)]=T
df$sequence =cumsum(v)
df[!duplicated(df),]
variable_1 sequence
1          x        1
3          y        2
5          x        3
8          z        4
</code>```

Body:
I have a dataset where I want to assign sequence number to a column with duplicated rows, for example:

variable_1
   x
   x
   y
   y
   x
   x
   x
   z
   z
   z

How do I get the result like this:

variable_1   sequence
     x          1
     y          2
     x          3
     z          4

I tried using unique, but I would miss the sequence number for x showing up the second time.

Body:
In base R

v=(df$variable_1!=lag(df$variable_1))
v[is.na(v)]=T
df$sequence =cumsum(v)
df[!duplicated(df),]
variable_1 sequence
1          x        1
3          y        2
5          x        3
8          z        4


来源: stackexchange

问:
Puma produces error on start says its running but cannot be accessed via API
I have a Rails 4.2.6 API running Puma on production and it failed after latest push. Reverted to a previously working commit but now have an error on start up even though the process is running on the server.

```<code>[1854] Puma starting in cluster mode...
[1854] * Version 3.4.0 (ruby 2.3.3-p222), codename: Owl Bowl Brawl
[1854] * Min threads: 0, max threads: 4
[1854] * Environment: production
[1854] * Process workers: 1
[1854] * Preloading application

THE ERROR---> /home/appname/.rbenv/versions/2.3.3/bin/puma: No such file or directory -

[1854] * Listening on ssl://0.0.0.0:8080?
 key=/home/appname/appname_react/sslforfree/private.key&cert=/home/appname/appname_react/sslforfree/certificate.crt
[1854] * Daemonizing...
</code>```

The file definitely exists and appears to be fine.

/home/appname/.rbenv/versions/2.3.3/bin/puma:

```<code>~/.rbenv/versions/2.3.3/bin$ cat puma
#!/usr/bin/env ruby
#
# This file was generated by RubyGems.
#
# The application 'puma' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require 'rubygems'

version = ">= 0.a"

if ARGV.first
str = ARGV.first
str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding
if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then
  version = $1
  ARGV.shift
 end
end

load Gem.bin_path('puma', 'puma', version)
</code>```

Any help is much appreciated!

答:
This was not the actual issue. In fact this "Error" is still printing during Puma start up but not affecting the API at all.
The real issue was that when I reverted to previous commit that commit had an old password to the database and THAT was the actual issue I was having.

I found it by looking through the  puma_stdout.log  file on the production box.

```<code> nano puma_stdout.log
</code>```

Standing on my own shoelaces again.... :-)

ContentLicense: CC BY-SA 3.0

Body:
I have a Rails 4.2.6 API running Puma on production and it failed after latest push. Reverted to a previously working commit but now have an error on start up even though the process is running on the server.

[1854] Puma starting in cluster mode...
[1854] * Version 3.4.0 (ruby 2.3.3-p222), codename: Owl Bowl Brawl
[1854] * Min threads: 0, max threads: 4
[1854] * Environment: production
[1854] * Process workers: 1
[1854] * Preloading application

THE ERROR---> /home/appname/.rbenv/versions/2.3.3/bin/puma: No such file or directory -

[1854] * Listening on ssl://0.0.0.0:8080?
 key=/home/appname/appname_react/sslforfree/private.key&cert=/home/appname/appname_react/sslforfree/certificate.crt
[1854] * Daemonizing...

The file definitely exists and appears to be fine.

/home/appname/.rbenv/versions/2.3.3/bin/puma:

~/.rbenv/versions/2.3.3/bin$ cat puma
#!/usr/bin/env ruby
#
# This file was generated by RubyGems.
#
# The application 'puma' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require 'rubygems'

version = ">= 0.a"

if ARGV.first
str = ARGV.first
str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding
if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then
  version = $1
  ARGV.shift
 end
end

load Gem.bin_path('puma', 'puma', version)

Any help is much appreciated!

Body:
This was not the actual issue. In fact this "Error" is still printing during Puma start up but not affecting the API at all.
The real issue was that when I reverted to previous commit that commit had an old password to the database and THAT was the actual issue I was having.

I found it by looking through the  puma_stdout.log  file on the production box.

 nano puma_stdout.log

Standing on my own shoelaces again.... :-)


问:
Set Time.zone only for one command in Rails 5
I want to parse a string to a Time object in Rails. This string is in another timezone than the default app timezone. So now, when I parse the string I first have to store the current/default time zone, change the time zone, parse the string and change the time zone back to default. That's 4 lines of code to to one thing:

```<code>current_timezone = Time.zone
Time.zone = "Target time zone"
Time.zone.parse("Tue Nov 23 23:29:57 2010")
Time.zone = current_timezone
</code>```

Is there a way to tell Rails inside the parse command which time zone to use?

答:
Time.in_zone allows you to do this a little more idiomatically.</p>

```<code># Acting with the rails default timezone
Time.use_zone("America/New_York") do
  # Acting with the target timezone
  Time.zone.parse("Tue Nov 23 23:29:57 2010") #=> Tue, 23 Nov 2010 23:29:57 EST -05:00
end
# Acting with the rails default timezone
</code>```

Body:
I want to parse a string to a Time object in Rails. This string is in another timezone than the default app timezone. So now, when I parse the string I first have to store the current/default time zone, change the time zone, parse the string and change the time zone back to default. That's 4 lines of code to to one thing:

current_timezone = Time.zone
Time.zone = "Target time zone"
Time.zone.parse("Tue Nov 23 23:29:57 2010")
Time.zone = current_timezone

Is there a way to tell Rails inside the parse command which time zone to use?

Body:
Time.in_zone allows you to do this a little more idiomatically.

# Acting with the rails default timezone
Time.use_zone("America/New_York") do
  # Acting with the target timezone
  Time.zone.parse("Tue Nov 23 23:29:57 2010") #=> Tue, 23 Nov 2010 23:29:57 EST -05:00
end
# Acting with the rails default timezone


问:
Ad management system in PHP?
I have created a website in PHP, now I want to add ad support there. Clients request for ads at some fixed locations in the website, they provide there ad in a fixed size.

I am looking for a CMS or Script which is able to manage ads, as per the ad area in the site. It should be able to manage that if an ad needs to be run for 10 days then that ad will be displayed there for 10 days and after that it will randomly pick the ads for that particular area.

Do anyone know any such CMS which offers such kind of facility, open-source CMS will be better but if there is any paid CMS for such functionality, then that's fine.

Please help, Thanks!

答: As far as I know wordpress offers a very good ads plugins. I suggest you to check it out :)</p>

ContentLicense: CC BY-SA 2.5

Title: Ad management system in PHP?


问:
Zip not working well with custom iterator function in Scala
I am experimenting with zippers in Scala and I am having difficulties getting custom iterator functions to work with them.

I have the following sample code:

```<code>Iterator
  .continually("s")
  .zip((1 to 5).iterator)
  .takeWhile {
    case ("s", 2) => println("two"); true
    case ("s", i) => println(i); true
  }
  .foreach { f: (String, Int) =>
    println(f)
  }
</code>```

When I run it, it prints out the results I am expecting:

```<code>1
(s,1)
two
(s,2)
3
(s,3)
4
(s,4)
5
(s,5)
</code>```

However, when I swap the takeWhile with my custom takeDoWhile (it includes the last failing result), I get something that is not expected:

```<code>1
(s,1)
1
(s,1)
1
(s,1)
1
(s,1)
1
(s,1)
1
(s,1)
...
(goes on forever)
</code>```

Here is the code for the takeDoWhile:

```<code>implicit final class InclusiveIterator[A](it: => Iterator[A]){
  @inline def takeDoWhile(predicate: A => Boolean): Iterator[A] = new AbstractIterator[A] {
    private var continue: Boolean = true

    def hasNext: Boolean = it.hasNext && continue

    def next(): A = {
      if(continue){
        val result: A = it.next()
        if (!predicate(result)) continue = false
        result // Give the result even if the predicate fails, but only once.
      }else{
        empty.next()
      }
    }
  }
}
</code>```

The weird thing is my takeDoWhile works perfectly fine as long as there is no zipper involved.

答:
This is caused you are using by name parameter: it: => Iterator[A] for InclusiveIterator, and since by name parameter will eval in every time it used.

Since it in takeDoWhile method it will reeval in any place it used, so it.next will not change the it iterator's offset.

there is an example to explain by name parameter for eval:

```<code>  def foo(name: => String): Unit = {
    println(name)
    println(name)
    println(name)
  }
  foo({println("start"); "end"})
  >start
  >end
  >start
  >end
  >start
  >end
</code>```

In the above example, the name by name parameter will eval 3 times in println(name).

So for your usage, you should not use the by name parameter, use by value parameter directly.

Body:
I am experimenting with zippers in Scala and I am having difficulties getting custom iterator functions to work with them.

I have the following sample code:

Iterator
  .continually("s")
  .zip((1 to 5).iterator)
  .takeWhile {
    case ("s", 2) => println("two"); true
    case ("s", i) => println(i); true
  }
  .foreach { f: (String, Int) =>
    println(f)
  }

When I run it, it prints out the results I am expecting:

1
(s,1)
two
(s,2)
3
(s,3)
4
(s,4)
5
(s,5)

However, when I swap the takeWhile with my custom takeDoWhile (it includes the last failing result), I get something that is not expected:

1
(s,1)
1
(s,1)
1
(s,1)
1
(s,1)
1
(s,1)
1
(s,1)
...
(goes on forever)

Here is the code for the takeDoWhile:

implicit final class InclusiveIterator[A](it: => Iterator[A]){
  @inline def takeDoWhile(predicate: A => Boolean): Iterator[A] = new AbstractIterator[A] {
    private var continue: Boolean = true

    def hasNext: Boolean = it.hasNext && continue

    def next(): A = {
      if(continue){
        val result: A = it.next()
        if (!predicate(result)) continue = false
        result // Give the result even if the predicate fails, but only once.
      }else{
        empty.next()
      }
    }
  }
}

The weird thing is my takeDoWhile works perfectly fine as long as there is no zipper involved.

Body:
This is caused you are using by name parameter: it: => Iterator[A] for InclusiveIterator, and since by name parameter will eval in every time it used.

Since it in takeDoWhile method it will reeval in any place it used, so it.next will not change the it iterator's offset.

there is an example to explain by name parameter for eval:

  def foo(name: => String): Unit = {
    println(name)
    println(name)
    println(name)
  }
  foo({println("start"); "end"})
  >start
  >end
  >start
  >end
  >start
  >end

In the above example, the name by name parameter will eval 3 times in println(name).

So for your usage, you should not use the by name parameter, use by value parameter directly.


问:
Why Isn't time variable changing?

function getTime() {
      const d = new Date();
      const secs = d.getSeconds();
      const mins = d.getMinutes();
      const hours = d.getHours();

      return {
        'hours': hours,
        'mins': mins,
        'secs': secs
      }
    }

    let time = getTime();

    setInterval(getTime, 1000);
    setInterval(() => {
      console.log(`${time.hours}:${time.mins}:${time.secs}`);
    }, 1000);```

The time displayed doesn't change. It just continually runs, outputting the same time instead of showing a change each second...

答:
time variable is declared only once, when script loads and stays in that state. Move it inside the interval to keep it updated.

function getTime() {
  const d = new Date();
  const secs = d.getSeconds();
  const mins = d.getMinutes();
  const hours = d.getHours();

  return {
    'hours': hours,
    'mins': mins,
    'secs': secs
  }
}

setInterval(() => {
  const time = getTime();
  console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);```

Title: Why Isn't time variable changing?

Body:
function getTime() {
      const d = new Date();
      const secs = d.getSeconds();
      const mins = d.getMinutes();
      const hours = d.getHours();

      return {
        'hours': hours,
        'mins': mins,
        'secs': secs
      }
    }

    let time = getTime();

    setInterval(getTime, 1000);
    setInterval(() => {
      console.log(`${time.hours}:${time.mins}:${time.secs}`);
    }, 1000);

The time displayed doesn't change. It just continually runs, outputting the same time instead of showing a change each second...


问:
Faster Way to Filter?
I have an array of type "Option".

The class Optioncontains an element optionDetail.

The class optionDetail contains elements of detailTraits, which is an [String] with each string being called the detailTraitName.

So my structure of getting the detailTraits looks like Option -> optionDetail -> detailTraitswhich would return me [String], or Option -> optionDetail -> detailTraits -> detailTraitName, which would return me just one String

I would like to match up the detailTraits array with another array, named selectedDetails, which is an [String] and find the elements in which all of the selectedDetails are contained inside of the detailTraits. I then want to return all of the Option in which this situation is true.

For example, if my selectedDetails array contains ["A", "B"], and I have one detailTraits array that has ["A","C"] and one that has ["A"] and one that has ["A", "B", "C"], I just want to return the option which had detailTraits of ["A", "B", "C"]

My current code looks like the following:

newOptions = option.filter({ $0.optionDetail?.detailTraits.filter({ selectedDetails.contains($0.detailTraitName ?? "") }).count == selectedDetails.count })

Is there a better way to do this? This algorithm seems pretty inefficient since It's probably in the order of magnitude of N^3, but I can't think of a better way to look through an array of arrays and match it to another array.

Thank you!

答:
You can optimise this by first filtering by comparing count on selectedDetails and detailTraits, and then comparing actual values. This way options set would be reduced to only those detailTraits having exact same count. For example you would only need to compare the string values with array containing exact 3 items (if selectedDetails is ["A", "B", "C"]), completely avoiding one iteration in loop.

Hope this helps

Title: Faster Way to Filter?


答:
You are only setting the value of time once, to the value of getTime() at that moment.

If you want the value to change, you have to set the value again every iteration.

```<code>setInterval(() => {
    var time = getTime();
    console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);
</code>```

Title: Why Isn't time variable changing?

Body:
You are only setting the value of time once, to the value of getTime() at that moment.

If you want the value to change, you have to set the value again every iteration.

setInterval(() => {
    var time = getTime();
    console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);


问:
Changing background color with Radio Buttons Android
I am attempting to change the background of a tab of my application by selecting a Radio Button from a RadioGroup, however I am not sure how to go about this.

So far I have
Favs.java:

```<code>import android.app.Activity;
import android.os.Bundle;

public class Favs extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.favs);
  }
}
</code>```

which points to this .xml file -> favs.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="fill_parent"
              android:orientation="vertical"
           xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_height="fill_parent">
   <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="What is your favorite color?"
            android:padding="3dip"/>
   <RadioGroup android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:orientation="vertical">
       <RadioButton android:id="@+id/radio_red"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Red"
                    android:onClick="onClick" />
       <RadioButton android:id="@+id/radio_yellow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Yellow" />
    </RadioGroup>
</LinearLayout>
</code>```

I understand that the android:onClick="onClick" needs to be there however I have no idea what to do after this.

答:
hi use below code for changing the background according to radio button selection

main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="fill_parent"
              android:orientation="vertical"
              android:id="@+id/LinearLayout"
           xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_height="fill_parent">
   <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="What is your favorite color?"
            android:padding="3dip"/>
   <RadioGroup android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:id="@+id/Group1"
               android:orientation="vertical">
       <RadioButton android:id="@+id/radio_red"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Red"
                    />
       <RadioButton android:id="@+id/radio_yellow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Yellow" />
    </RadioGroup>
</LinearLayout>
</code>```

Activity

```<code>public class Change extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final LinearLayout ll=(LinearLayout) findViewById(R.id.LinearLayout);

        final RadioButton radio_red = (RadioButton) findViewById(R.id.radio_red);
        final RadioButton radio_yellow = (RadioButton) findViewById(R.id.radio_yellow);
        radio_red.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                ll.setBackgroundColor(Color.RED);

            }
        });

 radio_yellow.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                ll.setBackgroundColor(Color.YELLOW);

            }
        });

    }
}
</code>```

Body:
I am attempting to change the background of a tab of my application by selecting a Radio Button from a RadioGroup, however I am not sure how to go about this.

So far I have
Favs.java:

import android.app.Activity;
import android.os.Bundle;

public class Favs extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.favs);
  }
}

which points to this .xml file -> favs.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="fill_parent"
              android:orientation="vertical"
           xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_height="fill_parent">
   <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="What is your favorite color?"
            android:padding="3dip"/>
   <RadioGroup android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:orientation="vertical">
       <RadioButton android:id="@+id/radio_red"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Red"
                    android:onClick="onClick" />
       <RadioButton android:id="@+id/radio_yellow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Yellow" />
    </RadioGroup>
</LinearLayout>

I understand that the android:onClick="onClick" needs to be there however I have no idea what to do after this.

Body:
hi use below code for changing the background according to radio button selection

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="fill_parent"
              android:orientation="vertical"
              android:id="@+id/LinearLayout"
           xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_height="fill_parent">
   <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="What is your favorite color?"
            android:padding="3dip"/>
   <RadioGroup android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:id="@+id/Group1"
               android:orientation="vertical">
       <RadioButton android:id="@+id/radio_red"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Red"
                    />
       <RadioButton android:id="@+id/radio_yellow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Yellow" />
    </RadioGroup>
</LinearLayout>

Activity

public class Change extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final LinearLayout ll=(LinearLayout) findViewById(R.id.LinearLayout);

        final RadioButton radio_red = (RadioButton) findViewById(R.id.radio_red);
        final RadioButton radio_yellow = (RadioButton) findViewById(R.id.radio_yellow);
        radio_red.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                ll.setBackgroundColor(Color.RED);

            }
        });

 radio_yellow.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                ll.setBackgroundColor(Color.YELLOW);

            }
        });

    }
}


答:
Time is not changing because you are using variable which are not getting updated.
Here are two problems

const time = getTime();//its called once  and time values are const
  will never change again

setInterval(getTime, 1000);//here function is getting executed but
  return value is never used and never assigned to time variable which
  is printed.

function getTime() {
  const d = new Date();
  const secs = d.getSeconds();
  const mins = d.getMinutes();
  const hours = d.getHours();

  return {
    'hours': hours,
    'mins': mins,
    'secs': secs
  }
}

//const time = getTime();//its called once and time values are const will never change again

//setInterval(getTime, 1000);//here function is getting executed but return value is never used and never assigned to time variable which is printed.
setInterval(() => {
  var time=getTime();
  //getTime
  console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);```

Title: Why Isn't time variable changing?


问:
Java - moving first letter of string to the end, and determining if word is the same when spelled backwards
I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.

e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.

Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.

Thank you in advance for any help.

Jack

This is what I've got so far, but I don't think it works properly.

```<code>public class WordPlay {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String word;
        String palindrome = "";
        String quit = "quit";

        do {
            System.out.print("Enter a word: ");
            word = scanner.nextLine().toUpperCase();

            int length = word.length();

            for (int i = length - 1; i >= 0; i--) {
                palindrome = palindrome + word.charAt(i);
            }

            if (word.equals(palindrome)) {
                System.out.println("Is the word + palindrome + " same as " + word + "?", true);
            } else {
                System.out.println(false);
            }
        } while (!word.equals(quit));
        System.out.println("Good Bye");
        scanner.close();

    }

}
</code>```

答:
I have tried to code it. See if it helps
    import java.util.Scanner;</p>

```<code>class StringCheck
{
 public static void main(String[] args)
 {
   Scanner sc = new Scanner(System.in);
   String str = new String();
   String tempstr = new String();
   System.out.println("Enter your String ");
   str = sc.next();
   int len = str.length();
//putting first character of str at last of tempstr
for (int i = 1 ; i<len; i++)
{
  tempstr += str.charAt(i);
}
tempstr += str.charAt(0);
//reversing tempstr
char[] tempchar = tempstr.toCharArray();
int j = len-1;
char temp;
for ( int i = 0; i<len/2 ; i++)
{
  if(i<j)
  {
    temp = tempchar[i];
    tempchar[i] = tempchar[j];
    tempchar[j]= temp;
    j--;
  }
  else
  break;
 }
 //reversing completed
 tempstr = new String(tempchar);
 //  System.out.println("the reversed string is "+tempstr);
    if(str.compareTo(tempstr)==0)
   {
     System.out.println("true");
   }
    else
   {
     System.out.println("false");
   }
 }
}
</code>```

Body:
I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.

e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.

Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.

Thank you in advance for any help.

Jack

This is what I've got so far, but I don't think it works properly.

public class WordPlay {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String word;
        String palindrome = "";
        String quit = "quit";

        do {
            System.out.print("Enter a word: ");
            word = scanner.nextLine().toUpperCase();

            int length = word.length();

            for (int i = length - 1; i >= 0; i--) {
                palindrome = palindrome + word.charAt(i);
            }

            if (word.equals(palindrome)) {
                System.out.println("Is the word + palindrome + " same as " + word + "?", true);
            } else {
                System.out.println(false);
            }
        } while (!word.equals(quit));
        System.out.println("Good Bye");
        scanner.close();

    }

}

Body:
I have tried to code it. See if it helps
    import java.util.Scanner;

class StringCheck
{
 public static void main(String[] args)
 {
   Scanner sc = new Scanner(System.in);
   String str = new String();
   String tempstr = new String();
   System.out.println("Enter your String ");
   str = sc.next();
   int len = str.length();
//putting first character of str at last of tempstr
for (int i = 1 ; i<len; i++)
{
  tempstr += str.charAt(i);
}
tempstr += str.charAt(0);
//reversing tempstr
char[] tempchar = tempstr.toCharArray();
int j = len-1;
char temp;
for ( int i = 0; i<len/2 ; i++)
{
  if(i<j)
  {
    temp = tempchar[i];
    tempchar[i] = tempchar[j];
    tempchar[j]= temp;
    j--;
  }
  else
  break;
 }
 //reversing completed
 tempstr = new String(tempchar);
 //  System.out.println("the reversed string is "+tempstr);
    if(str.compareTo(tempstr)==0)
   {
     System.out.println("true");
   }
    else
   {
     System.out.println("false");
   }
 }
}


问:
Pandas: ValueError: cannot convert float NaN to integer
I get ValueError: cannot convert float NaN to integer for following:

```<code>df = pandas.read_csv('zoom11.csv')
df[['x']] = df[['x']].astype(int)
</code>```

The "x" is a column in the csv file, I cannot spot any float NaN in the file, and I don't understand the error or why I am getting it.

When I read the column as String, then it has values like -1,0,1,...2000, all look very nice int numbers to me.

When I read the column as float, then this can be loaded. Then it shows values as -1.0,0.0 etc, still there are no any NaN-s

I tried with error_bad_lines = False and dtype parameter in read_csv to no avail. It just cancels loading with same exception.

The file is not small (10+ M rows), so cannot inspect it manually, when I extract a small header part, then there is no error, but it happens with full file. So it is something in the file, but cannot detect what.

Logically the csv should not have missing values, but even if there is some garbage then I would be ok to skip the rows. Or at least identify them, but I do not see way to scan through file and report conversion errors.

Update: Using the hints in comments/answers I got my data clean with this:

```<code># x contained NaN
df = df[~df['x'].isnull()]

# Y contained some other garbage, so null check was not enough
df = df[df['y'].str.isnumeric()]

# final conversion now worked
df[['x']] = df[['x']].astype(int)
df[['y']] = df[['y']].astype(int)
</code>```

答:
For identifying NaN values use boolean indexing:

```<code>print(df[df['x'].isnull()])
</code>```

Then for removing all non-numeric values use to_numeric with parameter errors='coerce' - to replace non-numeric values to NaNs:

```<code>df['x'] = pd.to_numeric(df['x'], errors='coerce')
</code>```

And for remove all rows with NaNs in column x use dropna:

```<code>df = df.dropna(subset=['x'])
</code>```

Last convert values to ints:

```<code>df['x'] = df['x'].astype(int)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I get ValueError: cannot convert float NaN to integer for following:

df = pandas.read_csv('zoom11.csv')
df[['x']] = df[['x']].astype(int)

The "x" is a column in the csv file, I cannot spot any float NaN in the file, and I don't understand the error or why I am getting it.

When I read the column as String, then it has values like -1,0,1,...2000, all look very nice int numbers to me.

When I read the column as float, then this can be loaded. Then it shows values as -1.0,0.0 etc, still there are no any NaN-s

I tried with error_bad_lines = False and dtype parameter in read_csv to no avail. It just cancels loading with same exception.

The file is not small (10+ M rows), so cannot inspect it manually, when I extract a small header part, then there is no error, but it happens with full file. So it is something in the file, but cannot detect what.

Logically the csv should not have missing values, but even if there is some garbage then I would be ok to skip the rows. Or at least identify them, but I do not see way to scan through file and report conversion errors.

Update: Using the hints in comments/answers I got my data clean with this:

# x contained NaN
df = df[~df['x'].isnull()]

# Y contained some other garbage, so null check was not enough
df = df[df['y'].str.isnumeric()]

# final conversion now worked
df[['x']] = df[['x']].astype(int)
df[['y']] = df[['y']].astype(int)

Body:
For identifying NaN values use boolean indexing:

print(df[df['x'].isnull()])

Then for removing all non-numeric values use to_numeric with parameter errors='coerce' - to replace non-numeric values to NaNs:

df['x'] = pd.to_numeric(df['x'], errors='coerce')

And for remove all rows with NaNs in column x use dropna:

df = df.dropna(subset=['x'])

Last convert values to ints:

df['x'] = df['x'].astype(int)


问:
Precompiled Web App still uses "Temporary ASP.NET Files" folder
OK, I'm totally confused.  I need to update an old ASP.NET Web Application but I'm totally unfamiliar with Visual Studio...

The updated web app uses some DLLs which are compiled as part of the solution and placed in the web app 'Bin' folder.  Two of these DLLs require other files in the same folder.

My problem is that, even though I publish the web app (locally for now) with the option "Precompile during publishing", at run time these DLLs are copied to the "Temporary ASP.NET Files" folder without their supporting files.

Is there a way to have ASP.NET use the DLLs in the 'Bin' folder without copying them somewhere else?  Or is there a way to 'attach' the supporting files to the DLLs so that they get copied as well?

And no, I have no idea what I'm doing at this point...

I found this unanswered question that is essentially the same thing (answers talk about properties I don't have).

答:
We ended up adding an appSettings key/value to web.config that the DLL use to find the required files.

```<code><configuration>
  ...
  <appSettings>
    <add key="sExeFolder" value="C:\Project\Support_Files"/>
  </appSettings>
  ...
</configuration>
</code>```

Body:
We ended up adding an appSettings key/value to web.config that the DLL use to find the required files.

<configuration>
  ...
  <appSettings>
    <add key="sExeFolder" value="C:\Project\Support_Files"/>
  </appSettings>
  ...
</configuration>


问:
Sending image through mail from the external storage
I am not able to attach an image to the mail from external storage.
I tried to use this line.

Uri image = Uri.parse("/storage/emulated/0/Pictures/park.jpg");

In this case mail is showing a message like can't attach empty file.

After that i am trying to execute the following code. It is showing some crash report. I have gone through some previously asked questions on this. Still i am not able to find out the perfect answer.

Here is the code that i am using...

```<code> Uri image = FileProvider.getUriForFile(this, "com.example.chint.asyntaskexample", new File("/storage/emulated/0/Pictures/", "park.jpg"));

    //Context
    //Package
    //File path (/storage/emulated/0/Pictures/park.jpg)

    Intent i = new Intent(Intent.ACTION_SEND);
    i.putExtra(Intent.EXTRA_STREAM, image);
    i.setType("image*//*");

    Intent chooser = Intent.createChooser(i, "Send Image");
    if (i.resolveActivity(getPackageManager()) != null)
        startActivity(chooser);
    else
        Toast.makeText(this, "Nothing", Toast.LENGTH_SHORT).show();
</code>```

I am getting a crash when i clicked on the share button.
Here is the logcat...

```<code>com.example.chint.asyntaskexample E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.chint.asyntaskexample, PID: 7157
                                                                             java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                                at android.view.View.performClick(View.java:6256)
                                                                                at android.view.View$PerformClick.run(View.java:24697)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                              Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:6256)
                                                                                at android.view.View$PerformClick.run(View.java:24697)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
                                                                                at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
                                                                                at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
                                                                                at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
                                                                                at com.example.chint.asyntaskexample.MainActivity.sendImage(MainActivity.java:105)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:6256)
                                                                                at android.view.View$PerformClick.run(View.java:24697)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

Please help me..

Thanks in advance.

答:
Here is the answer what i came up with...</p>

```<code>String filePath = "/storage/emulated/0/Pictures/park.jpg";

            Bitmap screenShot = BitmapFactory.decodeFile(filePath);
            File pic = new File(filePath);
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(pic);
                screenShot.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Uri uri = Uri.fromFile(pic);

            Intent sendIntent = new Intent(Intent.ACTION_SEND);
            sendIntent.setType("message/rfc822");
            sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
            Intent chooser = Intent.createChooser(sendIntent, "Send Image");

            if(sendIntent.resolveActivity(getPackageManager()) != null)
                startActivity(chooser);
            else
                Toast.makeText(ScreenShortAlertDialogue.this, "No Available Applications to send the image", Toast.LENGTH_LONG).show();
</code>```

Body:
I am not able to attach an image to the mail from external storage.
I tried to use this line.

Uri image = Uri.parse("/storage/emulated/0/Pictures/park.jpg");

In this case mail is showing a message like can't attach empty file.

After that i am trying to execute the following code. It is showing some crash report. I have gone through some previously asked questions on this. Still i am not able to find out the perfect answer.

Here is the code that i am using...

 Uri image = FileProvider.getUriForFile(this, "com.example.chint.asyntaskexample", new File("/storage/emulated/0/Pictures/", "park.jpg"));

    //Context
    //Package
    //File path (/storage/emulated/0/Pictures/park.jpg)

    Intent i = new Intent(Intent.ACTION_SEND);
    i.putExtra(Intent.EXTRA_STREAM, image);
    i.setType("image*//*");

    Intent chooser = Intent.createChooser(i, "Send Image");
    if (i.resolveActivity(getPackageManager()) != null)
        startActivity(chooser);
    else
        Toast.makeText(this, "Nothing", Toast.LENGTH_SHORT).show();

I am getting a crash when i clicked on the share button.
Here is the logcat...

com.example.chint.asyntaskexample E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.chint.asyntaskexample, PID: 7157
                                                                             java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                                at android.view.View.performClick(View.java:6256)
                                                                                at android.view.View$PerformClick.run(View.java:24697)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                              Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:6256)
                                                                                at android.view.View$PerformClick.run(View.java:24697)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
                                                                                at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
                                                                                at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
                                                                                at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
                                                                                at com.example.chint.asyntaskexample.MainActivity.sendImage(MainActivity.java:105)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:6256)
                                                                                at android.view.View$PerformClick.run(View.java:24697)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Please help me..

Thanks in advance.

Body:
Here is the answer what i came up with...

String filePath = "/storage/emulated/0/Pictures/park.jpg";

            Bitmap screenShot = BitmapFactory.decodeFile(filePath);
            File pic = new File(filePath);
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(pic);
                screenShot.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Uri uri = Uri.fromFile(pic);

            Intent sendIntent = new Intent(Intent.ACTION_SEND);
            sendIntent.setType("message/rfc822");
            sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
            Intent chooser = Intent.createChooser(sendIntent, "Send Image");

            if(sendIntent.resolveActivity(getPackageManager()) != null)
                startActivity(chooser);
            else
                Toast.makeText(ScreenShortAlertDialogue.this, "No Available Applications to send the image", Toast.LENGTH_LONG).show();


问:
Breadcrumbs: Abbreviated but still accessible

Above you se a typical breadcrumb.
Sometimes there are to many steps in that breadcrumb, so we have to shorten it by replacing some of the steps in the middle and display three dots instead

When a user clicks on the three dots, the entire breadcrumb is visible.

How would you handle the accessibility issues here?

We would like to show all the steps to our screen reader users so those users can tab trough the entire breadcrumb whiteout ever knowing about those dots.

All other users will only be able to see those tree dots.

We can accomplish this in a few ways:

Use display:none but this will hide the hidden content for all users, including screen readers

We can use the class.sr-only (since we're using Bootstrap) or something similar on those hidden links so only users with screen readers will se the hidden parts of the breadcrumb. This will work, but it will remove the hidden parts breadcrumbs from the tab order.

We can stick to #2 above and add taborder="0" to those hidden links in the breadcrumb, but then we also have to add taborder="0" to every single interaktive  element on the entire site and that is NOT an option. :-)

Are there any other ways to include the hidden links in the tab order?

(Sure, one can discuss the UX aspect of abbreviating a breadcrumb, but that's perhaps another topic.)

答:
(Sure, one can discuss the UX aspect of abbreviating a breadcrumb another topic.)

This is perfectly the topic.

Blind person are normal people who like simple things. If you think your breadcrumb is too long, give them the same functionalities :

```<code> <button aria-label="view full breadcrumb">...</button>
</code>```

Breadcrumbs have not been invented for blind people. They are part of one technique in a WCAG AAA guideline which implies that : it's not mandatory, and that it concerns everybody.

If you include hidden links in the tab and speech order, you are sure that your website won't be accessible.

A near-blind person using a screenreader in support of his eyes won't be able to view a link on the screen while it's announced by the screenreader.

A person using a keyboard only system will focus an invisible link which will remove the predictability of the focus order.

Note that for 2/ and 3/ the sr-only does not remove the elements from the tabindex, so this will work as you would expect

Body:
(Sure, one can discuss the UX aspect of abbreviating a breadcrumb another topic.)

This is perfectly the topic.

Blind person are normal people who like simple things. If you think your breadcrumb is too long, give them the same functionalities :

 <button aria-label="view full breadcrumb">...</button>

Breadcrumbs have not been invented for blind people. They are part of one technique in a WCAG AAA guideline which implies that : it's not mandatory, and that it concerns everybody.

If you include hidden links in the tab and speech order, you are sure that your website won't be accessible.

A near-blind person using a screenreader in support of his eyes won't be able to view a link on the screen while it's announced by the screenreader.

A person using a keyboard only system will focus an invisible link which will remove the predictability of the focus order.

Note that for 2/ and 3/ the sr-only does not remove the elements from the tabindex, so this will work as you would expect


问:
Getting "document is not defined" error when checking for valid jQuery code though JInt?
Is it possible to check if a JQuery string has a valid syntax? I've tried Jint because of this Determine whether a string contains valid javascript code. Unfortunately, it seems as if this is meant for another use-case.

I have tried the following (which leads to "document is not defined"):

```<code>public bool IsValidJqueryString(string jQueryString)
{
     // Validate JQuery
     var executedQuery = new Jint.Engine().Execute(
          @"$(document).ready(function () {
          });"
     );
}
</code>```

答:
From what I understand (I'm only starting out with Jint) it will run JavaScript, but it doesn't define any variables for you. You have to define up front which variables are going to be available within the JavaScript code (with SetValue()), or define them within the JavaScript code.

So yes, document is not defined since nothing has defined it. Even if you do define it, you may find that it will complain about $ not being a function, since that hasn't been defined either (you haven't loaded the jQuery library).

Body:
Is it possible to check if a JQuery string has a valid syntax? I've tried Jint because of this Determine whether a string contains valid javascript code. Unfortunately, it seems as if this is meant for another use-case.

I have tried the following (which leads to "document is not defined"):

public bool IsValidJqueryString(string jQueryString)
{
     // Validate JQuery
     var executedQuery = new Jint.Engine().Execute(
          @"$(document).ready(function () {
          });"
     );
}


问:
How do I store a custom user selected CSS template style (like wordpress visual editor)?
I am making a diary app. I want users to be able to customize/style the skin of their journal e.g. covers/backgrounds/fonts/colors etc.

I want to create something like the wordpress theme editor that allows users to update the background color in real time:

Here is how style editor would look.

For example if a user wants to set the writing area of the diary to a light yellow, how do I save that color into a custom CSS template and then render it again? Would I need to create a MySQL table just for style templates and have a row for color, background-color, etc... ?

答:
If you want to give users the ability to style a few HTML elements on different sections of your website, the simplest implementation is the following:

1) Create table users_styles with fields:

```<code>id (INT), user_id (INT), section_id (INT), value (VARCHAR 1000).
</code>```

The value field will contain a string with the values of styles in the JSON format. Don't forget about indexes.

2) Add constants of the style types in your PHP class, for example:

```<code>class UserStyle extends Model {

    const JOURNAL_COVER = 1;
    const FONT_NAME = 2;
    const FONT_SIZE = 3;
    const PAGE_THEME = 4;
    const PAD_THEME = 5;
    const BACKGROUND_COLOR = 6;
    // ...
}
</code>```

Constants for sections:

```<code>class SiteSection extends Model {

    const MAIN = 1;
    const BLOG = 2;
    const CALENDAR = 3;
    // ...
}
</code>```

3) Select types and values for the current user with the next query:

```<code>SELECT value
FROM users_styles
WHERE user_id = (int)$currentUserId
      AND section_id = (int)SiteSection::MAIN
</code>```

You'll get a string like this:

```<code>$userStyles = {"1":"sand.jpg","2":"water.jpg","3":"fire.jpg","4":"#EFEFEF","5":"Lora","6":"17px"};
</code>```

After json_decode($userStyles, true); it will contain the next values:

```<code>[
    1=>'sand.jpg',
    2=>'water.jpg',
    3=>'fire.jpg',
    4=>'#EFEFEF',
    5=>'Lora',
    6=>'17px'
];
</code>```

4) Insert styles as internal styles in the corresponding section template with the selected data. For example:

```<code><style type="text/css">
body {
    font-family: "<?= $userStyles[UserStyle::FONT_NAME] ?>", serif !important;
    font-size: <?= $userStyles[UserStyle::FONT_SIZE] ?>px !important;
    background-color: #<?= $userStyles[UserStyle::BACKGROUND_COLOR] ?> !important;
}

#journal-cover {
    background-image: url("<?= $currentUserStylesFilesDirPath.$userStyles[UserStyle::JOURNAL_COVER] ?>") !important;
}

#pad-theme {
    background-image: url("<?= currentUserStylesFilesDirPath.$userStyles[UserStyle::PAD_THEME] ?>") !important;
}
<style>
</code>```

This rules will rewrite all relevant rules for the styles of the body, #journal-cover and #pad-theme elements.

Body:
If you want to give users the ability to style a few HTML elements on different sections of your website, the simplest implementation is the following:

1) Create table users_styles with fields:

id (INT), user_id (INT), section_id (INT), value (VARCHAR 1000).

The value field will contain a string with the values of styles in the JSON format. Don't forget about indexes.

2) Add constants of the style types in your PHP class, for example:

class UserStyle extends Model {

    const JOURNAL_COVER = 1;
    const FONT_NAME = 2;
    const FONT_SIZE = 3;
    const PAGE_THEME = 4;
    const PAD_THEME = 5;
    const BACKGROUND_COLOR = 6;
    // ...
}

Constants for sections:

class SiteSection extends Model {

    const MAIN = 1;
    const BLOG = 2;
    const CALENDAR = 3;
    // ...
}

3) Select types and values for the current user with the next query:

SELECT value
FROM users_styles
WHERE user_id = (int)$currentUserId
      AND section_id = (int)SiteSection::MAIN

You'll get a string like this:

$userStyles = {"1":"sand.jpg","2":"water.jpg","3":"fire.jpg","4":"#EFEFEF","5":"Lora","6":"17px"};

After json_decode($userStyles, true); it will contain the next values:

[
    1=>'sand.jpg',
    2=>'water.jpg',
    3=>'fire.jpg',
    4=>'#EFEFEF',
    5=>'Lora',
    6=>'17px'
];

4) Insert styles as internal styles in the corresponding section template with the selected data. For example:

<style type="text/css">
body {
    font-family: "<?= $userStyles[UserStyle::FONT_NAME] ?>", serif !important;
    font-size: <?= $userStyles[UserStyle::FONT_SIZE] ?>px !important;
    background-color: #<?= $userStyles[UserStyle::BACKGROUND_COLOR] ?> !important;
}

#journal-cover {
    background-image: url("<?= $currentUserStylesFilesDirPath.$userStyles[UserStyle::JOURNAL_COVER] ?>") !important;
}

#pad-theme {
    background-image: url("<?= currentUserStylesFilesDirPath.$userStyles[UserStyle::PAD_THEME] ?>") !important;
}
<style>

This rules will rewrite all relevant rules for the styles of the body, #journal-cover and #pad-theme elements.


问:
Add Image on the Button
Any one help me. How to add the image on the button? I am using following code for create a button. I want to display the image instead of "refresh". is it possible to do this?
Thanks in advance.</p>

```<code><div data-role="button" data-iconpos="right" id="searchResultRefresh" data-icon="refresh">
 refresh </div>
</code>```

答:
You are interested in this document:

http://jquerymobile.com/demos/1.0a2/#docs/buttons/buttons-icons.html

Custom icons are mentioned at the bottom.
Take one of the existing ui-icon-sth classes and change the offsets to refer to the end of the icons file and then add your icon there if you want to reuse it a lot.

If not - just change the image link in the copied CSS and remove background-position definition.

Title: Add Image on the Button

Body:
Any one help me. How to add the image on the button? I am using following code for create a button. I want to display the image instead of "refresh". is it possible to do this?
Thanks in advance.

 refresh


问:
Why does PHP not process my request?
I have a PHP project in which I have an index.html with a simple form:

```<code>    <p>Test connection</p>
    <form action="Servicios.php" method="post">
        <input type='submit' name='Test' value='Test'>
    </form>
</code>```

in Servicios.php Im trying to process it like this

```<code><?php
   echo "can you print this";
    if($_SERVER["REQUEST_METHOD"]=="POST" )
    {
      if(!empty($_POST["Test"]))
      {
         echo "Hello world";
      }
    }
</code>```

But it doesn't works, thats because it never evaluates the first if like "true". The first echo at the top does works but if I do an echo to $_SERVER["REQUEST_METHOD"] it doesn't give me anything. I've tried with isset($_POST['Hola']) but I had the same result.

This only happens in the project I have in an internet host. I wrote this exact same code in my local computer using netbeans and xampp and it works perfectly. I have no idea why.

I have the feeling that I'm making some silly mistake but I cant find it.

My host is an Ubuntu server from the ec2 Amazon Web Services.

Edit
this is the output of <?=print_r($_SERVER);?> in Servicios.php
I replaced the parts where my ip is showed with [ip]

```<code>Array (
    [HTTP_HOST] => [ip]
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    [HTTP_ACCEPT_LANGUAGE] => es-MX,es-ES;q=0.9,es;q=0.7,es-AR;q=0.6,es-CL;q=0.4,en-US;q=0.3,en;q=0.1
    [HTTP_ACCEPT_ENCODING] => gzip, deflate
    [HTTP_REFERER] => http://[ip]/ProyectoPM/
    [CONTENT_TYPE] => application/x-www-form-urlencoded
    [CONTENT_LENGTH] => 11
    [HTTP_CONNECTION] => keep-alive
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [PATH] => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    [SERVER_SIGNATURE] => Apache/2.4.18 (Ubuntu) Server at [ip] Port 80
    [SERVER_SOFTWARE] => Apache/2.4.18 (Ubuntu)
    [SERVER_NAME] => [ip]
    [SERVER_ADDR] => 172.31.43.105
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => 189.208.87.127
    [DOCUMENT_ROOT] => /var/www/html
    [REQUEST_SCHEME] => http
    [CONTEXT_PREFIX] =>
    [CONTEXT_DOCUMENT_ROOT] => /var/www/html
    [SERVER_ADMIN] => webmaster@localhost
    [SCRIPT_FILENAME] => /var/www/html/ProyectoPM/Servicios.php
    [REMOTE_PORT] => 5672
    [GATEWAY_INTERFACE] => CGI/1.1
    [SERVER_PROTOCOL] => HTTP/1.1
    [REQUEST_METHOD] => POST
    [QUERY_STRING] =>
    [REQUEST_URI] => /ProyectoPM/Servicios.php
    [SCRIPT_NAME] => /ProyectoPM/Servicios.php
    [PHP_SELF] => /ProyectoPM/Servicios.php
    [REQUEST_TIME_FLOAT] => 1510846404.812
    [REQUEST_TIME] => 1510846404 ) 1
</code>```

This is in the array it returns with <?=var_dump($_SERVER); ?>

```<code> ["SERVER_PROTOCOL"]=> string(8) "HTTP/1.1"
 ["REQUEST_METHOD"]=> string(4) "POST"
 ["QUERY_STRING"]=> string(0) ""
 ["REQUEST_URI"]=> string(25) "/ProyectoPM/Servicios.php"
 ["SCRIPT_NAME"]=> string(25) "/ProyectoPM/Servicios.php"
 ["PHP_SELF"]=> string(25) "/ProyectoPM/Servicios.php"
 ["REQUEST_TIME_FLOAT"]=> float(1510847672.582)
 ["REQUEST_TIME"]=> int(1510847672) }
</code>```

A more important edit
At first I said that a simple echo "can you print this"; worked in the host, now I see that it doesn't either. When I move to Servicios.php in by clicking my button in index.html the browser moves to Servicios.php (it displays it in the url) but it simply doesnt show anything. It only shows something if i delete all the code an put a instrucion like <?=print_r($_SERVER);?>  which result I already put above.

答:
You can try this to check if post method</p>

```<code>if(strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') {
 // if form submitted with post method
    // validate request,
    // manage post request differently,
    // log or don't log request,
  // redirect to avoid resubmition on F5 etc
}
</code>```

Title: Why does PHP not process my request?

Body:
I have a PHP project in which I have an index.html with a simple form:

Test connection

    <form action="Servicios.php" method="post">
        <input type='submit' name='Test' value='Test'>
    </form>

in Servicios.php Im trying to process it like this

<?php
   echo "can you print this";
    if($_SERVER["REQUEST_METHOD"]=="POST" )
    {
      if(!empty($_POST["Test"]))
      {
         echo "Hello world";
      }
    }

But it doesn't works, thats because it never evaluates the first if like "true". The first echo at the top does works but if I do an echo to $_SERVER["REQUEST_METHOD"] it doesn't give me anything. I've tried with isset($_POST['Hola']) but I had the same result.

This only happens in the project I have in an internet host. I wrote this exact same code in my local computer using netbeans and xampp and it works perfectly. I have no idea why.

I have the feeling that I'm making some silly mistake but I cant find it.

My host is an Ubuntu server from the ec2 Amazon Web Services.

Edit
this is the output of <?=print_r($_SERVER);?> in Servicios.php
I replaced the parts where my ip is showed with [ip]

Array (
    [HTTP_HOST] => [ip]
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    [HTTP_ACCEPT_LANGUAGE] => es-MX,es-ES;q=0.9,es;q=0.7,es-AR;q=0.6,es-CL;q=0.4,en-US;q=0.3,en;q=0.1
    [HTTP_ACCEPT_ENCODING] => gzip, deflate
    [HTTP_REFERER] => http://[ip]/ProyectoPM/
    [CONTENT_TYPE] => application/x-www-form-urlencoded
    [CONTENT_LENGTH] => 11
    [HTTP_CONNECTION] => keep-alive
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [PATH] => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    [SERVER_SIGNATURE] => Apache/2.4.18 (Ubuntu) Server at [ip] Port 80
    [SERVER_SOFTWARE] => Apache/2.4.18 (Ubuntu)
    [SERVER_NAME] => [ip]
    [SERVER_ADDR] => 172.31.43.105
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => 189.208.87.127
    [DOCUMENT_ROOT] => /var/www/html
    [REQUEST_SCHEME] => http
    [CONTEXT_PREFIX] =>
    [CONTEXT_DOCUMENT_ROOT] => /var/www/html
    [SERVER_ADMIN] => webmaster@localhost
    [SCRIPT_FILENAME] => /var/www/html/ProyectoPM/Servicios.php
    [REMOTE_PORT] => 5672
    [GATEWAY_INTERFACE] => CGI/1.1
    [SERVER_PROTOCOL] => HTTP/1.1
    [REQUEST_METHOD] => POST
    [QUERY_STRING] =>
    [REQUEST_URI] => /ProyectoPM/Servicios.php
    [SCRIPT_NAME] => /ProyectoPM/Servicios.php
    [PHP_SELF] => /ProyectoPM/Servicios.php
    [REQUEST_TIME_FLOAT] => 1510846404.812
    [REQUEST_TIME] => 1510846404 ) 1

This is in the array it returns with <?=var_dump($_SERVER); ?>

 ["SERVER_PROTOCOL"]=> string(8) "HTTP/1.1"
 ["REQUEST_METHOD"]=> string(4) "POST"
 ["QUERY_STRING"]=> string(0) ""
 ["REQUEST_URI"]=> string(25) "/ProyectoPM/Servicios.php"
 ["SCRIPT_NAME"]=> string(25) "/ProyectoPM/Servicios.php"
 ["PHP_SELF"]=> string(25) "/ProyectoPM/Servicios.php"
 ["REQUEST_TIME_FLOAT"]=> float(1510847672.582)
 ["REQUEST_TIME"]=> int(1510847672) }

A more important edit
At first I said that a simple echo "can you print this"; worked in the host, now I see that it doesn't either. When I move to Servicios.php in by clicking my button in index.html the browser moves to Servicios.php (it displays it in the url) but it simply doesnt show anything. It only shows something if i delete all the code an put a instrucion like <?=print_r($_SERVER);?>  which result I already put above.

Body:
You can try this to check if post method

if(strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') {
 // if form submitted with post method
    // validate request,
    // manage post request differently,
    // log or don't log request,
  // redirect to avoid resubmition on F5 etc
}


问:
read json zipped directly from urlrquest
I want to read a file directly to python w/o having to save it - the zip files are relatively small and definitely fit into mem.

I am currently trying this:

```<code>        import urllib
        import json
        access_url = urllib.request.urlopen('http://api.eia.gov/bulk/COAL.zip')
        data = json.loads(access_url.read().decode())
</code>```

But I get the error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 15: invalid start byte

What extra step may solve this issue?

I am using python 3.6.

Thanks!

答:
You now treat a zipped archive (that can contain many files) as a file containing your actual data.  Let us assume your zip contains only one file that then contains the actual JSON data. This would work:

```<code>import zipfile
import io
import urllib
import json

access_url = urllib.request.urlopen('http://api.eia.gov/bulk/COAL.zip')

z = zipfile.ZipFile(io.BytesIO(access_url.read()))
data = json.loads(z.read(z.infolist()[0]).decode())
print(data)
</code>```

Or something like that. I was not actually able to test on live data but give it a go. It basically unzips the first file it finds in your archive and then treats this as json.

Body:
I want to read a file directly to python w/o having to save it - the zip files are relatively small and definitely fit into mem.

I am currently trying this:

        import urllib
        import json
        access_url = urllib.request.urlopen('http://api.eia.gov/bulk/COAL.zip')
        data = json.loads(access_url.read().decode())

But I get the error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 15: invalid start byte

What extra step may solve this issue?

I am using python 3.6.

Thanks!

Body:
You now treat a zipped archive (that can contain many files) as a file containing your actual data.  Let us assume your zip contains only one file that then contains the actual JSON data. This would work:

import zipfile
import io
import urllib
import json

access_url = urllib.request.urlopen('http://api.eia.gov/bulk/COAL.zip')

z = zipfile.ZipFile(io.BytesIO(access_url.read()))
data = json.loads(z.read(z.infolist()[0]).decode())
print(data)

Or something like that. I was not actually able to test on live data but give it a go. It basically unzips the first file it finds in your archive and then treats this as json.


问:
Router.use() requires a middle function, but got an Object. module.exports = router exists on page
from app.js

```<code> // REQUIRE ROUTES
    var commentRoutes = require("./routes/comments"),
    bpostRoutes = require("./routes/bposts"),
    indexRoutes = require("./routes/index");

   //USE ROUTES
   app.use("/", indexRoutes);
   app.use("/bposts", bpostRoutes);
   app.use("/bposts/:id/comments", commentRoutes);
</code>```

from routes/index.js

```<code>     var express = require("express");
     var router  = express.Router();

     //LANDING -root route
     router.get("/", function(req, res){
     res.render("landing");
   });

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

I am currently trying to setup all my routes before I create a DB or do anything meaningful for the blog. When I encountered this problem the first time it was because I didn't use

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

on each route page I had. Express router is installed and saved to package.json. Each time I have run into this error it's a quick fix because I didn't include export statement. Now I have finally remembered to add it in and I am still receiving this error message. Any suggestions or advice would be greatly appreciated!

```<code> throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
  ^

TypeError: Router.use() requires a middleware function but got a Object
    at Function.use (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:458:13)
    at EventEmitter.<anonymous> (/home/ubuntu/workspace/node_modules/express/lib/application.js:220:21)
    at Array.forEach (native)
    at EventEmitter.use (/home/ubuntu/workspace/node_modules/express/lib/application.js:217:7)
    at Object.<anonymous> (/home/ubuntu/workspace/app.js:25:5)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3
</code>```

答: I use an IDE callled C9(Cloud 9) and only use the free service, which means lower performance and potential downtime prioritizing user space for paid cx. So I logged out of my account and relogged in. It then cleared and cleaned up the workspace as it was launching my app. After this I was able to preview my app without any issue. Time to upgrade! I changed nothing in the code, no additions or subtractions. It's the first time I have seen it happen in 6 months I have used it. This did resolve the issue. Thanks for all the help and suggestions!</p>

Body:
from app.js

 // REQUIRE ROUTES
    var commentRoutes = require("./routes/comments"),
    bpostRoutes = require("./routes/bposts"),
    indexRoutes = require("./routes/index");

   //USE ROUTES
   app.use("/", indexRoutes);
   app.use("/bposts", bpostRoutes);
   app.use("/bposts/:id/comments", commentRoutes);

from routes/index.js

     var express = require("express");
     var router  = express.Router();

     //LANDING -root route
     router.get("/", function(req, res){
     res.render("landing");
   });

   module.exports = router;

I am currently trying to setup all my routes before I create a DB or do anything meaningful for the blog. When I encountered this problem the first time it was because I didn't use

module.exports = router;

on each route page I had. Express router is installed and saved to package.json. Each time I have run into this error it's a quick fix because I didn't include export statement. Now I have finally remembered to add it in and I am still receiving this error message. Any suggestions or advice would be greatly appreciated!

 throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
  ^

TypeError: Router.use() requires a middleware function but got a Object
    at Function.use (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:458:13)
    at EventEmitter.<anonymous> (/home/ubuntu/workspace/node_modules/express/lib/application.js:220:21)
    at Array.forEach (native)
    at EventEmitter.use (/home/ubuntu/workspace/node_modules/express/lib/application.js:217:7)
    at Object.<anonymous> (/home/ubuntu/workspace/app.js:25:5)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3


问:
CSS min-height not working in firefox
I'm working on a ReactJS app and I want my body to take up the entire screen at least - using min-height: 100%, with height: auto to account for the screen being more than 100%. This is not working in firefox specifically but is working in other browsers.

Left is chrome, right is firefox.

Everything is being held by a div with the body class as such;

```<code><div className={styles.body}>
   {this.props.children}
</div>
</code>```

My scss:

```<code>.body{
display: block;
font-family: "Ubuntu", sans-serif;
margin: auto;
height: auto;
min-height: 100%;
width: 100%;
background:
    linear-gradient(135deg, #696D7D 22px, #FAF5E3 22px, #FAF5E3 24px, transparent 24px, transparent 67px, #FAF5E3 67px, #FAF5E3 69px, transparent 69px),
    linear-gradient(225deg, #696D7D 22px, #FAF5E3 22px, #FAF5E3 24px, transparent 24px, transparent 67px, #FAF5E3 67px, #FAF5E3 69px, transparent 69px)0 64px;
background-color:#696D7D;
background-size: 64px 128px;
}
</code>```

答:
You could use the vh unit to set your div to 100% height of the viewport

```<code>.yourClass {
    height: 100vh;
}
</code>```

Hope it's what you was looking for.

Title: CSS min-height not working in firefox

Body:
I'm working on a ReactJS app and I want my body to take up the entire screen at least - using min-height: 100%, with height: auto to account for the screen being more than 100%. This is not working in firefox specifically but is working in other browsers.

Left is chrome, right is firefox.

Everything is being held by a div with the body class as such;

   {this.props.children}

My scss:

.body{
display: block;
font-family: "Ubuntu", sans-serif;
margin: auto;
height: auto;
min-height: 100%;
width: 100%;
background:
    linear-gradient(135deg, #696D7D 22px, #FAF5E3 22px, #FAF5E3 24px, transparent 24px, transparent 67px, #FAF5E3 67px, #FAF5E3 69px, transparent 69px),
    linear-gradient(225deg, #696D7D 22px, #FAF5E3 22px, #FAF5E3 24px, transparent 24px, transparent 67px, #FAF5E3 67px, #FAF5E3 69px, transparent 69px)0 64px;
background-color:#696D7D;
background-size: 64px 128px;
}

Body:
You could use the vh unit to set your div to 100% height of the viewport

.yourClass {
    height: 100vh;
}

Hope it's what you was looking for.


答:
That's because you are not updating the time variable, but just calling getTime in setInterval.

This is how it should be:

```<code>setInterval(function() {
  time = getTime();
  console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);
</code>```

Note:

If you declare your time variable as constant with cons keyword, trying to change it will throw this error:

Uncaught TypeError: Assignment to constant variable.

Demo:

function getTime() {
  const d = new Date();
  const secs = d.getSeconds();
  const mins = d.getMinutes();
  const hours = d.getHours();

  return {
    'hours': hours,
    'mins': mins,
    'secs': secs
  }
}

var time = getTime();

setInterval(function() {
  time = getTime();
    console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);```

Title: Why Isn't time variable changing?

Body:
function getTime() {
      const d = new Date();
      const secs = d.getSeconds();
      const mins = d.getMinutes();
      const hours = d.getHours();

      return {
        'hours': hours,
        'mins': mins,
        'secs': secs
      }
    }

    let time = getTime();

    setInterval(getTime, 1000);
    setInterval(() => {
      console.log(`${time.hours}:${time.mins}:${time.secs}`);
    }, 1000);

The time displayed doesn't change. It just continually runs, outputting the same time instead of showing a change each second...

Body:
That's because you are not updating the time variable, but just calling getTime in setInterval.

This is how it should be:

setInterval(function() {
  time = getTime();
  console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);

Note:

If you declare your time variable as constant with cons keyword, trying to change it will throw this error:

Uncaught TypeError: Assignment to constant variable.

Demo:

function getTime() {
  const d = new Date();
  const secs = d.getSeconds();
  const mins = d.getMinutes();
  const hours = d.getHours();

  return {
    'hours': hours,
    'mins': mins,
    'secs': secs
  }
}

var time = getTime();

setInterval(function() {
  time = getTime();
    console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);


问:
How to check which SQL query is so CPU intensive
Is there any possible way to check which query is so CPU intensive in _sqlsrv2 process?
Something which give me information about executed query in that process in that moment.

Is there any way to terminate that query without killing _sqlsrv2 process?

I cannot find any official materials in that subject.

Thank You for any help.

答:
You can use a Select like this:

```<code>select
    c."_Connect-type",
    c."_Connect-PID" as 'PID',
    c."_connect-ipaddress" as 'IP',
    c."_Connect-CacheInfo"
from
    pub."_connect" c
where
    c."_Connect-CacheInfo" is not null
</code>```

But first you need to enable connection cache, follow this example

Body:
You can use a Select like this:

select
    c."_Connect-type",
    c."_Connect-PID" as 'PID',
    c."_connect-ipaddress" as 'IP',
    c."_Connect-CacheInfo"
from
    pub."_connect" c
where
    c."_Connect-CacheInfo" is not null

But first you need to enable connection cache, follow this example


问:
link between two columns when generating random data
I have a spreadsheet of words in German and English.

For example:

```<code>          A          B           C          D
1     Hallo         Hello                  random word
2     Blau          Blue
3     Hund          Dog
4     Blumen        Flowers
5     Auto          Car
</code>```

And in a random cell (say in cell D1) I can generate a random german word from column A using:

```<code>=INDEX($A:$A|RANDBETWEEN(1|COUNTA($A:$A))|1)
</code>```

Now in E1, I want to print the appropriate english word. So when we press F9 and generate a new random word, I always get the correction translation.

Any suggestions on how to make this link?

答:
In E1

```<code>=VLOOKUP(D1,A:B,2,FALSE)
</code>```

where D1 contains:

```<code>=INDEX(A:A,RANDBETWEEN(1,COUNTA(A:A)))
</code>```

Body:
I have a spreadsheet of words in German and English.

For example:

          A          B           C          D
1     Hallo         Hello                  random word
2     Blau          Blue
3     Hund          Dog
4     Blumen        Flowers
5     Auto          Car

And in a random cell (say in cell D1) I can generate a random german word from column A using:

=INDEX($A:$A|RANDBETWEEN(1|COUNTA($A:$A))|1)

Now in E1, I want to print the appropriate english word. So when we press F9 and generate a new random word, I always get the correction translation.

Any suggestions on how to make this link?

Body:
In E1

=VLOOKUP(D1,A:B,2,FALSE)

where D1 contains:

=INDEX(A:A,RANDBETWEEN(1,COUNTA(A:A)))


问:
How are Corda node keystores generated in dev mode?
When in dev mode, does a Corda node generate a new identity certificate every time it starts up? How is the new identity certificate signed by the certificate authority?</p>

答:
In dev mode, the node will look in its keystore to see if it already has the certificates for its identity. If it doesn’t, it generates them automatically. A hardcoded test root CA is used to sign these certificates. This is not secure for real usage, but it suffices for dev/demo purposes.

Outside of dev mode, the node will expect the relevant certificates to already exist in its keystore, and will throw an exception if they don’t exist.


问:
Decode binary ExtensionObject
I'm testing Eclipse Milo (Version 0.1.5) to communicate as a client with the OPC UA server of a TwinCAT PLC. My java program acts as a kind of middleware. It reads structures from a TwinCAT OPC UA server, puts their values into a JSON and sends it to an other server.

For testing I created in the PLC a sample struct with two variables:

 stSimpleStruct (Structure definiend in PLC)

- bVar1 (boolean)

- fVar2 (float)

Picture of Struct in TwinCAT

If I read the node, the value is an ExtensionObject encoded as ByteString. The values of the structure variables (bVar1 and fVar2) should be read and put into a JSON object. So the result is something like this:

```<code>{
    “bVar1” : false,
    “fVar2” : 0
}
</code>```

The structure above is just an example. The structures to be read are only known at runtime. How can I decode the binary ExtensionObject to get access to the values of the structure variables?

Here is my code:

```<code> // Get endpoints
 String endpointURL = "opc.tcp://172.20.1.1:4840";
 EndpointDescription[] endpoints = UaTcpStackClient.getEndpoints(endpointURL).get();
 logger.info("Available endpoint:");
 for (EndpointDescription endpoint : endpoints)
 {
     logger.info("{} Security: {}", endpoint.getEndpointUrl(), endpoint.getSecurityPolicyUri());
 }
 // Chose endpoint
 SecurityPolicy securityPolicy = SecurityPolicy.None;
 EndpointDescription endpoint = Arrays.stream(endpoints)
     .filter(e -> e.getSecurityPolicyUri().equals(securityPolicy.getSecurityPolicyUri()))
     .findFirst()
     .orElseThrow(() -> new Exception("No desired endpoints returned"));
 logger.info("Using endpoint: {} [{}]", endpoint.getEndpointUrl(), SecurityPolicy.None);
 // Create client config
 OpcUaClientConfig config = OpcUaClientConfig.builder()
     .setApplicationName(LocalizedText.english("TestApplication"))
     .setEndpoint(endpoint)
     .setRequestTimeout(uint(5000))
     .build();
 OpcUaClient client = new OpcUaClient(config);
 // Synchronous connect
 client.connect().get();
 // Read struct
 NodeId nodeId = new NodeId(4, "MAIN.stSimpleStruct");
 VariableNode node = client.getAddressSpace().createVariableNode(nodeId);
 DataValue value = node.readValue().get();
 ExtensionObject extensionObject = (ExtensionObject) value.getValue().getValue();
</code>```

答:
Custom DataTypes aren't supported by Milo right now.

I have working code that can read the DataTypeDictionary nodes in the server and build custom codecs at runtime that get registered with the DataTypeManager, but if, when, and how this code is going to be released still hasn't been decided. In any case, it's written against the development 0.2.0 branch of Milo, which has changes to accommodate custom DataTypes, so it won't be available until at least then.

You can email me, the list, or stop by the gitter.im channel if you want to discuss this further.

Title: Decode binary ExtensionObject

Body:
I'm testing Eclipse Milo (Version 0.1.5) to communicate as a client with the OPC UA server of a TwinCAT PLC. My java program acts as a kind of middleware. It reads structures from a TwinCAT OPC UA server, puts their values into a JSON and sends it to an other server.

For testing I created in the PLC a sample struct with two variables:

 stSimpleStruct (Structure definiend in PLC)

- bVar1 (boolean)

- fVar2 (float)

Picture of Struct in TwinCAT

If I read the node, the value is an ExtensionObject encoded as ByteString. The values of the structure variables (bVar1 and fVar2) should be read and put into a JSON object. So the result is something like this:

{
    “bVar1” : false,
    “fVar2” : 0
}

The structure above is just an example. The structures to be read are only known at runtime. How can I decode the binary ExtensionObject to get access to the values of the structure variables?

Here is my code:

 // Get endpoints
 String endpointURL = "opc.tcp://172.20.1.1:4840";
 EndpointDescription[] endpoints = UaTcpStackClient.getEndpoints(endpointURL).get();
 logger.info("Available endpoint:");
 for (EndpointDescription endpoint : endpoints)
 {
     logger.info("{} Security: {}", endpoint.getEndpointUrl(), endpoint.getSecurityPolicyUri());
 }
 // Chose endpoint
 SecurityPolicy securityPolicy = SecurityPolicy.None;
 EndpointDescription endpoint = Arrays.stream(endpoints)
     .filter(e -> e.getSecurityPolicyUri().equals(securityPolicy.getSecurityPolicyUri()))
     .findFirst()
     .orElseThrow(() -> new Exception("No desired endpoints returned"));
 logger.info("Using endpoint: {} [{}]", endpoint.getEndpointUrl(), SecurityPolicy.None);
 // Create client config
 OpcUaClientConfig config = OpcUaClientConfig.builder()
     .setApplicationName(LocalizedText.english("TestApplication"))
     .setEndpoint(endpoint)
     .setRequestTimeout(uint(5000))
     .build();
 OpcUaClient client = new OpcUaClient(config);
 // Synchronous connect
 client.connect().get();
 // Read struct
 NodeId nodeId = new NodeId(4, "MAIN.stSimpleStruct");
 VariableNode node = client.getAddressSpace().createVariableNode(nodeId);
 DataValue value = node.readValue().get();
 ExtensionObject extensionObject = (ExtensionObject) value.getValue().getValue();


问:
Firefox Quantum responsive design mode: settings for align left & default size?
I just upgraded to firefox quantum and am unhappy with the changes to responsive design mode.  I can't find any settings to configure things manually, and I'm wondering if I'm missing something.

1) The responsive window is now centered in the browser, rather than being aligned left as it was previously.  This really messes with my workflow/window positioning for development.  Is there a way to align the responsive design mode window to the left?

2) The responsive design mode window always opens at 320 x 480.  In previous versions of firefox it would open at whatever size was last used.  Any way to change this?

Thanks in advance for any thoughts.

答:
1) Locate your profile folder (navigate to about:support and click button near "Profile Folder")

2) create or locate folder chrome there and create or locate file userContent.css in it

3) paste following code there

```<code>@-moz-document url("chrome://devtools/content/responsive.html/index.xhtml")
{
  #app {align-items: flex-start !important; }
}
</code>```

4) restart browser

Body:
1) Locate your profile folder (navigate to about:support and click button near "Profile Folder")

2) create or locate folder chrome there and create or locate file userContent.css in it

3) paste following code there

@-moz-document url("chrome://devtools/content/responsive.html/index.xhtml")
{
  #app {align-items: flex-start !important; }
}

4) restart browser


问:
Using Monolog and ReactPHP
I'm trying to build my Symfony application on top of ReactPHP engine, and everything goes fine, but the logs.

I have my application configured with a regular file log under devel environment, and a simple syslog log with level=error under production. In both environments I have "debug" enabled, otherwise even without ReactPHP and using a simple Apache, I cannot see any error in syslog.

The problem comes when I use ReactPHP. Initializing the symfony kernel using devel environment, everything is logged BUT the exception. It seems that I'm doing something wrong because Monolog is not handling the exception and any error is being logged.

Do you know any part of the Symfony application initialization where all this handlers are enabled (and I should add it as well in the kernel initialization in my ReactPHP file)?

If not, then... Symfony should work the same way under ReactPHP, right? I mean, the kernel should always handle any error/exception and log it the way I configured in MonologBundle, and after that, throw the exception again, right?

答: This is just a guess, but maybe your error gets usually logged via PHP's  set_exception_handler(), while ReactPHP will catch uncaught exceptions inside its request handler to ensure the server stays up and running and doesn't die for every uncaught exception.

Title: Using Monolog and ReactPHP


答:
```<code>import urllib.request
import json
from io import BytesIO
from zipfile import ZipFile

access_url = urllib.request.urlopen('http://api.eia.gov/bulk/COAL.zip')
zf = ZipFile(BytesIO(access_url.read()))
zdata = zf.read('COAL.txt')

print(zdata)
</code>```

Title: read json zipped directly from urlrquest


问:
How to enable --debug-only in LLVM build with cmake?
I am building LLVM with cmake and Ninja build generator as following:

```<code>cmake path/to/llvm/ -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=1 -DLLVM_ENABLE_CXX1Y=1 -DLLVM_ENABLE_RTTI=1 -DLLVM_TARGETS_TO_BUILD="X86" -G Ninja
</code>```

Now I a am trying to use the -debug-only=mytype option of opt to print some debug information about my own passes: using the following in my passes code:

```<code>define DEBUG_TYPE "mytype"
DEBUG(errs() << "My debug message\n");
</code>```

Running opt as following doesn't generate any output messages:

```<code>opt < a.bc > /dev/null -mypass -debug-only=mytype
</code>```

According to LLVM documentation:

For performance reasons, -debug-only is not available in optimized build (--enable-optimized) of LLVM.

I suspect this to be the root of my issue, but I can't find how to turn on/off this option when using cmake to build llvm.

答: I am adding here a complement answer to my question. As @Joky said, cmake -DLLVM_ENABLE_ASSERTIONS=ON must be specified when compiling llvm. Also, because my passes are built outside the llvm source tree, assertions must also be enabled when building the passes.

Body:
I am building LLVM with cmake and Ninja build generator as following:

cmake path/to/llvm/ -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=1 -DLLVM_ENABLE_CXX1Y=1 -DLLVM_ENABLE_RTTI=1 -DLLVM_TARGETS_TO_BUILD="X86" -G Ninja

Now I a am trying to use the -debug-only=mytype option of opt to print some debug information about my own passes: using the following in my passes code:

define DEBUG_TYPE "mytype"
DEBUG(errs() << "My debug message\n");

Running opt as following doesn't generate any output messages:

opt  /dev/null -mypass -debug-only=mytype

According to LLVM documentation:

For performance reasons, -debug-only is not available in optimized build (--enable-optimized) of LLVM.

I suspect this to be the root of my issue, but I can't find how to turn on/off this option when using cmake to build llvm.


问:
Text and table on single row and vertically aligned
I'm trying to have text and table inside another table cell and have them on a single row and vertically aligned.

Basically this code:

```<code><table>
  <tr>
    <td>
      text:
      <table>
        <tr>
          <td>a</td>
          <td>b</td>
        </tr>
      </table>
    </td>
  </tr>
</table>
</code>```

To yield this result:

```<code>text: a b
</code>```

Fiddle: https://jsfiddle.net/3uxcn5pz/

---- stop reading here to avoid cry of desperate  non-GUI programmer -----

I'm trying space-wrap, floating, displays, line heights etc.
But I cannot seem to accomplish this simple thing in a time that I need to build a space rocket guiding module. Instead I feel like html+CSS is there to torture innocent programmers (and if that's not enough - throw Javascript to the mix)

答:
Set both tables to display: inline-table and use the vertical-align property.

fiddle

table {
  display: inline-table;
}

td {
  vertical-align: text-bottom;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>
      text:
      <table>
        <tr>
          <td>a</td>
          <td>b</td>
        </tr>
      </table>
    </td>
  </tr>
</table>

<br/>
<br/>
<table>
  <tr>
    <td>
      text:
      <table>
        <tr>
          <td>a</td>
          <td>b</td>
        </tr>
      </table>
    </td>
  </tr>
</table></code>```

Body:
I'm trying to have text and table inside another table cell and have them on a single row and vertically aligned.

Basically this code:

      text:

          a
          b

To yield this result:

text: a b

Fiddle: https://jsfiddle.net/3uxcn5pz/

---- stop reading here to avoid cry of desperate  non-GUI programmer -----

I'm trying space-wrap, floating, displays, line heights etc.
But I cannot seem to accomplish this simple thing in a time that I need to build a space rocket guiding module. Instead I feel like html+CSS is there to torture innocent programmers (and if that's not enough - throw Javascript to the mix)

Body:
Set both tables to display: inline-table and use the vertical-align property.

fiddle

table {
  display: inline-table;
}

td {
  vertical-align: text-bottom;
}

<table>
  <tr>
    <td>
      text:
      <table>
        <tr>
          <td>a</td>
          <td>b</td>
        </tr>
      </table>
    </td>
  </tr>
</table>

<br/>
<br/>
<table>
  <tr>
    <td>
      text:
      <table>
        <tr>
          <td>a</td>
          <td>b</td>
        </tr>
      </table>
    </td>
  </tr>
</table>