问:
Combine columns of dataframe into new dataframe
I am new to pandas and working with DataFrames. I'm looking at the documentation for Merge,Join,Concatenate, and it's probably staring me right in the face, but I'm still having trouble transposing the data the way I need it.

I have data that looks like this ( R rows x 4302 columns ):

```<code>| w:350 |       r:350 | w:351 |   r:351 |  ...  | w:2499 |      r:2499 | w:2500 |  r:2500 |
-------------------------------------------------------------------------------------------
|   350 | -3.0998e-04 |   351 |  0.0001 |  ...  |   2499 | -3.6000e-05 |   2500 |  0.0004 |
|   350 | -1.8316e-03 |   351 | -0.0008 |  ...  |   2499 | -3.1124e-04 |   2500 | -0.0004 |
|   350 | -1.0520e-03 |   351 | -0.0014 |  ...  |   2499 |  4.0166e-04 |   2500 |  0.0012 |
|   350 | -3.4060e-04 |   351 |  0.0006 |  ...  |   2499 |  1.2782e-03 |   2500 |  0.0012 |
</code>```

That I want to look like this ( X rows x 2 columns ):

```<code>|     x |           y |
-----------------------
|   350 | -3.0998e-04 |
|   350 | -1.8316e-03 |
|   350 | -1.0520e-03 |
|   350 | -3.4060e-04 |
|   351 |      0.0001 |
|   351 |     -0.0008 |
|   351 |     -0.0014 |
|   351 |      0.0006 |
...
|  2499 | -3.6000e-05 |
|  2499 | -3.1124e-04 |
|  2499 |  4.0166e-04 |
|  2499 |  1.2782e-03 |
|  2500 |      0.0004 |
|  2500 |     -0.0004 |
|  2500 |      0.0012 |
|  2500 |      0.0012 |
</code>```

I guess you can think of it as a DataFrame of rows of multiple sets of x,y data, that I want combined into a DataFrame of rows of a single set of x,y data. Or in other words, each row is currently a graph of x,y data. And I need a single collection of x,y data of all the graphs.

I've tried this, but it's not working (probably because the column names not named the same). It's also probably not the most efficient way to do what I'm trying to do. Here output is my original data, and outputxy is the transposed data that I want.

```<code>outputxy = pandas.DataFrame()
for i in range(0, len(output.columns), 2):
    outputxy = pandas.concat([output.iloc[:, i:i+2], outputxy])
</code>```

Thank you in advance for any help!

答:
We can using wide_to_long, if you need column name to be x, y , you can rename it

PS: this method , does not require the order of your columns.

```<code>pd.wide_to_long(df.reset_index(),stubnames=['w','r'],i='index',j='drop',sep=':').reset_index(drop=True)
Out[205]:
     w         r
0  350 -0.000310
1  350 -0.001832
2  350 -0.001052
3  350 -0.000341
4  351  0.000100
5  351 -0.000800
6  351 -0.001400
7  351  0.000600
</code>```

Body:
I am new to pandas and working with DataFrames. I'm looking at the documentation for Merge,Join,Concatenate, and it's probably staring me right in the face, but I'm still having trouble transposing the data the way I need it.

I have data that looks like this ( R rows x 4302 columns ):

| w:350 |       r:350 | w:351 |   r:351 |  ...  | w:2499 |      r:2499 | w:2500 |  r:2500 |
-------------------------------------------------------------------------------------------
|   350 | -3.0998e-04 |   351 |  0.0001 |  ...  |   2499 | -3.6000e-05 |   2500 |  0.0004 |
|   350 | -1.8316e-03 |   351 | -0.0008 |  ...  |   2499 | -3.1124e-04 |   2500 | -0.0004 |
|   350 | -1.0520e-03 |   351 | -0.0014 |  ...  |   2499 |  4.0166e-04 |   2500 |  0.0012 |
|   350 | -3.4060e-04 |   351 |  0.0006 |  ...  |   2499 |  1.2782e-03 |   2500 |  0.0012 |

That I want to look like this ( X rows x 2 columns ):

|     x |           y |
-----------------------
|   350 | -3.0998e-04 |
|   350 | -1.8316e-03 |
|   350 | -1.0520e-03 |
|   350 | -3.4060e-04 |
|   351 |      0.0001 |
|   351 |     -0.0008 |
|   351 |     -0.0014 |
|   351 |      0.0006 |
...
|  2499 | -3.6000e-05 |
|  2499 | -3.1124e-04 |
|  2499 |  4.0166e-04 |
|  2499 |  1.2782e-03 |
|  2500 |      0.0004 |
|  2500 |     -0.0004 |
|  2500 |      0.0012 |
|  2500 |      0.0012 |

I guess you can think of it as a DataFrame of rows of multiple sets of x,y data, that I want combined into a DataFrame of rows of a single set of x,y data. Or in other words, each row is currently a graph of x,y data. And I need a single collection of x,y data of all the graphs.

I've tried this, but it's not working (probably because the column names not named the same). It's also probably not the most efficient way to do what I'm trying to do. Here output is my original data, and outputxy is the transposed data that I want.

outputxy = pandas.DataFrame()
for i in range(0, len(output.columns), 2):
    outputxy = pandas.concat([output.iloc[:, i:i+2], outputxy])

Thank you in advance for any help!

Body:
We can using wide_to_long, if you need column name to be x, y , you can rename it

PS: this method , does not require the order of your columns.

pd.wide_to_long(df.reset_index(),stubnames=['w','r'],i='index',j='drop',sep=':').reset_index(drop=True)
Out[205]:
     w         r
0  350 -0.000310
1  350 -0.001832
2  350 -0.001052
3  350 -0.000341
4  351  0.000100
5  351 -0.000800
6  351 -0.001400
7  351  0.000600


来源: stackexchange

问:
gensim with jython
Im using Jython 2.7.1. It is working fine. I need to install gensim. Does this library works in jython?

Thank you

答:
No, Jython does not support gensim.

Gensim has as dependencies SciPy and NumPy. Gensim Installation

Both libraries use native C extensions, which Jython does not support. There is a project whose goal is to allow the use of C extensions in Jython - JyNI. As of 2015, JyNI did not adequately support NumPy. See This Question. I have not tested later versions of JyNI.

ContentLicense: CC BY-SA 3.0

Title: gensim with jython


问:
Strange behavior with flashdata in codeigniter
I have found very strange behavior of "if" condition and session flashdata in codeigniter,

```<code>public function edit_equip($equip_id, $company_id) {
        $this->data['section_title'] = 'Edit Equipment';
        $this->data['equip_detail'] = $equip_detail = $this->common->select_data_by_id('equipment', 'id', $equip_id, '*', array());
        if (empty($equip_detail)) {
            $this->session->set_flashdata('error', 'Error Ouccrred. Try Again!');
            redirect('Company/equipment/' . $company_id, 'refresh');
        }
       //some other code
        $this->load->view('company/edit_equip', $this->data);
    }
</code>```

this is a function of my Equipment class. Now when I call below url like,
http://localhost/scale/Equipment/edit_equip/1/2

then edit view will open correctly. but now when I press F5 button or browser refresh button then it is showing "Error Ouccrred. Try Again!" flash message which I have set in above if condition. I am not understand why this is happening, because $equip_detail contains data and I have also try to die in it but it is not going into if which is correct so why only $this->session->set_flashdata('error', 'Error Ouccrred. Try Again!');
is providing effect?

in conclusion my code is not running if block but if i press F5 or browser refresh button after first time my view is loaded it is showing me error message which is set in if condition, but my code is not going to it otherwise it has to redirect but it is loading view page with flash message.

I have only set this flash message at only one place as per above code. I am using codeigniter 3.1.6

Please can anyone explain me this?

答:
This isn't the solution, but more of an investigation to satisfy yourself how things are working...

So when things go "screwy", its always a good time to go back to basics. So seeing as you are so convinced your code is executing correctly but giving you unexpected results here is some test code just to check out the behavior of flashdata.

Flash_session_test.php

```<code>class Flash_session_test extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper('url');
    }

    public function index()
    {
        echo "This is " . __METHOD__;
        $this->test_display();
    }

    /**
     * Mockup code derived from sample code
     *  to test the behavior of the flash data.
     *
     * @param $equip_id
     */
    public function edit_equip($equip_id)
    {
        echo "This is " . __METHOD__;

        // Set up our Fail / Pass for the If statement below.
        if (isset($equip_id)) {
            if ($equip_id == 'fail') {
                // Create a Fail Condition
                $equip_detail = null;
            } else {
                // Create a Pass Condition
                $equip_detail = array('fred' => 1);
            }
        }
        // The code we are testing.
        if (empty($equip_detail)) {
            $this->session->set_flashdata('error', 'Error Occurred. Try Again!');
            // Redirect and display the flashdata error message
            redirect('/flash_session_test', 'refresh');
        }
        $this->test_display();
    }

    /**
     * Our Test "View" put here for simplicity
     */
    public function test_display()
    {
        echo '<br>';
        echo '<a href="/flash_session_test/edit_equip/pass" >Click here to Create a PASS</a>';
        echo '<br>';
        echo '<a href="/flash_session_test/edit_equip/fail" >Click here to Create an ERROR</a>';
        echo '<br>';
        echo '<br>';
        // Only display the message if we have one
        $error = $this->session->flashdata('error');
        if ($error === null) { // If null, then It doesn't exist
            echo '<div style="color:green">';
            echo "Not An Error in Sight!";
            echo '</div>';
        } else {
            echo '<div style="color:red">';
            echo $this->session->flashdata('error');
            echo '</div>';
            echo "Now Refresh the page!";
        }
    }
}
</code>```

Note: This will run standalone, without relying on your existing code.

Body:
I have found very strange behavior of "if" condition and session flashdata in codeigniter,

public function edit_equip($equip_id, $company_id) {
        $this->data['section_title'] = 'Edit Equipment';
        $this->data['equip_detail'] = $equip_detail = $this->common->select_data_by_id('equipment', 'id', $equip_id, '*', array());
        if (empty($equip_detail)) {
            $this->session->set_flashdata('error', 'Error Ouccrred. Try Again!');
            redirect('Company/equipment/' . $company_id, 'refresh');
        }
       //some other code
        $this->load->view('company/edit_equip', $this->data);
    }

this is a function of my Equipment class. Now when I call below url like,
http://localhost/scale/Equipment/edit_equip/1/2

then edit view will open correctly. but now when I press F5 button or browser refresh button then it is showing "Error Ouccrred. Try Again!" flash message which I have set in above if condition. I am not understand why this is happening, because $equip_detail contains data and I have also try to die in it but it is not going into if which is correct so why only $this->session->set_flashdata('error', 'Error Ouccrred. Try Again!');
is providing effect?

in conclusion my code is not running if block but if i press F5 or browser refresh button after first time my view is loaded it is showing me error message which is set in if condition, but my code is not going to it otherwise it has to redirect but it is loading view page with flash message.

I have only set this flash message at only one place as per above code. I am using codeigniter 3.1.6

Please can anyone explain me this?

Body:
This isn't the solution, but more of an investigation to satisfy yourself how things are working...

So when things go "screwy", its always a good time to go back to basics. So seeing as you are so convinced your code is executing correctly but giving you unexpected results here is some test code just to check out the behavior of flashdata.

Flash_session_test.php

class Flash_session_test extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper('url');
    }

    public function index()
    {
        echo "This is " . __METHOD__;
        $this->test_display();
    }

    /**
     * Mockup code derived from sample code
     *  to test the behavior of the flash data.
     *
     * @param $equip_id
     */
    public function edit_equip($equip_id)
    {
        echo "This is " . __METHOD__;

        // Set up our Fail / Pass for the If statement below.
        if (isset($equip_id)) {
            if ($equip_id == 'fail') {
                // Create a Fail Condition
                $equip_detail = null;
            } else {
                // Create a Pass Condition
                $equip_detail = array('fred' => 1);
            }
        }
        // The code we are testing.
        if (empty($equip_detail)) {
            $this->session->set_flashdata('error', 'Error Occurred. Try Again!');
            // Redirect and display the flashdata error message
            redirect('/flash_session_test', 'refresh');
        }
        $this->test_display();
    }

    /**
     * Our Test "View" put here for simplicity
     */
    public function test_display()
    {
        echo '<br>';
        echo '<a href="/flash_session_test/edit_equip/pass" >Click here to Create a PASS</a>';
        echo '<br>';
        echo '<a href="/flash_session_test/edit_equip/fail" >Click here to Create an ERROR</a>';
        echo '<br>';
        echo '<br>';
        // Only display the message if we have one
        $error = $this->session->flashdata('error');
        if ($error === null) { // If null, then It doesn't exist
            echo '<div style="color:green">';
            echo "Not An Error in Sight!";
            echo '</div>';
        } else {
            echo '<div style="color:red">';
            echo $this->session->flashdata('error');
            echo '</div>';
            echo "Now Refresh the page!";
        }
    }
}

Note: This will run standalone, without relying on your existing code.


问:
Google Translate tool will not make translation preference persist across multiple pages
Google Translate Tools let you embed a translation dropdown in your website that lets users translate pages. However, this preference is only for that page...as soon as they click to a different page on the site, they have to re-select the language.

Any ideas on how to make this preference persistent? Is there an option for Google Translate that I'm missing (it seems like this would be an extremely common use case)? Or am I stuck using jQuery to set a cookie and then trigger a click event for the desired <option> on each page load?

答:
From google translate support:

Translate an entire web page directly from Google Translate, simply by entering its address (e.g. "www.google.com") into the input box and clicking Translate.

It means going on http://translate.google.com/ and doing that. I believe it even gives a different translation from the Tools.

ContentLicense: CC BY-SA 2.5


问:
Variable in function undefined / Javascript
I can't get my function to work properly.

This ist my code:

```<code>function createPlayer() {
  var nation = new Array("Germany", "USA", "France", "Spain", "Belgium", "Nigeria", "Camerun", "Egypt", "Morocco", "SouthAfrica");

  var deFN = new Array("Andreas", "Daniel", "Kevin", "Lukas", "Timo", "Lennard");
  var usFN = new Array("Tyler", "Ron");
  var frFN = new Array("Lucas", "Mathis");

  var deLN = new Array("Müller", "Meyer", "Ries", "Kellermann", "Werner", "König");
  var usLN = new Array("Stinson", "Wellington", "Booker", "James", "Owen", "Nolan");
  var frLN = new Array("Lefevre", "Bonnet");

  var nationPlayer = nation[Math.floor(Math.random() * nation.length)];
  var namePlayer = new Array("");

  if (nationPlayer == Germany) {
    var namePlayer = deFN[Math.floor(Math.random() * deFN.length)] + deLN[Math.floor(Math.random() * deLN.length)];
  } else if (nationPlayer == USA) {
    var namePlayer = usFN[Math.floor(Math.random() * usFN.length)] + usLN[Math.floor(Math.random() * usLN.length)];

  } else if (nationPlayer == France) {
    var namePlayer = frFN[Math.floor(Math.random() * frFN.length)] + frLN[Math.floor(Math.random() * frLN.length)];

  } else {
    var namePlayer = "Other nation"
  }

  console.log(namePlayer);
}
</code>```

First this function should pick one random nation of the nation array.
Then if the random picker picked one of these 3 nations, it should connect the nation, the first name and the last name to the variable Array "namePlayer"

(Sorry I'm a Newbie)

答:
You need to replace nationPlayer == Germany to nationPlayer == "Germany", because variable Germany is not defined.

function createPlayer() {

  var nation = new Array("Germany","USA","France","Spain","Belgium","Nigeria","Camerun","Egypt","Morocco","SouthAfrica");

  var deFN = new Array("Andreas","Daniel","Kevin","Lukas","Timo","Lennard");
  var usFN = new Array("Tyler", "Ron");
  var frFN = new Array("Lucas" , "Mathis");

  var deLN = new Array("Müller","Meyer","Ries","Kellermann","Werner","König");
  var usLN = new Array("Stinson","Wellington","Booker","James","Owen","Nolan");
  var frLN = new Array("Lefevre", "Bonnet");

  var nationPlayer = nation[Math.floor(Math.random() * nation.length)];
  var namePlayer;

  if (nationPlayer == "Germany") {
    namePlayer = deFN[Math.floor(Math.random() * deFN.length)] + deLN[Math.floor(Math.random() * deLN.length)];
  } else if (nationPlayer == "USA") {
    namePlayer = usFN[Math.floor(Math.random() * usFN.length)] + usLN[Math.floor(Math.random() * usLN.length)];
  } else if (nationPlayer == "France") {
    namePlayer = frFN[Math.floor(Math.random() * frFN.length)] + frLN[Math.floor(Math.random() * frLN.length)];
  } else {
    namePlayer = "Other nation"
  }
  console.log(namePlayer);
}

createPlayer()```

Body:
I can't get my function to work properly.

This ist my code:

function createPlayer() {
  var nation = new Array("Germany", "USA", "France", "Spain", "Belgium", "Nigeria", "Camerun", "Egypt", "Morocco", "SouthAfrica");

  var deFN = new Array("Andreas", "Daniel", "Kevin", "Lukas", "Timo", "Lennard");
  var usFN = new Array("Tyler", "Ron");
  var frFN = new Array("Lucas", "Mathis");

  var deLN = new Array("Müller", "Meyer", "Ries", "Kellermann", "Werner", "König");
  var usLN = new Array("Stinson", "Wellington", "Booker", "James", "Owen", "Nolan");
  var frLN = new Array("Lefevre", "Bonnet");

  var nationPlayer = nation[Math.floor(Math.random() * nation.length)];
  var namePlayer = new Array("");

  if (nationPlayer == Germany) {
    var namePlayer = deFN[Math.floor(Math.random() * deFN.length)] + deLN[Math.floor(Math.random() * deLN.length)];
  } else if (nationPlayer == USA) {
    var namePlayer = usFN[Math.floor(Math.random() * usFN.length)] + usLN[Math.floor(Math.random() * usLN.length)];

  } else if (nationPlayer == France) {
    var namePlayer = frFN[Math.floor(Math.random() * frFN.length)] + frLN[Math.floor(Math.random() * frLN.length)];

  } else {
    var namePlayer = "Other nation"
  }

  console.log(namePlayer);
}

First this function should pick one random nation of the nation array.
Then if the random picker picked one of these 3 nations, it should connect the nation, the first name and the last name to the variable Array "namePlayer"

(Sorry I'm a Newbie)


问:
Why can't I `tail` the result of a `tail` on a Perl 6 list?
Why can't I tail the result of a tail? I can call head on the sequence tail returns (and other variations), but a tail on a tail doesn't work (in 2017.10):

```<code>> my $list = <a b c d e f g h i j>;
(a b c d e f g h i j)
> $list.head(5).head
a
> $list.head(5).tail
e
> $list.tail(5).head
f
</code>```

This one fails:

```<code>> $list.tail(5).tail
Nil
</code>```

But throwing a list in there works:

```<code>> $list.tail(5).list.tail
j
</code>```

答:
This is a bug.

The .count-only optimization method for List.iterator did not account for the fact that the iterator may already be partially consumed (here, by the first .tail call) when the method is called and, as timotimo++ pointed out in the comments, kept always returning the original length. The argless .tail then used that method, hitting the bug.

This is now fixed on 2017.11-76-gf70e20b Rakudo

Unless I'm misunderstanding iterator protocol, the same bug was present in quite a few other iterators, so thanks for finding this hive!

Body:
Why can't I tail the result of a tail? I can call head on the sequence tail returns (and other variations), but a tail on a tail doesn't work (in 2017.10):

> my $list = ;
(a b c d e f g h i j)
> $list.head(5).head
a
> $list.head(5).tail
e
> $list.tail(5).head
f

This one fails:

> $list.tail(5).tail
Nil

But throwing a list in there works:

> $list.tail(5).list.tail
j


问:
Random Numbers; Converting list to string
My assignment is to make a random number generator in the form of a coin flip.  As this is somewhat of a starting class, at this point of the term, I am only allowed to use certain built in functions.  I was aided by a link the instructor gave us that helped me understand the current code I'm using to generate that list. Here is the code used to generate the list:

```<code>userin = int(input("enter the number of coin flips: ")
coin = ['H', 'T']
userlist = (random.choices((coin), k=userin))
</code>```

Now, I was storing the randomly generated list into userlist because I am to also print it as a list.  Seems simple enough.  I've tried printing it as list, but I'm assuming since I have it coded this way, it will always print it in list format.  I know this is simple, and the goal after this will take even more work, but my mind is stuck on this. I will eventually have to count how many "heads" and "tails" were generated, thus the string.

答:
I think what you are looking for is something along the lines of this:

```<code>import random

try:
    userin = int(input("Enter the number of desired coin flips: "))

except ValueError:
    print("Invalid Input")

coin = ['H', 'T']
userlist =(random.choices((coin), k=userin))

print('You flipped '  + str(userlist.count('H')) + ' Heads and ' + str(userlist.count('T')) + ' Tails.')

print(userlist)

k=""

for x in range(0, len(userlist)):

    k=str(k) +"" + str(userlist.pop())

print(k)
</code>```

This is assuming you just want to print the results of the coin flips. Added a try loop at the start in case an integer is not entered. Make sure to import random so that it works as well, also added a missing parentheses at the end of your input statement. Used the list.count() function to find the number of T's or H's in userlist. Also just using str() in your print should work. Hopefully this will serve your purposes.

Body:
My assignment is to make a random number generator in the form of a coin flip.  As this is somewhat of a starting class, at this point of the term, I am only allowed to use certain built in functions.  I was aided by a link the instructor gave us that helped me understand the current code I'm using to generate that list. Here is the code used to generate the list:

userin = int(input("enter the number of coin flips: ")
coin = ['H', 'T']
userlist = (random.choices((coin), k=userin))

Now, I was storing the randomly generated list into userlist because I am to also print it as a list.  Seems simple enough.  I've tried printing it as list, but I'm assuming since I have it coded this way, it will always print it in list format.  I know this is simple, and the goal after this will take even more work, but my mind is stuck on this. I will eventually have to count how many "heads" and "tails" were generated, thus the string.

Body:
I think what you are looking for is something along the lines of this:

import random

try:
    userin = int(input("Enter the number of desired coin flips: "))

except ValueError:
    print("Invalid Input")

coin = ['H', 'T']
userlist =(random.choices((coin), k=userin))

print('You flipped '  + str(userlist.count('H')) + ' Heads and ' + str(userlist.count('T')) + ' Tails.')

print(userlist)

k=""

for x in range(0, len(userlist)):

    k=str(k) +"" + str(userlist.pop())

print(k)

This is assuming you just want to print the results of the coin flips. Added a try loop at the start in case an integer is not entered. Make sure to import random so that it works as well, also added a missing parentheses at the end of your input statement. Used the list.count() function to find the number of T's or H's in userlist. Also just using str() in your print should work. Hopefully this will serve your purposes.


问:
Passing a hash as an initial value when creating an object
I am making a Temperature class with instance methods that convert the temperature from f to c, and vice-versa. A test case is:

```<code>Temperature.new(:f => 32).in_celsius #=> 0
</code>```

I thought that passing :f => 32 would give the conversion. I don't know how to extract the value 32 from the hash :f => 32. I want to extract that so that I can convert that number either into f or c.

Below is my answer code.

```<code>class Temperature
  def initialize(f = 0, c = 0)
    @f = f
    @c = c
  end

  def in_fahrenheit
    c = @c * 1.8
    c += 32
    @f = c.floor
    @f
  end

  def in_celsius
    f = @f - 32
    f /= 1.8
    @c = f.floor
    @c
  end

  def fahrenheit
    @f
  end

  def celsius
    @c
  end
end
</code>```

I am not familiar with hashes passed as initial values when creating objects. I would appreciate any advice.

答:
Your initialize method is looking for two parameters, but your input contains only one, the hash. Here's how you can handle a hash containing Fahrenheit:

```<code>  def initialize(temp)
    @f = temp[:f]
  end
</code>```

If you want to handle input in either F or C, I'll leave that as an exercise for you.

Body:
I am making a Temperature class with instance methods that convert the temperature from f to c, and vice-versa. A test case is:

Temperature.new(:f => 32).in_celsius #=> 0

I thought that passing :f => 32 would give the conversion. I don't know how to extract the value 32 from the hash :f => 32. I want to extract that so that I can convert that number either into f or c.

Below is my answer code.

class Temperature
  def initialize(f = 0, c = 0)
    @f = f
    @c = c
  end

  def in_fahrenheit
    c = @c * 1.8
    c += 32
    @f = c.floor
    @f
  end

  def in_celsius
    f = @f - 32
    f /= 1.8
    @c = f.floor
    @c
  end

  def fahrenheit
    @f
  end

  def celsius
    @c
  end
end

I am not familiar with hashes passed as initial values when creating objects. I would appreciate any advice.

Body:
Your initialize method is looking for two parameters, but your input contains only one, the hash. Here's how you can handle a hash containing Fahrenheit:

  def initialize(temp)
    @f = temp[:f]
  end

If you want to handle input in either F or C, I'll leave that as an exercise for you.


问:
JQuery to get input field value based on label

I need to copy the value of the first input box to the second input box.  The id and name of these input boxes are coming from tables.  What is fix will be the labels like 'Code' and 'Copy Code'

```<code><label>Code</label>
<input type="text" value="1234"  id="custcode_1" />

<label>Copy Code</label>
<input type="text" value=""  id="custcode_2" />
</code>```

For normal scenario it will be just

```<code>$('#custcode_2').val($('#custcode_1').val());
</code>```

But the id or name are generated on the fly so this is not possible.  How to achieve this using labels of the input boxes.

Thanks for the help.

答:
i think you can store the data value at data- attributes:

```<code><label id="code" data-value="1234">
<label id="copy_code" data-value="">
</code>```

and then copy the value of code to copy_code using

```<code>$('#copy_code').data('value', $('#code').data('value'))
</code>```

Body:
I need to copy the value of the first input box to the second input box.  The id and name of these input boxes are coming from tables.  What is fix will be the labels like 'Code' and 'Copy Code'

Code
<input type="text" value="1234"  id="custcode_1" />

Copy Code
<input type="text" value=""  id="custcode_2" />

For normal scenario it will be just

$('#custcode_2').val($('#custcode_1').val());

But the id or name are generated on the fly so this is not possible.  How to achieve this using labels of the input boxes.

Thanks for the help.

Body:
i think you can store the data value at data- attributes:

<label id="code" data-value="1234">
<label id="copy_code" data-value="">

and then copy the value of code to copy_code using

$('#copy_code').data('value', $('#code').data('value'))


问:
determining whether a window is in desktop bounds c++
I wrote some code to determinate whether a certain window is inside the desktop bounds.

Somehow, it doesn't work. For every window, regardless whether it is inside or outside the desktop, false is returned. Something is terribly wrong here, but after staring at this piece of code for 3 hours now, I still don't know where the problem is. If I try to read a RECT struct from the pointer sent in the PMSG's WPARAM, I get a AccessViolationException. Why is this happening?

My code look like this, and always returns false:

```<code>static bool IsInBounds(HWND window)
{
    DEVMODE d;
    d.dmSize = sizeof(DEVMODE);
    BOOL b = EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &d);
    if(b == FALSE)
    {
        PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"FMSG"), (WPARAM)window, NULL);
    }
    RECT R;
    GetWindowRect(window, &R);
    POINT p = POINT();
    p.x = (LONG)d.dmPelsWidth;
    p.y = (LONG)d.dmPelsHeight;
    PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"PMSG"), (WPARAM)&R, d.dmPelsWidth);
    if(R.right < 0 || R.bottom < 0 || R.left > (LONG)d.dmPelsWidth || R.top > (LONG)d.dmPelsHeight)
    {
        return false;
    }
    return true;
}
</code>```

EDIT:
after calling IsInBounds, which returned an error number 1400 (Invalid window handle), but before returning from the hook callback, I called IsWindow(window), to see, if my handle is still valid. The truth is: it is in deed a valid handle! How can it be that GetWindowRect says its an invalid handle?

EDIT:
I tried MonitorFromWindow as sujested, but it returned NULL, and calling GetLastError resulted in error no. 1400, which is already familiar to me. Looks like MonitorFromWindow implicitly calls GetWindowRect. I don't care about the size, but is there another way to get window coordinates from a handle?

答:
(1) Straightforward

```<code>RECT rDesk = { 0 };
GetBystemParametersInfo(SPI_GETWORKAREA, 0, &rDesk, 0);
RECT rWnd;
GetWindowRect(wnd, &rWnd);
POINT pttl = { rWnd.left, rWnd.top);
POINT ptbr = { rWnd.right, rWnd.bottom);
if (PtInRect(&rDesk, pttl) && PtInRect(&rDesk, ptbr))
   // ....
</code>```

SPI_GETWORKAREA queries the desktop area (as opposed to the screen, which includes the Taskbar etc.)
Replace GetSystemParametersInfo with GetMonitorInfo  to support multiple monitors.

(2) GetWindowRect

Does the target window belong to an elevated process, or a process running in a different security context?

(3) Other remarks

For RegisterMessage, don't use such non-unique names. After all, it works systemwide. I make a point of embedding a GUID in their name.

PostMessage has already been mentioned: it's asynchronous, and you can pass pointers cross-process.

I don't see why you need to pass your window handle to some other, unrelated window.

Body:
I wrote some code to determinate whether a certain window is inside the desktop bounds.

Somehow, it doesn't work. For every window, regardless whether it is inside or outside the desktop, false is returned. Something is terribly wrong here, but after staring at this piece of code for 3 hours now, I still don't know where the problem is. If I try to read a RECT struct from the pointer sent in the PMSG's WPARAM, I get a AccessViolationException. Why is this happening?

My code look like this, and always returns false:

static bool IsInBounds(HWND window)
{
    DEVMODE d;
    d.dmSize = sizeof(DEVMODE);
    BOOL b = EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &d);
    if(b == FALSE)
    {
        PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"FMSG"), (WPARAM)window, NULL);
    }
    RECT R;
    GetWindowRect(window, &R);
    POINT p = POINT();
    p.x = (LONG)d.dmPelsWidth;
    p.y = (LONG)d.dmPelsHeight;
    PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"PMSG"), (WPARAM)&R, d.dmPelsWidth);
    if(R.right < 0 || R.bottom < 0 || R.left > (LONG)d.dmPelsWidth || R.top > (LONG)d.dmPelsHeight)
    {
        return false;
    }
    return true;
}

EDIT:
after calling IsInBounds, which returned an error number 1400 (Invalid window handle), but before returning from the hook callback, I called IsWindow(window), to see, if my handle is still valid. The truth is: it is in deed a valid handle! How can it be that GetWindowRect says its an invalid handle?

EDIT:
I tried MonitorFromWindow as sujested, but it returned NULL, and calling GetLastError resulted in error no. 1400, which is already familiar to me. Looks like MonitorFromWindow implicitly calls GetWindowRect. I don't care about the size, but is there another way to get window coordinates from a handle?

Body:
(1) Straightforward

RECT rDesk = { 0 };
GetBystemParametersInfo(SPI_GETWORKAREA, 0, &rDesk, 0);
RECT rWnd;
GetWindowRect(wnd, &rWnd);
POINT pttl = { rWnd.left, rWnd.top);
POINT ptbr = { rWnd.right, rWnd.bottom);
if (PtInRect(&rDesk, pttl) && PtInRect(&rDesk, ptbr))
   // ....

SPI_GETWORKAREA queries the desktop area (as opposed to the screen, which includes the Taskbar etc.)
Replace GetSystemParametersInfo with GetMonitorInfo  to support multiple monitors.

(2) GetWindowRect

Does the target window belong to an elevated process, or a process running in a different security context?

(3) Other remarks

For RegisterMessage, don't use such non-unique names. After all, it works systemwide. I make a point of embedding a GUID in their name.

PostMessage has already been mentioned: it's asynchronous, and you can pass pointers cross-process.

I don't see why you need to pass your window handle to some other, unrelated window.


问:
Add labels to navigation bar
I am adding a calendar to my app and thought it would be cool to mimic the format of standard iOS Calendar app as per weekday labels:

In the Calendar app, these labels (S,M,T,W,T,F,S) seem to be integrated into the navigation bar, so I was wondering if there is a way to implement this or if this is something Apple left to themselves (as there seems to be no standard way to add anything but bar button items). Mind you, these labels should be dynamic - e.g. rearrange in case of day 2 as firstWeekDay for certain Locale.

答:
Apple proposes not to resize navigationBar itself, but remove shadow from bar and add custom view under your navigationBar.

Please refer the apple recommended approach for extended navigation bars here - https://developer.apple.com/library/content/samplecode/NavBar/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007418-Intro-DontLinkElementID_2

And your particular scenario - https://developer.apple.com/library/content/samplecode/NavBar/Listings/NavBar_ExtendedNavBar_ExtendedNavBarViewController_swift.html#//apple_ref/doc/uid/DTS40007418-NavBar_ExtendedNavBar_ExtendedNavBarViewController_swift-DontLinkElementID_13

Title: Add labels to navigation bar


问:
Setting getSheetbyName according to cell value
I'm not much of a programmer but managed to cobbled together a script and can't seem to get the last part working. I want to pass activelog string into log and feel like it's a simple syntax issue I'm overlooking:

```<code>var activelog = e.source.getSheetByName("SHEET1").getRange("A1").getValue();
var log = e.source.getSheetByName(activelog);
</code>```

Activelog gets the value of dropdown menu cell A1 on Sheet1 that contains list of all the relevant sheets. The script then copies down a formula in column C of whichever sheet is selected if something is typed in B1 of Sheet1. Right now specifying the sheetname "LOG" works fine:

```<code>function onEdit(e) {
    var activelog = e.source.getSheetByName("SHEET1").getRange("A1").getValue();
    var log = e.source.getSheetByName("LOG");
    var lr = log.getLastRow();
    var fdr = log.getRange(1,23,lr);
    var formula = "";

    if (e.source.getActiveSheet().getName() !== "SHEET1" || e.range.rowStart != 1 || e.range.columnStart != 2 ) return
    log.getRange("C1").setFormula(formula);log.getRange("C1").copyTo(fdr);
}
</code>```

答:
You are missing a ; after your return in the last line.
Right now if the range is incorrect and it enters your condition, it doesreturn log.getRange("C1").setFormula(formula);

And if it doesn't enter the if, all it does is log.getRange("C1").copyTo(fdr); without setting the formula first

Body:
I'm not much of a programmer but managed to cobbled together a script and can't seem to get the last part working. I want to pass activelog string into log and feel like it's a simple syntax issue I'm overlooking:

var activelog = e.source.getSheetByName("SHEET1").getRange("A1").getValue();
var log = e.source.getSheetByName(activelog);

Activelog gets the value of dropdown menu cell A1 on Sheet1 that contains list of all the relevant sheets. The script then copies down a formula in column C of whichever sheet is selected if something is typed in B1 of Sheet1. Right now specifying the sheetname "LOG" works fine:

function onEdit(e) {
    var activelog = e.source.getSheetByName("SHEET1").getRange("A1").getValue();
    var log = e.source.getSheetByName("LOG");
    var lr = log.getLastRow();
    var fdr = log.getRange(1,23,lr);
    var formula = "";

    if (e.source.getActiveSheet().getName() !== "SHEET1" || e.range.rowStart != 1 || e.range.columnStart != 2 ) return
    log.getRange("C1").setFormula(formula);log.getRange("C1").copyTo(fdr);
}


问:
How do i get the value of dynamic input fields from javascript function?
I am trying to make a dynamic form using a javascript function, but i'm amateur on this, so i'm not sure how to collect the inputs values, considering is a dynamic function. This is the HTML part:

```<code><div>
   Amount of people: <input type="text" id="member" name="member" value=""><br />
   <button id="btn" onclick="addinputFields()">Show</button>
</div>
<form action="{{ url_for('red_preferente') }}" method="post">
     <div id="mydiv"/><br />
     <input type="submit" value="Quote"/>
</form>
</code>```

And this is the JS function "addinputFields", im calling above

```<code>function addinputFields(){
var number = document.getElementById("member").value;

  for (i=0;i<number;i++){
      var campo_1 = document.createElement("output");
      campo_1.type = "text";
      campo_1.value = " Nombre: ";
      mydiv.appendChild(campo_1);

      var nombre = document.createElement("input");
      nombre.type = "text";
      nombre.id = "name"
      mydiv.appendChild(nombre);

      var campo_2 = document.createElement("output");
      campo_2.type = "text";
      campo_2.value = " Edad: ";
      mydiv.appendChild(campo_2);

      var edad = document.createElement("input");
      edad.type = "text";
      edad.id = "age"
      mydiv.appendChild(edad);

      var campo_3 = document.createElement("output");
      campo_3.type = "text";
      campo_3.value = " Modalidad: ";
      mydiv.appendChild(campo_3);

      var modalidades = ["Titular","Asegurado","Dependiente"];
      var listado = document.createElement("select");
      listado.id = "mySelect";

      for (var x = 0; x < modalidades.length; x++) {
          var option = document.createElement("option");
          option.value = modalidades[x];
          option.text = modalidades[x];
          listado.appendChild(option);
      }
      mydiv.appendChild(listado);
  }}
</code>```

I'm trying to use "document.getElementById('mydiv').value" to have the input value, but i receive none value

I need each one of the input value of vars: nombre, edad, listado. Any idea?

Thanks a lot for help!

答:
There are many possible causes of your problem. Because inputs are strings you should cast your input using

```<code>var number = parseInt(document.getElementById("member").value);
</code>```

The problem seems to lie around the createElement() statements. Your <variable name>.value isn't right. That only works for the value of an <input> or <textarea>. Simpler would have been to get rid of the createElement()s. The

```<code>var campo_1 = document.createElement("output");
campo_1.type = "text";
campo_1.value = " Nombre: ";
mydiv.appendChild(campo_1);
</code>```

lines could have easily been re-written

```<code>mydiv.innerHTML += "Nombre: ";
</code>```

Body:
I am trying to make a dynamic form using a javascript function, but i'm amateur on this, so i'm not sure how to collect the inputs values, considering is a dynamic function. This is the HTML part:

   Amount of people: <input type="text" id="member" name="member" value="">

   <button id="btn" onclick="addinputFields()">Show</button>

<form action="{{ url_for('red_preferente') }}" method="post">

     <input type="submit" value="Quote"/>
</form>

And this is the JS function "addinputFields", im calling above

function addinputFields(){
var number = document.getElementById("member").value;

  for (i=0;i<number;i++){
      var campo_1 = document.createElement("output");
      campo_1.type = "text";
      campo_1.value = " Nombre: ";
      mydiv.appendChild(campo_1);

      var nombre = document.createElement("input");
      nombre.type = "text";
      nombre.id = "name"
      mydiv.appendChild(nombre);

      var campo_2 = document.createElement("output");
      campo_2.type = "text";
      campo_2.value = " Edad: ";
      mydiv.appendChild(campo_2);

      var edad = document.createElement("input");
      edad.type = "text";
      edad.id = "age"
      mydiv.appendChild(edad);

      var campo_3 = document.createElement("output");
      campo_3.type = "text";
      campo_3.value = " Modalidad: ";
      mydiv.appendChild(campo_3);

      var modalidades = ["Titular","Asegurado","Dependiente"];
      var listado = document.createElement("select");
      listado.id = "mySelect";

      for (var x = 0; x < modalidades.length; x++) {
          var option = document.createElement("option");
          option.value = modalidades[x];
          option.text = modalidades[x];
          listado.appendChild(option);
      }
      mydiv.appendChild(listado);
  }}

I'm trying to use "document.getElementById('mydiv').value" to have the input value, but i receive none value

I need each one of the input value of vars: nombre, edad, listado. Any idea?

Thanks a lot for help!

Body:
There are many possible causes of your problem. Because inputs are strings you should cast your input using

var number = parseInt(document.getElementById("member").value);

The problem seems to lie around the createElement() statements. Your <variable name>.value isn't right. That only works for the value of an <input> or <textarea>. Simpler would have been to get rid of the createElement()s. The

var campo_1 = document.createElement("output");
campo_1.type = "text";
campo_1.value = " Nombre: ";
mydiv.appendChild(campo_1);

lines could have easily been re-written

mydiv.innerHTML += "Nombre: ";


问:
Calculate each row values python

I want to calculate average of each row and result them in another new column at the each of the DataFrame. This is small sample of data that I am having
I am not sure how I should write a function that can calculate row by row for it since my actual data will have something like 600K rows.
</p>

Title: Calculate each row values python

Body:
Try this,

 df = pd.DataFrame([[2,1],[3,2],[4,3],[5,4]],columns=['B','A'],index=[1,2,3,4])
 df['mean'] = df.mean(axis=1)
 df
 Output:
    B  A  mean
 1  2  1   1.5
 2  3  2   2.5
 3  4  3   3.5
 4  5  4   4.5


问:
Protocol Enumerable not implemented for MyApp.MyStruct
I'm trying to create a join table, and I'm running into this error while trying to build a struct.

ERROR

protocol Enumerable not implemented for %Statcasters.UsersLeagues{meta: #Ecto.Schema.Metadata<:built, "users_leagues">, commissioner: nil, id: nil, inserted_at: nil, league: #Ecto.Association.NotLoaded, league_id: nil, updated_at: nil, user: #Ecto.Association.NotLoaded, user_id: nil}. This protocol is implemented for: DBConnection.PrepareStream, DBConnection.Stream, Date.Range, Ecto.Adapters.SQL.Stream, File.Stream, Function, GenEvent.Stream, HashDict, HashSet, IO.Stream, List, Map, MapSet, Postgrex.Stream, Range, Stream, Timex.Interval

It's failing on this line:

LEAGUE CONTROLLER:

```<code>  def new(conn, _params) do
    changeset = League.changeset(%League{users_leagues: %UsersLeagues{}})

    render(conn, "new.html", changeset: changeset)
  end
</code>```

I have a has_many through relationship with leagues and users. The join table is the users_leages table and that is what I'm trying to create in the new action. But when I try to load the new page. it breaks with this error.

答:
The error means that Ecto tried to use the value of the field users_leagues as an Enumerable which %UsersLeagues{} isn't. Since the field is a has_many field, a record can have many of them and it needs to be a list (or more specifically an Enumerable) of %UsersLeagues{} structs.

You can fix this by wrapping %UsersLeagues{} in a list:

```<code>changeset = League.changeset(%League{users_leagues: [%UsersLeagues{}]})
</code>```

Body:
I'm trying to create a join table, and I'm running into this error while trying to build a struct.

ERROR

protocol Enumerable not implemented for %Statcasters.UsersLeagues{meta: #Ecto.Schema.Metadata<:built, "users_leagues">, commissioner: nil, id: nil, inserted_at: nil, league: #Ecto.Association.NotLoaded, league_id: nil, updated_at: nil, user: #Ecto.Association.NotLoaded, user_id: nil}. This protocol is implemented for: DBConnection.PrepareStream, DBConnection.Stream, Date.Range, Ecto.Adapters.SQL.Stream, File.Stream, Function, GenEvent.Stream, HashDict, HashSet, IO.Stream, List, Map, MapSet, Postgrex.Stream, Range, Stream, Timex.Interval

It's failing on this line:

LEAGUE CONTROLLER:

  def new(conn, _params) do
    changeset = League.changeset(%League{users_leagues: %UsersLeagues{}})

    render(conn, "new.html", changeset: changeset)
  end

I have a has_many through relationship with leagues and users. The join table is the users_leages table and that is what I'm trying to create in the new action. But when I try to load the new page. it breaks with this error.

Body:
The error means that Ecto tried to use the value of the field users_leagues as an Enumerable which %UsersLeagues{} isn't. Since the field is a has_many field, a record can have many of them and it needs to be a list (or more specifically an Enumerable) of %UsersLeagues{} structs.

You can fix this by wrapping %UsersLeagues{} in a list:

changeset = League.changeset(%League{users_leagues: [%UsersLeagues{}]})


问:
Using another classes function in c#
im trying to be able to call the function from the dieclass and use the roll number in the matchplay class... is this possible?

```<code>public class DieClass
{
    public void DiceRoll(int min, int max)
    {
        Random random = new Random();

        int roll1 = random.Next(0, 6);
        int roll2 = random.Next(0, 6);
        int roll3 = random.Next(0, 6);
    }
}

public class MatchPlay
{
    public void Match()
    {
        DieClass.DiceRoll();

        Console.WriteLine("Starting Match Play...");
        Console.WriteLine();
        Console.WriteLine("Round One");
        Console.WriteLine("Your first dice is [0]", roll1);
        Console.WriteLine("Your second dice is [0]", roll2);
        Console.WriteLine("Your third dice is [0]", roll3);
    }
}
</code>```

}

答:
Either you need to make DiceRoll a static method, or create an instance of DieClass and call your method through that.

For example, you may declare your method as

```<code>public static void DiceRoll(int min, int max)
</code>```

Or you can instantiate an object like:

```<code>DieClass dice = new DieClass();

dice.DiceRoll(0, 6);
</code>```

That being said, you have other problems with your DieClass class, the most obvious of which is you need a means of communicating the result back to the caller. The easiest approach would be to have DiceRoll() generate a single result and return that. Also, you've hardcoded 0 and 6 as your params to random.Next() despite the method expecting a pair of parameters min and max.

Title: Using another classes function in c#

Body:
im trying to be able to call the function from the dieclass and use the roll number in the matchplay class... is this possible?

public class DieClass
{
    public void DiceRoll(int min, int max)
    {
        Random random = new Random();

        int roll1 = random.Next(0, 6);
        int roll2 = random.Next(0, 6);
        int roll3 = random.Next(0, 6);
    }
}

public class MatchPlay
{
    public void Match()
    {
        DieClass.DiceRoll();

        Console.WriteLine("Starting Match Play...");
        Console.WriteLine();
        Console.WriteLine("Round One");
        Console.WriteLine("Your first dice is [0]", roll1);
        Console.WriteLine("Your second dice is [0]", roll2);
        Console.WriteLine("Your third dice is [0]", roll3);
    }
}

}

Body:
Either you need to make DiceRoll a static method, or create an instance of DieClass and call your method through that.

For example, you may declare your method as

public static void DiceRoll(int min, int max)

Or you can instantiate an object like:

DieClass dice = new DieClass();

dice.DiceRoll(0, 6);

That being said, you have other problems with your DieClass class, the most obvious of which is you need a means of communicating the result back to the caller. The easiest approach would be to have DiceRoll() generate a single result and return that. Also, you've hardcoded 0 and 6 as your params to random.Next() despite the method expecting a pair of parameters min and max.


问:
Javascript/CSS - animation duration in pixel per second
How can i set the duration of an transition/animation to pixel per second?

You see the two different wrappers, with a different total height depending on it's colored content. The total speed is the same, given from the css transition attribute, thats okay if you want several animations with the same duration. For a smoother look i want to set this transition/animation effect to pixel per second so it takes as long as many pixels there. More content = more pixel = longer animation.

How can i achieve this with vanilla javascript or even css?

var wrapper1 = document.getElementById('wrapper1');
var wrapper2 = document.getElementById('wrapper2');
var header1 = document.getElementById('header1');
var header2 = document.getElementById('header2');
var wrapper1CmputedHeight = wrapper1.scrollHeight;
var wrapper2CmputedHeight = wrapper2.scrollHeight;

header1.addEventListener('click', function() {
  if (wrapper1.style.height === '60px') {
    wrapper1.style.height = wrapper1CmputedHeight + 'px';
  } else {
    wrapper1.style.height = '60px';
  }
})

header2.addEventListener('click', function() {
  if (wrapper2.style.height === '60px') {
    wrapper2.style.height = wrapper2CmputedHeight + 'px';
  } else {
    wrapper2.style.height = '60px';
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper1,
#wrapper2 {
  background: #fff;
  border: 1px solid grey;
  overflow: hidden;
  transition: height .2s linear
}

#wrapper1 {
  margin-bottom: 40px
}

#header1,
#header2 {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer
}

#content1 {
  height: 20px;
  background: blue
}

#content2 {
  height: 600px;
  background: green
}</code>```

    header

    header

```

答:
The only way to do this with css transitions, is to dynamically calculate the duration of the transition using a little javascript. So, in your code, I would remove the duration for the transition rule in your css, i,e.

```<code>#wrapper1,
#wrapper2 {
  background: #fff;
  overflow: hidden;
  transition: height linear
}
</code>```

and I would instead set the duration in the click handler as follows:

```<code>header1.addEventListener('click', function () {
    if(wrapper1.style.height === '60px') {
    wrapper1.style.height = wrapper1CmputedHeight + 'px';
    wrapper1.style.transitionDuration=(wrapper1CmputedHeight/100)+"s";
  } else {
    wrapper1.style.height = '60px';
  }
})
</code>```

So in this case, I've used a speed of 100px per second (this is the /100 part in the above code).

Body:
How can i set the duration of an transition/animation to pixel per second?

You see the two different wrappers, with a different total height depending on it's colored content. The total speed is the same, given from the css transition attribute, thats okay if you want several animations with the same duration. For a smoother look i want to set this transition/animation effect to pixel per second so it takes as long as many pixels there. More content = more pixel = longer animation.

How can i achieve this with vanilla javascript or even css?

var wrapper1 = document.getElementById('wrapper1');
var wrapper2 = document.getElementById('wrapper2');
var header1 = document.getElementById('header1');
var header2 = document.getElementById('header2');
var wrapper1CmputedHeight = wrapper1.scrollHeight;
var wrapper2CmputedHeight = wrapper2.scrollHeight;

header1.addEventListener('click', function() {
  if (wrapper1.style.height === '60px') {
    wrapper1.style.height = wrapper1CmputedHeight + 'px';
  } else {
    wrapper1.style.height = '60px';
  }
})

header2.addEventListener('click', function() {
  if (wrapper2.style.height === '60px') {
    wrapper2.style.height = wrapper2CmputedHeight + 'px';
  } else {
    wrapper2.style.height = '60px';
  }
})

#wrapper1,
#wrapper2 {
  background: #fff;
  border: 1px solid grey;
  overflow: hidden;
  transition: height .2s linear
}

#wrapper1 {
  margin-bottom: 40px
}

#header1,
#header2 {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer
}

#content1 {
  height: 20px;
  background: blue
}

#content2 {
  height: 600px;
  background: green
}

    header

    header

Body:
The only way to do this with css transitions, is to dynamically calculate the duration of the transition using a little javascript. So, in your code, I would remove the duration for the transition rule in your css, i,e.

#wrapper1,
#wrapper2 {
  background: #fff;
  overflow: hidden;
  transition: height linear
}

and I would instead set the duration in the click handler as follows:

header1.addEventListener('click', function () {
    if(wrapper1.style.height === '60px') {
    wrapper1.style.height = wrapper1CmputedHeight + 'px';
    wrapper1.style.transitionDuration=(wrapper1CmputedHeight/100)+"s";
  } else {
    wrapper1.style.height = '60px';
  }
})

So in this case, I've used a speed of 100px per second (this is the /100 part in the above code).


问:
Multiple models in a view
I want to have 2 models in one view. The page contains both LoginViewModel and RegisterViewModel.

e.g.

```<code>public class LoginViewModel
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public class RegisterViewModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}
</code>```

Do I need to make another ViewModel which holds these 2 ViewModels?

```<code>public BigViewModel
{
    public LoginViewModel LoginViewModel{get; set;}
    public RegisterViewModel RegisterViewModel {get; set;}
}
</code>```

I need the validation attributes to be brought forward to the view. This is why I need the ViewModels.

Isn't there another way such as (without the BigViewModel):

```<code> @model ViewModel.RegisterViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Name)
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }

 @model ViewModel.LoginViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }
</code>```

答:
I'd recommend using Html.RenderAction and PartialViewResults to accomplish this; it will allow you to display the same data, but each partial view would still have a single view model and removes the need for a BigViewModel

So your view contain something like the following:

```<code>@Html.RenderAction("Login")
@Html.RenderAction("Register")
</code>```

Where Login & Register are both actions in your controller defined like the following:

```<code>public PartialViewResult Login( )
{
    return PartialView( "Login", new LoginViewModel() );
}

public PartialViewResult Register( )
{
    return PartialView( "Register", new RegisterViewModel() );
}
</code>```

The Login & Register would then be user controls residing in either the current View folder, or in the Shared folder and would like something like this:

/Views/Shared/Login.cshtml: (or /Views/MyView/Login.cshtml)

```<code>@model LoginViewModel
@using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Email)
    @Html.PasswordFor(model => model.Password)
}
</code>```

/Views/Shared/Register.cshtml: (or /Views/MyView/Register.cshtml)

```<code>@model ViewModel.RegisterViewModel
@using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Name)
    @Html.TextBoxFor(model => model.Email)
    @Html.PasswordFor(model => model.Password)
}
</code>```

And there you have a single controller action, view and view file for each action with each totally distinct and not reliant upon one another for anything.

ContentLicense: CC BY-SA 4.0

Title: Multiple models in a view

Body:
I want to have 2 models in one view. The page contains both LoginViewModel and RegisterViewModel.

e.g.

public class LoginViewModel
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public class RegisterViewModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

Do I need to make another ViewModel which holds these 2 ViewModels?

public BigViewModel
{
    public LoginViewModel LoginViewModel{get; set;}
    public RegisterViewModel RegisterViewModel {get; set;}
}

I need the validation attributes to be brought forward to the view. This is why I need the ViewModels.

Isn't there another way such as (without the BigViewModel):

 @model ViewModel.RegisterViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Name)
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }

 @model ViewModel.LoginViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }

Body:
I'd recommend using Html.RenderAction and PartialViewResults to accomplish this; it will allow you to display the same data, but each partial view would still have a single view model and removes the need for a BigViewModel

So your view contain something like the following:

@Html.RenderAction("Login")
@Html.RenderAction("Register")

Where Login & Register are both actions in your controller defined like the following:

public PartialViewResult Login( )
{
    return PartialView( "Login", new LoginViewModel() );
}

public PartialViewResult Register( )
{
    return PartialView( "Register", new RegisterViewModel() );
}

The Login & Register would then be user controls residing in either the current View folder, or in the Shared folder and would like something like this:

/Views/Shared/Login.cshtml: (or /Views/MyView/Login.cshtml)

@model LoginViewModel
@using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Email)
    @Html.PasswordFor(model => model.Password)
}

/Views/Shared/Register.cshtml: (or /Views/MyView/Register.cshtml)

@model ViewModel.RegisterViewModel
@using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Name)
    @Html.TextBoxFor(model => model.Email)
    @Html.PasswordFor(model => model.Password)
}

And there you have a single controller action, view and view file for each action with each totally distinct and not reliant upon one another for anything.


问:
ng-repeat parameter in search, SpringBoot/AngularJS
Here is my Repository:

```<code>@Repository
public interface DataRepository extends JpaRepository<Data, Long>{

@Query("SELECT d FROM Data d WHERE "
+ "(:name IS NULL OR d.name like :name) AND "
+ "(:minPriority IS NULL OR d.priority >= :minPriority) AND "
+ "(:maxPriority IS NULL OR d.priority <= :maxPriority) AND "
+ "( //needed code here )"
Page<Data> search(
@Param("name") String name,
@Param("minPriority") Integer minPriority,
@Param("maxPriority") Integer maxPriority,
@Param("nameOfEmployee") String name, int page);

}
</code>```

I have problem with namrOfEmployee parameter. In my Angular I need to   select one of values from ng-repeat:

```<code><div class="form-group">
  <label for="employee">Employees</label>
  <select class="form-control" ng-model="newEmployee.idEmployee"
    id="employee">
    <option ng-selected="newEmployee.idEmployee == e.id" ng-repeat="e in
    employees" value="{{ e.id }}"> {{ e.name }}</option>
  </select>
</div>
<div class="form-group">
  <button class="btn btn-primary" ng-click="search()">Search</button>
</div>
</code>```

Employee is different entity. Do I maybe need to join Data and Employee tables? Any ideas?

Here are Data and Employee classes:

```<code>@Entity
@Table(name="Data")
public class Data {
@Id
@GeneratedValue
@Column(name="id")
private Long id;
@Column(name="name")
private String name;
@Column(name="description")
private String description;
@Column(name="priority")
private int priority;
}

@Entity
@Table(name="Employee")
public class Employee {
@Id
@GeneratedValue
@Column(name="id")
private Long id;
@Column(name="firstName")
private String firstName;
@Column(name="lastName")
private String lastName;
@Column(name="position")
private String position;
}
</code>```

答:
I am struggling a bit to understand your question here. There seem to be a few components. Primarily, your Employee and Data entities are not related from a code perspective. There is also a bit of design confusion. I've put together what seems to make sense from what you have here.

The below solution will provide this workflow:

UI -> Request & List Employees -> Select Employee -> Request & Display associated data.

From the AngularJS side, I would first make a request for your list of employees. If you don't have that implemented yet, it's just going to be another repository (ie. EmployeeRepository), and an exposed endpoint for listing them. At that point, you'll have an array of employees in your UI. Once one is selected, you would then pass the request to this search method, providing the supplied parameters. In return, you would get back the datum that is associated to that employee.

First, we need to update your @Entity models to have a relationship:

Here, we make use of @OneToMany and @ManyToOne. @OneToMany means that an Employee has many Data. @ManyToOne means that many datum have one Employee.

Employee.java

```<code>@Entity
@Table(name = "Employee")
public class Employee {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;
    @Column(name = "firstName")
    private String firstName;
    @Column(name = "lastName")
    private String lastName;
    @Column(name = "position")
    private String position;

    @OneToMany
    private Set<Data> data;

    // Getters/Setters/Etc

}
</code>```

Data.java

```<code>@Entity
@Table(name = "Data")
public class Data {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;
    @Column(name = "name")
    private String name;
    @Column(name = "description")
    private String description;
    @Column(name = "priority")
    private int priority;

    @ManyToOne
    private Employee employee;

    // Getters/Setters/Etc

}
</code>```

Now that they are related from a JPA perspective, we can update the query:

I noticed that you had defined int page. I've updated to use Pageable.
  I have also changed your parameter to employeeId, as it would appear that your > goal is to pull back data given the employee's ID.

DataRepository.java

```<code>@Query("SELECT d FROM Data d "
        + "WHERE d.employee.id = :employeeId AND "
        + "(:name IS NULL OR d.name like :name) AND "
        + "(:minPriority IS NULL OR d.priority >= :minPriority) AND "
        + "(:maxPriority IS NULL OR d.priority <= :maxPriority) ")
Page<Data> search(@Param("name") String name,
                    @Param("minPriority") Integer minPriority,
                    @Param("maxPriority") Integer maxPriority,
                    @Param("employeeId") Long employeeId,
                    Pageable pageable);
</code>```

Body:
Here is my Repository:

@Repository
public interface DataRepository extends JpaRepository<Data, Long>{

@Query("SELECT d FROM Data d WHERE "
+ "(:name IS NULL OR d.name like :name) AND "
+ "(:minPriority IS NULL OR d.priority >= :minPriority) AND "
+ "(:maxPriority IS NULL OR d.priority <= :maxPriority) AND "
+ "( //needed code here )"
Page<Data> search(
@Param("name") String name,
@Param("minPriority") Integer minPriority,
@Param("maxPriority") Integer maxPriority,
@Param("nameOfEmployee") String name, int page);

}

I have problem with namrOfEmployee parameter. In my Angular I need to   select one of values from ng-repeat:

  Employees
  <select class="form-control" ng-model="newEmployee.idEmployee"
    id="employee">
    <option ng-selected="newEmployee.idEmployee == e.id" ng-repeat="e in
    employees" value="{{ e.id }}"> {{ e.name }}</option>
  </select>

  <button class="btn btn-primary" ng-click="search()">Search</button>

Employee is different entity. Do I maybe need to join Data and Employee tables? Any ideas?

Here are Data and Employee classes:

@Entity
@Table(name="Data")
public class Data {
@Id
@GeneratedValue
@Column(name="id")
private Long id;
@Column(name="name")
private String name;
@Column(name="description")
private String description;
@Column(name="priority")
private int priority;
}

@Entity
@Table(name="Employee")
public class Employee {
@Id
@GeneratedValue
@Column(name="id")
private Long id;
@Column(name="firstName")
private String firstName;
@Column(name="lastName")
private String lastName;
@Column(name="position")
private String position;
}

Body:
I am struggling a bit to understand your question here. There seem to be a few components. Primarily, your Employee and Data entities are not related from a code perspective. There is also a bit of design confusion. I've put together what seems to make sense from what you have here.

The below solution will provide this workflow:

UI -> Request & List Employees -> Select Employee -> Request & Display associated data.

From the AngularJS side, I would first make a request for your list of employees. If you don't have that implemented yet, it's just going to be another repository (ie. EmployeeRepository), and an exposed endpoint for listing them. At that point, you'll have an array of employees in your UI. Once one is selected, you would then pass the request to this search method, providing the supplied parameters. In return, you would get back the datum that is associated to that employee.

First, we need to update your @Entity models to have a relationship:

Here, we make use of @OneToMany and @ManyToOne. @OneToMany means that an Employee has many Data. @ManyToOne means that many datum have one Employee.

Employee.java

@Entity
@Table(name = "Employee")
public class Employee {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;
    @Column(name = "firstName")
    private String firstName;
    @Column(name = "lastName")
    private String lastName;
    @Column(name = "position")
    private String position;

    @OneToMany
    private Set<Data> data;

    // Getters/Setters/Etc

}

Data.java

@Entity
@Table(name = "Data")
public class Data {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;
    @Column(name = "name")
    private String name;
    @Column(name = "description")
    private String description;
    @Column(name = "priority")
    private int priority;

    @ManyToOne
    private Employee employee;

    // Getters/Setters/Etc

}

Now that they are related from a JPA perspective, we can update the query:

I noticed that you had defined int page. I've updated to use Pageable.
  I have also changed your parameter to employeeId, as it would appear that your > goal is to pull back data given the employee's ID.

DataRepository.java

@Query("SELECT d FROM Data d "
        + "WHERE d.employee.id = :employeeId AND "
        + "(:name IS NULL OR d.name like :name) AND "
        + "(:minPriority IS NULL OR d.priority >= :minPriority) AND "
        + "(:maxPriority IS NULL OR d.priority <= :maxPriority) ")
Page<Data> search(@Param("name") String name,
                    @Param("minPriority") Integer minPriority,
                    @Param("maxPriority") Integer maxPriority,
                    @Param("employeeId") Long employeeId,
                    Pageable pageable);


问:
'The left hand side of an assignment must be a variable' : Bubble Sort - JAVA OOP
I have this function which runs a Bubble Sort algorithm to sort a LinkedList created in another class.

```<code>for(int k=0; k < n; k++){
                for(int j=1; j < (n-i); j++){
                         if(loopObj.loopedGradeReq(j-1) > loopObj.loopedGradeReq(j)){
                                //swap elements
                                temp = loopObj.loopedGradeReq(j-1);
                                loopObj.getGradeReq().get(j-1) = loopObj.getGradeReq().get(j);
                                arr[j-1] = arr[j];
                                loopObj.getGradeReq().get(j) = temp;
                        }

                }
        }
</code>```

However, I keep getting a

'the left hand side of an argument must be a variable'

error whenever I get to this line :

```<code> loopObj.getGradeReq().get(j-1) = loopObj.getGradeReq().get(j);
</code>```

What can I do? Thanks in advance!

答:
Both sides of the assignment return a value, that is to say that you are calling the get() function of the GradeReq returned by loopObj.getGradeReq(). You can't assign to the value returned by a function (get()), rather you do something with it. Without seeing the interfaces there's not enough information to completely answer this, but the solution might look something more like...

```<code>loopObj.getGradeReq().set(j-1, loopObj.getGradeReq().get(j));
</code>```

assuming that there was a method called set(index, object) in the GradeReq class.

Body:
I have this function which runs a Bubble Sort algorithm to sort a LinkedList created in another class.

for(int k=0; k < n; k++){
                for(int j=1; j < (n-i); j++){
                         if(loopObj.loopedGradeReq(j-1) > loopObj.loopedGradeReq(j)){
                                //swap elements
                                temp = loopObj.loopedGradeReq(j-1);
                                loopObj.getGradeReq().get(j-1) = loopObj.getGradeReq().get(j);
                                arr[j-1] = arr[j];
                                loopObj.getGradeReq().get(j) = temp;
                        }

                }
        }

However, I keep getting a

'the left hand side of an argument must be a variable'

error whenever I get to this line :

 loopObj.getGradeReq().get(j-1) = loopObj.getGradeReq().get(j);

What can I do? Thanks in advance!

Body:
Both sides of the assignment return a value, that is to say that you are calling the get() function of the GradeReq returned by loopObj.getGradeReq(). You can't assign to the value returned by a function (get()), rather you do something with it. Without seeing the interfaces there's not enough information to completely answer this, but the solution might look something more like...

loopObj.getGradeReq().set(j-1, loopObj.getGradeReq().get(j));

assuming that there was a method called set(index, object) in the GradeReq class.


问:
Select random image cover in SQL
I would like to select a random image for cover of the album. If the album contains images tagged with "cover", then it should select from those images only. If a sub-album has images tagged with "cover", then it should not select images that are not tagged with "cover".

Here is a visual structure.

```<code>Album 1
├───Image 1
├───Album 2
│   ├───Image 2
│   ├───Image 3 (cover)
│   └───Image 4 (cover)
└───Album 3
    ├───Image 5
    └───Image 6
</code>```

Album 1 should choose from Image 1, Image 3, Image 4, Image 5, Image 6

Album 2 should choose from Image 3, Image 4

Album 3 should choose from Image 5, Image 6

Here is my tables

Table tags

```<code>| id | name  |
|----|-------|
| 1  | cover |
</code>```

Table image_tag

```<code>| id | image_id | tag_id |
|----|----------|--------|
| 1  | 3        | 1      |
| 2  | 4        | 1      |
</code>```

Table album_image

```<code>| id | album_id | image_id |
|----|----------|----------|
| 1  | 1        | 1        |
| 2  | 2        | 2        |
| 3  | 2        | 3        |
| 4  | 2        | 4        |
| 5  | 3        | 5        |
| 6  | 3        | 6        |
</code>```

Table albums

```<code>| id | name    | parent_id |
|----|---------|-----------|
| 1  | album 1 | null      |
| 2  | album 2 | 1,        |
| 3  | album 3 | 1,        |
</code>```

This is the SQL I came up.

```<code>SELECT ai.image_id AS image_id FROM albums AS a
INNER JOIN album_image AS ai ON ai.album_id = a.id
LEFT JOIN image_tag AS it ON it.image_id = ai.image_id AND it.tag_id = 1[1]
WHERE a.id = 1[2] OR parent_id LIKE '1,%'[3]
ORDER BY CASE
    WHEN it.tag_id IS NOT NULL AND a.id = 1[4] THEN RAND()
    ELSE RAND() + 1
END  ASC LIMIT 1;
</code>```

[1]: This is current get by another SQL in PHP. It would be nice if the can be merged. Is it possible to LEFT JOIN a INNER JOIN table? What if the tag does not exist?

[2], [4]: This is the album id came from PHP.

[3]: This is came from PHP to ensure sub-album is included.

The solution will generate the following result.

Album 1 should choose from Image 1, Image 2, Image 3, Image 4, Image 5, Image 6

Album 2 should choose from Image 3, Image 4

Album 3 should choose from Image 5, Image 6

Is there a way to modify the SQL so that I can generate my expected result?

P.S. I am running MySQL.

EDIT
Schema for testing

```<code>CREATE TABLE tags (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name TEXT NOT NULL
);
INSERT INTO tags (name) VALUES ('cover');

CREATE TABLE image_tag (
  id INT AUTO_INCREMENT PRIMARY KEY,
  image_id INT NOT NULL,
  tag_id INT NOT NULL
);
INSERT INTO image_tag (image_id, tag_id) VALUES (3, 1);
INSERT INTO image_tag (image_id, tag_id) VALUES (4, 1);

CREATE TABLE album_image (
  id INT AUTO_INCREMENT PRIMARY KEY,
  album_id INT NOT NULL,
  image_id INT NOT NULL
);
INSERT INTO album_image (album_id, image_id) VALUES (1, 1);
INSERT INTO album_image (album_id, image_id) VALUES (2, 2);
INSERT INTO album_image (album_id, image_id) VALUES (2, 3);
INSERT INTO album_image (album_id, image_id) VALUES (2, 4);
INSERT INTO album_image (album_id, image_id) VALUES (3, 5);
INSERT INTO album_image (album_id, image_id) VALUES (3, 6);

CREATE TABLE albums (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name TEXT NOT NULL,
  parent_id TEXT
);
INSERT INTO albums (name, parent_id) VALUES ('album 1', NULL);
INSERT INTO albums (name, parent_id) VALUES ('album 2', '1,');
INSERT INTO albums (name, parent_id) VALUES ('album 3', '1,');
</code>```

答:
Here is my solution.</p>

```<code>SELECT ai.image_id AS image_id, (
    SELECT COUNT(*) FROM albums AS a2
        INNER JOIN album_image AS ai2 ON ai2.album_id=a2.id
        LEFT JOIN image_tag AS it2
            INNER JOIN tags AS t2 ON t2.id = it2.tag_id
        ON it2.image_id = ai2.image_id AND t2.name = 'cover'
        WHERE a2.id = a.id AND t2.name IS NOT NULL AND it.tag_id IS NULL
    ) AS count FROM albums AS a
INNER JOIN album_image AS ai ON ai.album_id=a.id
LEFT JOIN image_tag AS it
    INNER JOIN tags AS t ON t.id = it.tag_id
ON it.image_id = ai.image_id AND t.name = 'cover'
WHERE a.id = 1 OR parent_id LIKE '1,%'
ORDER BY CASE
    WHEN it.tag_id IS NOT NULL AND a.id = 1 THEN RAND()
    WHEN count > 0 THEN RAND() + 2
    ELSE RAND() + 1
END ASC LIMIT 1;
</code>```

Title: Select random image cover in SQL

Body:
I would like to select a random image for cover of the album. If the album contains images tagged with "cover", then it should select from those images only. If a sub-album has images tagged with "cover", then it should not select images that are not tagged with "cover".

Here is a visual structure.

Album 1
├───Image 1
├───Album 2
│   ├───Image 2
│   ├───Image 3 (cover)
│   └───Image 4 (cover)
└───Album 3
    ├───Image 5
    └───Image 6

Album 1 should choose from Image 1, Image 3, Image 4, Image 5, Image 6

Album 2 should choose from Image 3, Image 4

Album 3 should choose from Image 5, Image 6

Here is my tables

Table tags

| id | name  |
|----|-------|
| 1  | cover |

Table image_tag

| id | image_id | tag_id |
|----|----------|--------|
| 1  | 3        | 1      |
| 2  | 4        | 1      |

Table album_image

| id | album_id | image_id |
|----|----------|----------|
| 1  | 1        | 1        |
| 2  | 2        | 2        |
| 3  | 2        | 3        |
| 4  | 2        | 4        |
| 5  | 3        | 5        |
| 6  | 3        | 6        |

Table albums

| id | name    | parent_id |
|----|---------|-----------|
| 1  | album 1 | null      |
| 2  | album 2 | 1,        |
| 3  | album 3 | 1,        |

This is the SQL I came up.

SELECT ai.image_id AS image_id FROM albums AS a
INNER JOIN album_image AS ai ON ai.album_id = a.id
LEFT JOIN image_tag AS it ON it.image_id = ai.image_id AND it.tag_id = 1[1]
WHERE a.id = 1[2] OR parent_id LIKE '1,%'[3]
ORDER BY CASE
    WHEN it.tag_id IS NOT NULL AND a.id = 1[4] THEN RAND()
    ELSE RAND() + 1
END  ASC LIMIT 1;

[1]: This is current get by another SQL in PHP. It would be nice if the can be merged. Is it possible to LEFT JOIN a INNER JOIN table? What if the tag does not exist?

[2], [4]: This is the album id came from PHP.

[3]: This is came from PHP to ensure sub-album is included.

The solution will generate the following result.

Album 1 should choose from Image 1, Image 2, Image 3, Image 4, Image 5, Image 6

Album 2 should choose from Image 3, Image 4

Album 3 should choose from Image 5, Image 6

Is there a way to modify the SQL so that I can generate my expected result?

P.S. I am running MySQL.

EDIT
Schema for testing

CREATE TABLE tags (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name TEXT NOT NULL
);
INSERT INTO tags (name) VALUES ('cover');

CREATE TABLE image_tag (
  id INT AUTO_INCREMENT PRIMARY KEY,
  image_id INT NOT NULL,
  tag_id INT NOT NULL
);
INSERT INTO image_tag (image_id, tag_id) VALUES (3, 1);
INSERT INTO image_tag (image_id, tag_id) VALUES (4, 1);

CREATE TABLE album_image (
  id INT AUTO_INCREMENT PRIMARY KEY,
  album_id INT NOT NULL,
  image_id INT NOT NULL
);
INSERT INTO album_image (album_id, image_id) VALUES (1, 1);
INSERT INTO album_image (album_id, image_id) VALUES (2, 2);
INSERT INTO album_image (album_id, image_id) VALUES (2, 3);
INSERT INTO album_image (album_id, image_id) VALUES (2, 4);
INSERT INTO album_image (album_id, image_id) VALUES (3, 5);
INSERT INTO album_image (album_id, image_id) VALUES (3, 6);

CREATE TABLE albums (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name TEXT NOT NULL,
  parent_id TEXT
);
INSERT INTO albums (name, parent_id) VALUES ('album 1', NULL);
INSERT INTO albums (name, parent_id) VALUES ('album 2', '1,');
INSERT INTO albums (name, parent_id) VALUES ('album 3', '1,');

Body:
Here is my solution.

SELECT ai.image_id AS image_id, (
    SELECT COUNT(*) FROM albums AS a2
        INNER JOIN album_image AS ai2 ON ai2.album_id=a2.id
        LEFT JOIN image_tag AS it2
            INNER JOIN tags AS t2 ON t2.id = it2.tag_id
        ON it2.image_id = ai2.image_id AND t2.name = 'cover'
        WHERE a2.id = a.id AND t2.name IS NOT NULL AND it.tag_id IS NULL
    ) AS count FROM albums AS a
INNER JOIN album_image AS ai ON ai.album_id=a.id
LEFT JOIN image_tag AS it
    INNER JOIN tags AS t ON t.id = it.tag_id
ON it.image_id = ai.image_id AND t.name = 'cover'
WHERE a.id = 1 OR parent_id LIKE '1,%'
ORDER BY CASE
    WHEN it.tag_id IS NOT NULL AND a.id = 1 THEN RAND()
    WHEN count > 0 THEN RAND() + 2
    ELSE RAND() + 1
END ASC LIMIT 1;


问:
group_by a data frame by the grouping variables of another data frame
I have the data frame df

```<code>df <- tibble(x = 1, y = 2) %>% group_by(x, y)
</code>```

and I would like to group the data frame df2 using the grouping variables of df.

This does not work:

```<code>df2 <- tibble(x = 3, y = 4) %>% group_by(groups(df))
</code>```

答:
You can use group_by_at with group_vars (returns a character vector):

```<code>df2 <- tibble(x = 3, y = 4) %>% group_by_at(group_vars(df))

df2
# A tibble: 1 x 2
# Groups:   x, y [1]
#      x     y
#  <dbl> <dbl>
#1     3     4
</code>```

Or if using group_by with groups which returns a list of symbols, you need rlang::UQS to splice the symbols as argument to group_by:

```<code>library(rlang)
df2 <- tibble(x = 3, y = 4) %>% group_by(UQS(groups(df)))
df2
# A tibble: 1 x 2
# Groups:   x, y [1]
#      x     y
#  <dbl> <dbl>
#1     3     4
</code>```

Body:
I have the data frame df

df <- tibble(x = 1, y = 2) %>% group_by(x, y)

and I would like to group the data frame df2 using the grouping variables of df.

This does not work:

df2 <- tibble(x = 3, y = 4) %>% group_by(groups(df))

Body:
You can use group_by_at with group_vars (returns a character vector):

df2 <- tibble(x = 3, y = 4) %>% group_by_at(group_vars(df))

df2
# A tibble: 1 x 2
# Groups:   x, y [1]
#      x     y
#  <dbl> <dbl>
#1     3     4

Or if using group_by with groups which returns a list of symbols, you need rlang::UQS to splice the symbols as argument to group_by:

library(rlang)
df2 <- tibble(x = 3, y = 4) %>% group_by(UQS(groups(df)))
df2
# A tibble: 1 x 2
# Groups:   x, y [1]
#      x     y
#  <dbl> <dbl>
#1     3     4


问:
Couldn't retrieve data from my database
I have a problem in my system. Last time i checked, my system was working fine but now i get this error and it seems like my system cannot retrieve data from my database. I am getting a Token mismatch exception even though i have csrf token in all of my forms. Somebody Help.</p>

答:
A Token Mismatch Exception can occur from other situations other than a form missing a csrf token. An expired session or expired token on an old page can also cause the problem. Try logging out and back in, and try clearing your cookies on your site to see if it's a problem with your session.

Could you also provide a snippet of the code in question? What does your csrf token code look like? It's possible that it's just not a proper use of the csrf token.

Title: Couldn't retrieve data from my database


问:
How to make  and <input> appear on the same line on an HTML form?
I am creating a registration form for a website. I want each label and its corresponding input element to appear on the same line.

Here's my code:

#form {
 background-color: #FFF;
 height: 600px;
 width: 600px;
 margin-right: auto;
 margin-left: auto;
 margin-top: 0px;
 border-top-left-radius: 10px;
 border-top-right-radius: 10px;
 padding: 0px;
}

label {
 font-family: Georgia, "Times New Roman", Times, serif;
 font-size: 18px;
 color: #333;
 height: 20px;
 width: 200px;
 margin-top: 10px;
 margin-left: 10px;
 text-align: right;
 clear: both;
}

input {
 height: 20px;
 width: 300px;
 border: 1px solid #000;
 margin-top: 10px;
 float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="form">

 <form action="" method="post" name="registration" class="register">

  <fieldset>

   <label for="Student"> Name: </label>
   <input name="Student" />
   <label for="Matric_no"> Matric number: </label>
   <input name="Matric_no" />
   <label for="Email"> Email: </label>
   <input name="Email" />
   <label for="Username"> Username: </label>
   <input name="Username" />
   <label for="Password"> Password: </label>
   <input name="Password" type="password" />

   <input name="regbutton" type="button" class="button" value="Register" />
  </fieldset>

 </form>
</div>  </code>```

答:
I found "display:flex" style is a good way to make these elements in same line. No matter what kind of element in the div. Especially if the input class is form-control,other solutions like bootstrap, inline-block will not work well.

Example:

```<code><div style="display:flex; flex-direction: row; justify-content: center; align-items: center">
    <label for="Student">Name:</label>
    <input name="Student" />
</div>
</code>```

More detail about display:flex:

flex-direction:   row, column

justify-content:  flex-end, center, space-between, space-around

align-items:      stretch, flex-start, flex-end, center

Title: How to make <label> and <input> appear on the same line on an HTML form?

Body:
I am creating a registration form for a website. I want each label and its corresponding input element to appear on the same line.

Here's my code:

#form {
 background-color: #FFF;
 height: 600px;
 width: 600px;
 margin-right: auto;
 margin-left: auto;
 margin-top: 0px;
 border-top-left-radius: 10px;
 border-top-right-radius: 10px;
 padding: 0px;
}

label {
 font-family: Georgia, "Times New Roman", Times, serif;
 font-size: 18px;
 color: #333;
 height: 20px;
 width: 200px;
 margin-top: 10px;
 margin-left: 10px;
 text-align: right;
 clear: both;
}

input {
 height: 20px;
 width: 300px;
 border: 1px solid #000;
 margin-top: 10px;
 float: left;
}

 <form action="" method="post" name="registration" class="register">

  <fieldset>

    Name:
   <input name="Student" />
    Matric number:
   <input name="Matric_no" />
    Email:
   <input name="Email" />
    Username:
   <input name="Username" />
    Password:
   <input name="Password" type="password" />

   <input name="regbutton" type="button" class="button" value="Register" />
  </fieldset>

 </form>

Body:
I found "display:flex" style is a good way to make these elements in same line. No matter what kind of element in the div. Especially if the input class is form-control,other solutions like bootstrap, inline-block will not work well.

Example:

<div style="display:flex; flex-direction: row; justify-content: center; align-items: center">
    <label for="Student">Name:</label>
    <input name="Student" />
</div>

More detail about display:flex:

flex-direction:   row, column

justify-content:  flex-end, center, space-between, space-around

align-items:      stretch, flex-start, flex-end, center


答:
You could loop through the inputs and in this loop grab the previous input of the current one. From there you take it's value.

$('input').each(function(i, e) {
  var previousSibling = $(this).prevAll('input').first();

  if (previousSibling.length) {
    $(this).val(previousSibling.val());
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label>Code</label>
<input type="text" value="1234" id="custcode_1" />

<label>Copy Code</label>
<input type="text" value="" id="custcode_2" /></code>```

Title: JQuery to get input field value based on label

Body:
I need to copy the value of the first input box to the second input box.  The id and name of these input boxes are coming from tables.  What is fix will be the labels like 'Code' and 'Copy Code'

Code
<input type="text" value="1234"  id="custcode_1" />

Copy Code
<input type="text" value=""  id="custcode_2" />

For normal scenario it will be just

$('#custcode_2').val($('#custcode_1').val());

But the id or name are generated on the fly so this is not possible.  How to achieve this using labels of the input boxes.

Thanks for the help.

Body:
You could loop through the inputs and in this loop grab the previous input of the current one. From there you take it's value.

$('input').each(function(i, e) {
  var previousSibling = $(this).prevAll('input').first();

  if (previousSibling.length) {
    $(this).val(previousSibling.val());
  }
});

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

<label>Code</label>
<input type="text" value="1234" id="custcode_1" />

<label>Copy Code</label>
<input type="text" value="" id="custcode_2" />


问:
Approvaltests and PDF
Can I use ApprovalTests with PDF's? I tried using the FileLauncher but it seems the identical PDF's are slightly different at file (bit) level. Or did I use it wrongly?</p>

```<code>[TestMethod]
[UseReporter(typeof(FileLauncherReporter))]
public void TestPdf()
{
    var createSomePdf = PdfCreate();

    ApprovalTests.Approvals.Verify(new FileInfo(createSomePdf.FileName));

}
</code>```

答:
Looks like this is built in to ApprovalTests now.

usage:

```<code>Approvals.VerifyPdfFile(pdfFileLocation);
</code>```

See the source:

```<code>public static void VerifyPdfFile(string pdfFilePath)
{
    PdfScrubber.ScrubPdf(pdfFilePath);
    Verify(new ExistingFileWriter(pdfFilePath));
}
</code>```

Title: Approvaltests and PDF

Body:
Can I use ApprovalTests with PDF's? I tried using the FileLauncher but it seems the identical PDF's are slightly different at file (bit) level. Or did I use it wrongly?

[TestMethod]
[UseReporter(typeof(FileLauncherReporter))]
public void TestPdf()
{
    var createSomePdf = PdfCreate();

    ApprovalTests.Approvals.Verify(new FileInfo(createSomePdf.FileName));

}

Body:
Looks like this is built in to ApprovalTests now.

usage:

Approvals.VerifyPdfFile(pdfFileLocation);

See the source:

public static void VerifyPdfFile(string pdfFilePath)
{
    PdfScrubber.ScrubPdf(pdfFilePath);
    Verify(new ExistingFileWriter(pdfFilePath));
}


问:
execute ftp with white space in path
The following PowerShell script runs an ftp command but returns an error as it cannot get find the absolute source path (which includes white space and does take the complete path as "File One” and “Destination One".

Output:

```<code>/usr/bin/lftp -c \"mirror --only-missing --verbose sftp://jason@10.1.1.1:/e:/Files/File One e:/Files/Destination One/File One\"

Access failed: No such file (e:/Files/File)
</code>```

The values of each variables are hardcoded and cannot be changed for a reason. In that case, what are the changes required in the $ftppath or $ftpcmd to include these white spaces in the source and dest, so it can return the ftpcmd correctly. Could someone please help?

Script:

```<code># these values are hardcoded and cannot be modified

$root = "/e:/Files"
$source = "File One"
$dest = "e:/Files/Destination One/File One"
$user = "jason"
$server = "10.1.1.1"

# ftp command
$ftppath = "sftp://$user" + '@' + $server + ':' + $root + '/'  + $source + ' ' + $dest
$ftpcmd = '/usr/bin/lftp -c \"mirror --only-missing  --verbose ' + "$ftppath"+'\"'
$ftpcmd
Invoke-Expression -command $ftpcmd
</code>```

答:
```shell</p>

<h1>ftp command</h1>

<p>$ftppath = "sftp://$user" + '@' + $server + ':' + $root + '/'  + $source + ' ' + $dest</p>

<p>```

replace by this,use quote wrap $dest

```shell</p>

<h1>ftp command</h1>

<p>$ftppath = "sftp://$user" + '@' + $server + ':' + $root + '/'  + $source + ' ' + "${dest}"</p>

<p>```

Title: execute ftp with white space in path

Body:
The following PowerShell script runs an ftp command but returns an error as it cannot get find the absolute source path (which includes white space and does take the complete path as "File One” and “Destination One".

Output:

/usr/bin/lftp -c \"mirror --only-missing --verbose sftp://jason@10.1.1.1:/e:/Files/File One e:/Files/Destination One/File One\"

Access failed: No such file (e:/Files/File)

The values of each variables are hardcoded and cannot be changed for a reason. In that case, what are the changes required in the $ftppath or $ftpcmd to include these white spaces in the source and dest, so it can return the ftpcmd correctly. Could someone please help?

Script:

# these values are hardcoded and cannot be modified

$root = "/e:/Files"
$source = "File One"
$dest = "e:/Files/Destination One/File One"
$user = "jason"
$server = "10.1.1.1"

# ftp command
$ftppath = "sftp://$user" + '@' + $server + ':' + $root + '/'  + $source + ' ' + $dest
$ftpcmd = '/usr/bin/lftp -c \"mirror --only-missing  --verbose ' + "$ftppath"+'\"'
$ftpcmd
Invoke-Expression -command $ftpcmd


问:
I have an If statement that isn't behaving like I expect it too, maybe I'm stacking it wrong?
I have an if/then statement that is not behaving as such. My level of expertise is about 1/10.

I'm trying to take a user input value and give a variable output
depending on the value.

My script gives me 10, which is each function returning 5, which is wrong

```<code> def abs_func():
    plank_input = raw_input("How long can you hold a plank?:")
    situps_input = raw_input("How many situps can you do?:")

#checking the input we just recieved
    print "Plank Input:",plank_input
    print "Situps Input:",situps_input

#This Checks the plank time against my values.
    def abs_char1(plank):
        global abs_rate1
        if plank >= 120:
            abs_rate1 =+ 5
        else:
            if plank >= 90:
                abs_rate1 =+ 4
            else:
                if plank >= 60:
                    abs_rate1 =+ 3
                else:
                    abs_rate1 =+ 2
        print "Abs 1:",abs_rate1
        return abs_rate1

#This Checks the plank time against my values.
    def abs_char2(situps):
        global abs_rate2

        if situps >= 120:
            abs_rate2 =+ 5
        else:
            if situps >= 100:
                abs_rate2 =+ 4
            else:
                if situps >= 80:
                    abs_rate2 =+ 3
                else:
                    abs_rate2 =+ 2
        print "Abs 2:", abs_rate2
        return abs_rate2

    a1 = abs_char1(plank_input)
    a2 = abs_char2(situps_input)

    print "a1:",a1,"a2:",a2
    abs_rate = a1 + a2
    print abs_rate

abs_func()
</code>```

I want it to spit out the correct values, like 3 and 4, totaling 7.

But, it always prints out 5 and 5, totaling 10 and I don't know why...

答:
raw_input() and input() handle things differently, so when I used raw_input() instead of input() It changed the code enough to fail me out.
Why it did that I do not know, but it did.</p>

Body:
I have an if/then statement that is not behaving as such. My level of expertise is about 1/10.

I'm trying to take a user input value and give a variable output
depending on the value.

My script gives me 10, which is each function returning 5, which is wrong

 def abs_func():
    plank_input = raw_input("How long can you hold a plank?:")
    situps_input = raw_input("How many situps can you do?:")

#checking the input we just recieved
    print "Plank Input:",plank_input
    print "Situps Input:",situps_input

#This Checks the plank time against my values.
    def abs_char1(plank):
        global abs_rate1
        if plank >= 120:
            abs_rate1 =+ 5
        else:
            if plank >= 90:
                abs_rate1 =+ 4
            else:
                if plank >= 60:
                    abs_rate1 =+ 3
                else:
                    abs_rate1 =+ 2
        print "Abs 1:",abs_rate1
        return abs_rate1

#This Checks the plank time against my values.
    def abs_char2(situps):
        global abs_rate2

        if situps >= 120:
            abs_rate2 =+ 5
        else:
            if situps >= 100:
                abs_rate2 =+ 4
            else:
                if situps >= 80:
                    abs_rate2 =+ 3
                else:
                    abs_rate2 =+ 2
        print "Abs 2:", abs_rate2
        return abs_rate2

    a1 = abs_char1(plank_input)
    a2 = abs_char2(situps_input)

    print "a1:",a1,"a2:",a2
    abs_rate = a1 + a2
    print abs_rate

abs_func()

I want it to spit out the correct values, like 3 and 4, totaling 7.

But, it always prints out 5 and 5, totaling 10 and I don't know why...


问:
Find first character of string, then compare it with a symbol c++
Attempting to check the first character of a string to see if it contains a "/".

```<code>string pathname = "/test";
if(pathname.at(0) == "/")
{
    // if first character is a slash then delete the slash
    // but only delete the slash if it's the first character
    pathname.erase(pathname.begin()+0);
}
</code>```

I understand that the above code will not work because pathname.at(0) is considered an int.

I'm sure this has been asked before. But I have looked around a lot. I've seen the substr method the find method and many others. I can't seem to get them working right though.

Suggestions? Thanks in advance.

答:
Use single quote for character constant.

```<code>if(pathname.at(0) == '/')
                     ^ ^
</code>```

Double quotes, no matter how many characters are inside, represents a C-style string. You can't compare a character to a C-string.

Body:
Attempting to check the first character of a string to see if it contains a "/".

string pathname = "/test";
if(pathname.at(0) == "/")
{
    // if first character is a slash then delete the slash
    // but only delete the slash if it's the first character
    pathname.erase(pathname.begin()+0);
}

I understand that the above code will not work because pathname.at(0) is considered an int.

I'm sure this has been asked before. But I have looked around a lot. I've seen the substr method the find method and many others. I can't seem to get them working right though.

Suggestions? Thanks in advance.

Body:
Use single quote for character constant.

if(pathname.at(0) == '/')
                     ^ ^

Double quotes, no matter how many characters are inside, represents a C-style string. You can't compare a character to a C-string.


问:
What is the fastest sorting algorithm for a small number of integers?
I am wondering what the fastest algorithm would be for this.  I have 8 integers between 0 and 3000 and I need to sort them.  Although there are only 8 integers, this operation will be performed millions of times.</p>

答:
For only 8 integers and given that the range is much greater than 8, insertion sort is probably the best. Try it to start with, and if profiling indicates that it's not the bottleneck then leave it.

(Depending on many factors, the cutoff point at which quick-sort becomes better than insertion sort is usually between 5 and 10 items).