问:
Python error when running project
I have an error when running one of my projects, and it is very strange.    What happens is this:

```<code> File "src/run.py", line 4, in <module>
from dotenv import load_dotenv, find_dotenv
ImportError: No module named dotenv
</code>```

The strange thing is that I have installed python-dotenv.
This is the fourth line:

```<code>from dotenv import load_dotenv, find_dotenv
</code>```

Does anyone know how to fix this? Running High Sierra with python 2.7.

答:
It sounds you have have installed dotenv for another python distribution.

You can try to run the two following commands that use the same python program to install and run python-dotenv. The first one installs python-dotenv with pip. The second one tests the install. I use sudo to install it with main python program.

```<code>sudo python -m pip install python-dotenv
python -c 'from dotenv import load_dotenv, find_dotenv'
</code>```

It works also with Python3 (where you do not have to run the install command with sudo)

```<code>python3 -m pip install python-dotenv
python3 -c 'from dotenv import load_dotenv, find_dotenv'
</code>```

Title: Python error when running project

Body:
I have an error when running one of my projects, and it is very strange.    What happens is this:

 File "src/run.py", line 4, in <module>
from dotenv import load_dotenv, find_dotenv
ImportError: No module named dotenv

The strange thing is that I have installed python-dotenv.
This is the fourth line:

from dotenv import load_dotenv, find_dotenv

Does anyone know how to fix this? Running High Sierra with python 2.7.

Body:
It sounds you have have installed dotenv for another python distribution.

You can try to run the two following commands that use the same python program to install and run python-dotenv. The first one installs python-dotenv with pip. The second one tests the install. I use sudo to install it with main python program.

sudo python -m pip install python-dotenv
python -c 'from dotenv import load_dotenv, find_dotenv'

It works also with Python3 (where you do not have to run the install command with sudo)

python3 -m pip install python-dotenv
python3 -c 'from dotenv import load_dotenv, find_dotenv'


来源: stackexchange

问:
Unit testing elasticsearch.net's implicit operator using Moq
I am not sure ElasticSearch's .net low level client is commonly used yet, because NEST seems to be the "go to" approach to implement an Elasticsearch client in .net.

Anyway, among many other methods, the main IElasticLowLevelClient interface exposes a method to create indices :

```<code>ElasticsearchResponse<T> IndicesCreate<T>(
    string index,
    PostData<object> body,
    Func<CreateIndexRequestParameters, CreateIndexRequestParameters> requestParameters = null
) where T : class;
</code>```

As explained in this doc, you can pass a string instead of an instance of PostData<object> thanks to one of the handy PostData's implicit operators :

```<code>public class PostData<T> : IPostData<T>, IPostData
{
     // ... code omitted
     public static implicit operator PostData<T>(string literalString);
}
</code>```

I am unit testing a PersonIndexer class whose role is to call IndicesCreate with the correct index name "people" and the correct json body - I don't care about the last param. To do that I am mocking IElasticLowLevelClient using the Moq library.

Here is how PersonIndexer calls the low level client to create the index :

```<code>var result = _elasticClient.IndicesCreate<object>("people", "{ properties: {etc}}", null);
</code>```

Here is what the PersonIndexerTest class verification would ideally look like (json parsing simplified):

```<code>_elasticClientMock.Verify(c => c.IndicesCreate<object>(
            "people",
            It.Is<string>(body =>
                JObject.Parse(body).SelectToken("$.properties.name.type").ToString() == "string"
            ),
            null
        ));
</code>```

The issue is that Moq never sees this call because it is expecting PostData<object> to match the second argument type, not a string.

You would tell me to use the "real" underlying type in my clause : It.Is<PostData<object>>(...) but this raises another issue : the PostData class does not publicly expose the string I used as the implicit constructor, thus it prevents me from parsing the body of my index creation request.

Is there any trick I can use to verify the string passed ? Is there any way to setup the mock so that it reproduces the implicit operator's behavior ? Am I going in the wrong direction...?

答:
Provided you are not testing implementation of IElasticLowLevelClient the easiest approach to the problem would be to define you own interface for index creation that will accept index name and a string body. Use that interface from your code and assert correctness in test.

Alternatively you can use a bit of reflection to get private _literalString field in It.Is<PostData<object>>(...) statement.

UPDATE:

After investigating implementation of PostData I think I found better alernavive to reflection. You can setup callback for the method invocation, and the write PostData to a stream. Then you will be able to convert stream to a string and assert.

```<code>// Arrange
PostData<object> data = null;
mock
    .Setup(m => m.IndicesCreate<object>(It.IsAny<string>(), It.IsAny<PostData<object>>(), null))
    .Callback<string, PostData<object>>((s, d) => data = d);

// Act
// You test logic

// Assert
var stream = new MemoryStream();
data.Write(stream, fakeSettings);
var index = Enconding.UTF8.GetString(stream.ToArray());
index.Should().Be("{ properties: {etc}}");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am not sure ElasticSearch's .net low level client is commonly used yet, because NEST seems to be the "go to" approach to implement an Elasticsearch client in .net.

Anyway, among many other methods, the main IElasticLowLevelClient interface exposes a method to create indices :

ElasticsearchResponse<T> IndicesCreate<T>(
    string index,
    PostData<object> body,
    Func<CreateIndexRequestParameters, CreateIndexRequestParameters> requestParameters = null
) where T : class;

As explained in this doc, you can pass a string instead of an instance of PostData<object> thanks to one of the handy PostData's implicit operators :

public class PostData<T> : IPostData<T>, IPostData
{
     // ... code omitted
     public static implicit operator PostData<T>(string literalString);
}

I am unit testing a PersonIndexer class whose role is to call IndicesCreate with the correct index name "people" and the correct json body - I don't care about the last param. To do that I am mocking IElasticLowLevelClient using the Moq library.

Here is how PersonIndexer calls the low level client to create the index :

var result = _elasticClient.IndicesCreate<object>("people", "{ properties: {etc}}", null);

Here is what the PersonIndexerTest class verification would ideally look like (json parsing simplified):

_elasticClientMock.Verify(c => c.IndicesCreate<object>(
            "people",
            It.Is<string>(body =>
                JObject.Parse(body).SelectToken("$.properties.name.type").ToString() == "string"
            ),
            null
        ));

The issue is that Moq never sees this call because it is expecting PostData<object> to match the second argument type, not a string.

You would tell me to use the "real" underlying type in my clause : It.Is<PostData<object>>(...) but this raises another issue : the PostData class does not publicly expose the string I used as the implicit constructor, thus it prevents me from parsing the body of my index creation request.

Is there any trick I can use to verify the string passed ? Is there any way to setup the mock so that it reproduces the implicit operator's behavior ? Am I going in the wrong direction...?

Body:
Provided you are not testing implementation of IElasticLowLevelClient the easiest approach to the problem would be to define you own interface for index creation that will accept index name and a string body. Use that interface from your code and assert correctness in test.

Alternatively you can use a bit of reflection to get private _literalString field in It.Is<PostData<object>>(...) statement.

UPDATE:

After investigating implementation of PostData I think I found better alernavive to reflection. You can setup callback for the method invocation, and the write PostData to a stream. Then you will be able to convert stream to a string and assert.

// Arrange
PostData<object> data = null;
mock
    .Setup(m => m.IndicesCreate<object>(It.IsAny<string>(), It.IsAny<PostData<object>>(), null))
    .Callback<string, PostData<object>>((s, d) => data = d);

// Act
// You test logic

// Assert
var stream = new MemoryStream();
data.Write(stream, fakeSettings);
var index = Enconding.UTF8.GetString(stream.ToArray());
index.Should().Be("{ properties: {etc}}");


问:
Calculator function is not working, is showing function undefined
Below funtion not working and showing "add is undefined". I am calculating by chaining the function calls.</p>

```<code>var calc = {
  x: 5,
  add: function(num) {
    x = x + num;
    return x;
  },
  sub: function(num) {
    x = x - num;
    return x;
  },
  set: function(num) {
    x = num;
    return x;
  },
  print: function() {
    console.log(x);
  }
}
calc.set(5).add(3).sub(2).add(10).print();
</code>```

答:
I would rather do this :

var Calc = function (x) {
  this.x = x;
};

Calc.prototype = {
  add: function (y) {
    this.x += y;
    return this;
  },
  sub: function (y) {
    this.x -= y;
    return this;
  },
  valueOf: function () {
    return this.x;
  },
  toString: function () {
    return (+this) + "";
  },
  print : function () {
    console.log(this.toString());
    return this;
  }
};

function calc (x) {
  return new Calc(x);
}

calc(1).add(
  calc(5).add(3).sub(2).add(10).print()
).print();```

Body:
Below funtion not working and showing "add is undefined". I am calculating by chaining the function calls.

var calc = {
  x: 5,
  add: function(num) {
    x = x + num;
    return x;
  },
  sub: function(num) {
    x = x - num;
    return x;
  },
  set: function(num) {
    x = num;
    return x;
  },
  print: function() {
    console.log(x);
  }
}
calc.set(5).add(3).sub(2).add(10).print();


问:
data filtering in gridview using jquery
i have done the data filteration in gridview as like

http://tomcoote.co.uk/wp-content/CodeBank/Demos/columnFilters/demo.html

 on this page. But my requirement is some different from it. I Have a textbox outside the gridview i want to filter data according to this. please help me as soon as possible.

Thanks In advance.

答:
This might not be the answer for you question but it might help people who comes here.</p>

```<code> $(document).ready(function () {
            $("#txtID").keyup(function () {
                _this = this;
                $.each($("#grdEmployee tbody").find("tr:has(td)"), function () {
                    if ($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) != -1)
                        $(this).show();
                    else
                    $(this).hide();

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

Title: data filtering in gridview using jquery

Body:
This might not be the answer for you question but it might help people who comes here.

 $(document).ready(function () {
            $("#txtID").keyup(function () {
                _this = this;
                $.each($("#grdEmployee tbody").find("tr:has(td)"), function () {
                    if ($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) != -1)
                        $(this).show();
                    else
                    $(this).hide();

                });
            });
        });


问:
using sqlite with python, fetchall()

I am trying to compare a list of links to the liks stored in an sqlite database.

assuming the links in the database are:

link.com\page1

link.com\page2

link.com\page3

I have written the following code to chick if a given link exists in the database and adds it if it did not exist.

```<code>links = ['link.com\page2', 'link.com\page4']
c.execute('SELECT link FROM ads')
previouslinks = c.fetchall()

for l in links:
    if l not in previouslinks:
        c.execute('''INSERT INTO ads(link) VALUES(?)''', (l))
        conn.commit()
    else:
        pass
</code>```

the problem is even though the link is in the database, the script does not recognise it!

when I try to print previouslinks variable, results look something like this:

```<code>[('link.com\page1',), ('link.com\page2',), ('link.com\page3',)]
</code>```

I think the problem  is with the extra parentheses and commas, but I am not exactly sure.

答:
fetchall() returns a list of rows, where each row is a tuple containing all column values. A tuple containing a string is not the same as the string.

You have to extract the values from the rows (and you don't need fetchall() when iterating over a cursor):

```<code>previouslinks = [row[0] for row in c]
</code>```

Title: using sqlite with python, fetchall()

Body:
I am trying to compare a list of links to the liks stored in an sqlite database.

assuming the links in the database are:

link.com\page1

link.com\page2

link.com\page3

I have written the following code to chick if a given link exists in the database and adds it if it did not exist.

links = ['link.com\page2', 'link.com\page4']
c.execute('SELECT link FROM ads')
previouslinks = c.fetchall()

for l in links:
    if l not in previouslinks:
        c.execute('''INSERT INTO ads(link) VALUES(?)''', (l))
        conn.commit()
    else:
        pass

the problem is even though the link is in the database, the script does not recognise it!

when I try to print previouslinks variable, results look something like this:

[('link.com\page1',), ('link.com\page2',), ('link.com\page3',)]

I think the problem  is with the extra parentheses and commas, but I am not exactly sure.

Body:
fetchall() returns a list of rows, where each row is a tuple containing all column values. A tuple containing a string is not the same as the string.

You have to extract the values from the rows (and you don't need fetchall() when iterating over a cursor):

previouslinks = [row[0] for row in c]


问:
Why we don't draw ER for NoSQL databses
I know that NoSQL databases for instance MongoDB, can't be modeled using Entity-relationship "ER" diagram because it's schema-less but I can model UML and it kind of shows the relations between the attributes, so what's the difference and why? </p>

答:
ER diagrams aren't a good fit for document databases. The entity-relationship model supports many-to-many binary as well as ternary and higher relationships, composite keys and attributes on relationships, all of which aren't directly supported in hierarchical/network model DBMSs. It's not too difficult to map from one model to the other if one understands both. However, my experience is that most developers don't even distinguish them, let alone understand them well.

UML class diagrams look a lot like network data models, if you exclude methods. Both are graphs (whereas relational data models are hypergraphs) so the correspondence is much closer. However, class diagrams should be used for modeling systems rather than data. A road map is not the same as an engineering diagram for a car.

Title: Why we don't draw ER for NoSQL databses


问:
Get list of devices in local network (LAN)?
I'm looking for a way to find all devices (especially printers) in the local area network (LAN).

Is there are way to differentiate between printers and other devices (smartphones, laptops, computers, etc.)?

答:
you should use Network Service Discovery

https://developer.android.com/training/connect-devices-wirelessly/nsd.html


问:
JSON data not passing to tableView Cell
I am trying to get the below code to pass JSON data to the table viewCell. I have confirmed that the JSON data is being captured and stored in the variable downloadLenderRates. But I cannot get the values to pass to the tabelView Cell. I confirmed that the cell identifier is named correctly and the swift file that helps manage the tableView cell is named correctly. At this point, I get no error messages and just a blank table when I run the app. I am not sure why!

```<code>class MortgageRatesVC: UIViewController, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    let mortgousURL = URL(string:"http://mortgous.com/JSON/currentRatesJSON.php")!
    var lenderRates = [LenderRate]()

    override func viewDidLoad() {
        super.viewDidLoad()

        downloadJason()

    }

    func downloadJason () {
        lenderRates = []

       // guard let downloadURL = url else { return }
        URLSession.shared.dataTask(with: mortgousURL) { data, urlResponse, error in
            guard let data = data else { return }
            do {
                let dateFormat = DateFormatter()
                dateFormat.locale = Locale(identifier: "en_US_POSIX")
                dateFormat.dateFormat = "yyyy-MM-dd"
                let decoder = JSONDecoder()
                decoder.dateDecodingStrategy = .formatted(dateFormat)
                let downloadLenderRates = try decoder.decode([LenderRate].self, from: data)

               // print(downloadLenderRates)

                self.lenderRates = downloadLenderRates

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }

            } catch {
                print(error)
            }
        }.resume()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return lenderRates.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "LenderCell") as? LenderCell else { return UITableViewCell() }

        cell.lenderNamelbl.text = lenderRates[indexPath.row].financialInstitution
        print(lenderRates[indexPath.row].financialInstitution)

        return cell

    }

}
</code>```

答:
The syntax

```<code>guard let cell = tableView.dequeueReusableCell(withIdentifier: "LenderCell") as? LenderCell else {
      return UITableViewCell()
}
</code>```

is very bad habit.

The guard can only fail if there is a design error which occurs for example if the developer forgot to set the class of the cell to the custom class. In this case you won't see anything in the table view.

This is one of the few cases where force-unwrapping is recommended. If the design is set up properly the cell is valid and its type is the custom class. Further use always the API dequeueReusableCell(withIdentifier:for:) which returns a non-optional cell.

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "LenderCell", for: indexPath) as! LenderCell
</code>```

Title: JSON data not passing to tableView Cell

Body:
I am trying to get the below code to pass JSON data to the table viewCell. I have confirmed that the JSON data is being captured and stored in the variable downloadLenderRates. But I cannot get the values to pass to the tabelView Cell. I confirmed that the cell identifier is named correctly and the swift file that helps manage the tableView cell is named correctly. At this point, I get no error messages and just a blank table when I run the app. I am not sure why!

class MortgageRatesVC: UIViewController, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    let mortgousURL = URL(string:"http://mortgous.com/JSON/currentRatesJSON.php")!
    var lenderRates = [LenderRate]()

    override func viewDidLoad() {
        super.viewDidLoad()

        downloadJason()

    }

    func downloadJason () {
        lenderRates = []

       // guard let downloadURL = url else { return }
        URLSession.shared.dataTask(with: mortgousURL) { data, urlResponse, error in
            guard let data = data else { return }
            do {
                let dateFormat = DateFormatter()
                dateFormat.locale = Locale(identifier: "en_US_POSIX")
                dateFormat.dateFormat = "yyyy-MM-dd"
                let decoder = JSONDecoder()
                decoder.dateDecodingStrategy = .formatted(dateFormat)
                let downloadLenderRates = try decoder.decode([LenderRate].self, from: data)

               // print(downloadLenderRates)

                self.lenderRates = downloadLenderRates

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }

            } catch {
                print(error)
            }
        }.resume()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return lenderRates.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "LenderCell") as? LenderCell else { return UITableViewCell() }

        cell.lenderNamelbl.text = lenderRates[indexPath.row].financialInstitution
        print(lenderRates[indexPath.row].financialInstitution)

        return cell

    }

}

Body:
The syntax

guard let cell = tableView.dequeueReusableCell(withIdentifier: "LenderCell") as? LenderCell else {
      return UITableViewCell()
}

is very bad habit.

The guard can only fail if there is a design error which occurs for example if the developer forgot to set the class of the cell to the custom class. In this case you won't see anything in the table view.

This is one of the few cases where force-unwrapping is recommended. If the design is set up properly the cell is valid and its type is the custom class. Further use always the API dequeueReusableCell(withIdentifier:for:) which returns a non-optional cell.

let cell = tableView.dequeueReusableCell(withIdentifier: "LenderCell", for: indexPath) as! LenderCell


问:
How to check on multiple conditions in PHP
I want to check the security input of a form.
People should answer the security question with the words "allow", "Allow" or 'ALLOW'. These 3 answers are all accepted.

I tried code below but it doesn't pass the if loop if I type one of these 3 answers. What I am doing wrong?

```<code>if( ! isset($_POST['security']) || empty($_POST['security']) || $_POST['security'] != 'allow' || $_POST['security'] != 'Allow' || $_POST['security'] != 'ALLOW') {
      $error .= "<p class=\"message-error\">" . $messages['security_invalid'] . "</p>";
}
</code>```

答:
```<code>$security = 'Allow';
var_dump($security != 'allow' || $security != 'Allow');
</code>```

Output:

```<code>bool(true)
</code>```

The first comparison $security != 'allow' evaluates to true above, which short-circuits the expression.

You could rewrite your expression to something like:

```<code>$security = 'Allow';
var_dump($security != 'allow' && $security != 'Allow' && $security != 'ALLOW');
</code>```

Output:

```<code>bool(false)
</code>```

Which is still a little unwieldy.

You'll likely need to check for errors in more than one place eventually.  Splitting out your validation may help clear things up.

```<code><?php
$security = isset($_POST['security']) ? $_POST['security'] : null;
$email    = isset($_POST['email'])    ? $_POST['email']    : null;
$errors   = [];

if(!in_array($security, array('allow', 'Allow', 'ALLOW')))
    $errors['security'] = 'Invalid security answer.';
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false)
    $errors['email'] = 'Invalid email address.';

$has_errors = (bool) count($errors);

$error = '';
foreach($errors as $error)
    $error .= "<p class=\"message-error\">" . $error . "</p>";
</code>```

Body:
I want to check the security input of a form.
People should answer the security question with the words "allow", "Allow" or 'ALLOW'. These 3 answers are all accepted.

I tried code below but it doesn't pass the if loop if I type one of these 3 answers. What I am doing wrong?

if( ! isset($_POST['security']) || empty($_POST['security']) || $_POST['security'] != 'allow' || $_POST['security'] != 'Allow' || $_POST['security'] != 'ALLOW') {
      $error .= "
" . $messages['security_invalid'] . "
";
}

Body:
$security = 'Allow';
var_dump($security != 'allow' || $security != 'Allow');

Output:

bool(true)

The first comparison $security != 'allow' evaluates to true above, which short-circuits the expression.

You could rewrite your expression to something like:

$security = 'Allow';
var_dump($security != 'allow' && $security != 'Allow' && $security != 'ALLOW');

Output:

bool(false)

Which is still a little unwieldy.

You'll likely need to check for errors in more than one place eventually.  Splitting out your validation may help clear things up.

<?php
$security = isset($_POST['security']) ? $_POST['security'] : null;
$email    = isset($_POST['email'])    ? $_POST['email']    : null;
$errors   = [];

if(!in_array($security, array('allow', 'Allow', 'ALLOW')))
    $errors['security'] = 'Invalid security answer.';
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false)
    $errors['email'] = 'Invalid email address.';

$has_errors = (bool) count($errors);

$error = '';
foreach($errors as $error)
    $error .= "<p class=\"message-error\">" . $error . "</p>";


问:
How to send Spinner selected value in database using wamp server
In this android code it is sending description in database but not sending Spinner value in database

```<code>package com.example.mis_internee.test;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.SQLOutput;
import java.util.HashMap;
import java.util.Map;

public class atd_leave_form extends AppCompatActivity {

    EditText Descr, lastname, age;
    Button insert;
    TextView back;
    RequestQueue requestQueue;
    String insertUrl = "http://192.168.0.102/A/issue.php";
    //    String showUrl = "http://192.168.1.65/tutorial/showStudents.php";
    TextView TV;

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

        Descr = (EditText) findViewById(R.id.descText);
        insert = (Button) findViewById(R.id.send);
        TV = (TextView) findViewById(R.id.uname);
        back = (TextView) findViewById(R.id.Back);
//        TV= (TextView)findViewById(R.id.textView);

        final Spinner staticSpinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter.createFromResource(this, R.array.list,android.R.layout.simple_spinner_item);
        staticAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        staticSpinner.setAdapter(staticAdapter);

//         String name= "Username= "+getIntent().getExtras().getString("username");
//        TV.setText(name);

//       String name= "Username= "+getIntent().getExtras().getString("username");
//        result.setText(name);

//
//        back.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent i = new Intent(atd_leave_form.this, MainActivity.class);
//                startActivity(i);
//
//
//            }
//        });

        requestQueue = Volley.newRequestQueue(getApplicationContext());

        insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String DESCR = Descr.getText().toString();
                final String Spin = staticSpinner.getSelectedItem().toString();

                StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
                    @Override

                    public void onResponse(String response) {
                        if(Descr.getText().toString().equals("")){
                            Toast.makeText(getApplication(),"Please Enter Detail ",Toast.LENGTH_LONG).show();
                        }
                        else if(Descr.getText().toString().length()<10){
                            Toast.makeText(getApplication(),"Text Must be Greater Than 10",Toast.LENGTH_LONG).show();
                        }
                        else{
                            System.out.println(response.toString());
                            Toast.makeText(getApplication(),"Application Submitted Successfully....!",Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(atd_leave_form. this, Issue.class);
                            startActivity(intent);

                        }
                    }}, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }) {

                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String,String> parameters  = new HashMap<String, String>();
                        parameters.put("Descr",Descr.getText().toString());
                        parameters.put("Spin",staticSpinner.toString());
                        return parameters;
                    }
                };
                requestQueue.add(request);
            }

        });

    }

}
</code>```

i used spinner and select value and submit it but no error with submission description in database. i am using oracle web services with wamp server, but description submitting spinner value is not.
thanks in advance

答:
use staticSpinner.getSelectedItem().toString() instead of staticSpinner.toString() in posting parameters
you are posting wrong data check below code

```<code>     insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String DESCR = Descr.getText().toString();
                final String Spin = staticSpinner.getSelectedItem().toString();

                StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
                    @Override

                    public void onResponse(String response) {
                        if(Descr.getText().toString().equals("")){
                            Toast.makeText(getApplication(),"Please Enter Detail ",Toast.LENGTH_LONG).show();
                        }
                        else if(Descr.getText().toString().length()<10){
                            Toast.makeText(getApplication(),"Text Must be Greater Than 10",Toast.LENGTH_LONG).show();
                        }
                        else{
                            System.out.println(response.toString());
                            Toast.makeText(getApplication(),"Application Submitted Successfully....!",Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(atd_leave_form. this, Issue.class);
                            startActivity(intent);

                        }
                    }}, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }) {

                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String,String> parameters  = new HashMap<String, String>();
                        parameters.put("Descr",Descr.getText().toString());
                        parameters.put("Spin",Spin);//change here
                        return parameters;
                    }
                };
                requestQueue.add(request);
            }

        });

    }

}
</code>```

Body:
In this android code it is sending description in database but not sending Spinner value in database

package com.example.mis_internee.test;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.SQLOutput;
import java.util.HashMap;
import java.util.Map;

public class atd_leave_form extends AppCompatActivity {

    EditText Descr, lastname, age;
    Button insert;
    TextView back;
    RequestQueue requestQueue;
    String insertUrl = "http://192.168.0.102/A/issue.php";
    //    String showUrl = "http://192.168.1.65/tutorial/showStudents.php";
    TextView TV;

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

        Descr = (EditText) findViewById(R.id.descText);
        insert = (Button) findViewById(R.id.send);
        TV = (TextView) findViewById(R.id.uname);
        back = (TextView) findViewById(R.id.Back);
//        TV= (TextView)findViewById(R.id.textView);

        final Spinner staticSpinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter.createFromResource(this, R.array.list,android.R.layout.simple_spinner_item);
        staticAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        staticSpinner.setAdapter(staticAdapter);

//         String name= "Username= "+getIntent().getExtras().getString("username");
//        TV.setText(name);

//       String name= "Username= "+getIntent().getExtras().getString("username");
//        result.setText(name);

//
//        back.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent i = new Intent(atd_leave_form.this, MainActivity.class);
//                startActivity(i);
//
//
//            }
//        });

        requestQueue = Volley.newRequestQueue(getApplicationContext());

        insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String DESCR = Descr.getText().toString();
                final String Spin = staticSpinner.getSelectedItem().toString();

                StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
                    @Override

                    public void onResponse(String response) {
                        if(Descr.getText().toString().equals("")){
                            Toast.makeText(getApplication(),"Please Enter Detail ",Toast.LENGTH_LONG).show();
                        }
                        else if(Descr.getText().toString().length()<10){
                            Toast.makeText(getApplication(),"Text Must be Greater Than 10",Toast.LENGTH_LONG).show();
                        }
                        else{
                            System.out.println(response.toString());
                            Toast.makeText(getApplication(),"Application Submitted Successfully....!",Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(atd_leave_form. this, Issue.class);
                            startActivity(intent);

                        }
                    }}, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }) {

                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String,String> parameters  = new HashMap<String, String>();
                        parameters.put("Descr",Descr.getText().toString());
                        parameters.put("Spin",staticSpinner.toString());
                        return parameters;
                    }
                };
                requestQueue.add(request);
            }

        });

    }

}

i used spinner and select value and submit it but no error with submission description in database. i am using oracle web services with wamp server, but description submitting spinner value is not.
thanks in advance

Body:
use staticSpinner.getSelectedItem().toString() instead of staticSpinner.toString() in posting parameters
you are posting wrong data check below code

     insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String DESCR = Descr.getText().toString();
                final String Spin = staticSpinner.getSelectedItem().toString();

                StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
                    @Override

                    public void onResponse(String response) {
                        if(Descr.getText().toString().equals("")){
                            Toast.makeText(getApplication(),"Please Enter Detail ",Toast.LENGTH_LONG).show();
                        }
                        else if(Descr.getText().toString().length()<10){
                            Toast.makeText(getApplication(),"Text Must be Greater Than 10",Toast.LENGTH_LONG).show();
                        }
                        else{
                            System.out.println(response.toString());
                            Toast.makeText(getApplication(),"Application Submitted Successfully....!",Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(atd_leave_form. this, Issue.class);
                            startActivity(intent);

                        }
                    }}, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }) {

                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String,String> parameters  = new HashMap<String, String>();
                        parameters.put("Descr",Descr.getText().toString());
                        parameters.put("Spin",Spin);//change here
                        return parameters;
                    }
                };
                requestQueue.add(request);
            }

        });

    }

}


问:
Cloud Haskell - How to write "pure" for Closures?
I've been playing with Cloud Haskell. I've noticed in the hackage documentation there's a kind of applicative interface. But in particular I'm trying to find or write a function closurePure with the following signature:

```<code>closurePure :: (Typeable a, Binary a) => a -> Closure a
</code>```

This is basically a restricted version of pure.

Whilst the Closure datatype itself is abstract, the following closure provided:

```<code>closure :: Static (ByteString -> a) -> ByteString -> Closure a
</code>```

So I can get this far:

```<code>closurePure :: (Typeable a, Binary a) => a -> Closure a
closurePure x = closure ??? (encode x)
</code>```

The problem is what to put where the ???s are.

My first attempt was the following:

```<code>myDecode :: (Typeable a, Binary a) => Static (ByteString -> a)
myDecode = staticPtr (static decode)
</code>```

But upon reading the GHC docs on static pointers, the show example suggested to me that you can't have a constraint because a constrained function doesn't have a Typeable instance. So I tried the work around suggested using Dict:

```<code>myDecode :: Typeable a => Static (Dict (Binary a) -> ByteString -> a)
myDecode = staticPtr (static (\Dict -> decode))
</code>```

But now I've got the wrong type that doesn't fit into the closure function above.

Is there anyway to write closurePure or something similar (or have I missed it in the Cloud Haskell docs)? Raising binary plain types to Closures seems essential to using the applicative interface given, but I can't work out how to do it.

Note that I can do this:

```<code>class StaticDecode a where
  staticPtrDecode :: StaticPtr (ByteString -> a)

instance StaticDecode Int where
  staticPtrDecode = static Data.Binary.decode

instance StaticDecode Float where
  staticPtrDecode = static Data.Binary.decode

instance StaticDecode Integer where
  staticPtrDecode = static Data.Binary.decode

-- More instances etc...

myPure :: forall a. (Typeable a, StaticDecode a, Binary a) => a -> Closure a
myPure x = closure (staticPtr staticPtrDecode) (encode x)
</code>```

Which works well but basically requires me to repeat an instance for each Binary instance. It seems messy and I'd prefer another way.

答:
You're right, Closure has an applicative-like structure, a fact made even more explicit in both the interface and the implementation of distributed-closure. It's not quite applicative, because in the pure case we do have the additional constraint that the argument must somehow be serializable.

Actually, we have a stronger constraint. Not only must the argument be serializable, but the constraint must itself be serializable. Just like it's hard to serialize functions directly, you can imagine that it's hard to serialize constraints. But just like for functions, the trick is to serialize a static pointer to the constraint itself, if such a static pointer exists. How do we know that such a pointer exists? We could introduce a type class with a single method that gives us the name of the pointer, given a constraint:

```<code>class GimmeStaticPtr c where
  gimmeStaticPtr :: StaticPtr (Dict c)
</code>```

There's a slight technical trick going on here. The kind of the type index for StaticPtr is the kind *, whereas a constraint has kind Constraint.  So we reuse a trick from the constraints library that consists in wrapping a constraint into a data type (Dict above), which like all data types is of kind *. Constraints that have an associated GimmeStaticPtr instance are called static constraints.

In general, it's sometimes useful to compose static constraints to get more static constraints. StaticPtr is not composable, but Closure is. so what distributed-closure actually does is define a similar class, that we'll call,

```<code>class GimmeClosure c where
  gimmeClosure :: Closure (Dict c)
</code>```

Now we can define closurePure in a similar way that you did:

```<code>closurePure :: (Typeable a, GimmeClosure (Binary a)) => a -> Closure a
</code>```

It would be great if in the future, the compiler could resolve GimmeClosure constraints on-the-fly by generating static pointers as needed. But for now, the thing that comes closest is Template Haskell. distributed-closure provides a module to autogenerate GimmeClosure (Cls a) constraints at the definition site for class Cls. See withStatic here.

Incidentally, Edsko de Vries gave a great talk about distributed-closure and the ideas embodied therein.

Body:
I've been playing with Cloud Haskell. I've noticed in the hackage documentation there's a kind of applicative interface. But in particular I'm trying to find or write a function closurePure with the following signature:

closurePure :: (Typeable a, Binary a) => a -> Closure a

This is basically a restricted version of pure.

Whilst the Closure datatype itself is abstract, the following closure provided:

closure :: Static (ByteString -> a) -> ByteString -> Closure a

So I can get this far:

closurePure :: (Typeable a, Binary a) => a -> Closure a
closurePure x = closure ??? (encode x)

The problem is what to put where the ???s are.

My first attempt was the following:

myDecode :: (Typeable a, Binary a) => Static (ByteString -> a)
myDecode = staticPtr (static decode)

But upon reading the GHC docs on static pointers, the show example suggested to me that you can't have a constraint because a constrained function doesn't have a Typeable instance. So I tried the work around suggested using Dict:

myDecode :: Typeable a => Static (Dict (Binary a) -> ByteString -> a)
myDecode = staticPtr (static (\Dict -> decode))

But now I've got the wrong type that doesn't fit into the closure function above.

Is there anyway to write closurePure or something similar (or have I missed it in the Cloud Haskell docs)? Raising binary plain types to Closures seems essential to using the applicative interface given, but I can't work out how to do it.

Note that I can do this:

class StaticDecode a where
  staticPtrDecode :: StaticPtr (ByteString -> a)

instance StaticDecode Int where
  staticPtrDecode = static Data.Binary.decode

instance StaticDecode Float where
  staticPtrDecode = static Data.Binary.decode

instance StaticDecode Integer where
  staticPtrDecode = static Data.Binary.decode

-- More instances etc...

myPure :: forall a. (Typeable a, StaticDecode a, Binary a) => a -> Closure a
myPure x = closure (staticPtr staticPtrDecode) (encode x)

Which works well but basically requires me to repeat an instance for each Binary instance. It seems messy and I'd prefer another way.

Body:
You're right, Closure has an applicative-like structure, a fact made even more explicit in both the interface and the implementation of distributed-closure. It's not quite applicative, because in the pure case we do have the additional constraint that the argument must somehow be serializable.

Actually, we have a stronger constraint. Not only must the argument be serializable, but the constraint must itself be serializable. Just like it's hard to serialize functions directly, you can imagine that it's hard to serialize constraints. But just like for functions, the trick is to serialize a static pointer to the constraint itself, if such a static pointer exists. How do we know that such a pointer exists? We could introduce a type class with a single method that gives us the name of the pointer, given a constraint:

class GimmeStaticPtr c where
  gimmeStaticPtr :: StaticPtr (Dict c)

There's a slight technical trick going on here. The kind of the type index for StaticPtr is the kind *, whereas a constraint has kind Constraint.  So we reuse a trick from the constraints library that consists in wrapping a constraint into a data type (Dict above), which like all data types is of kind *. Constraints that have an associated GimmeStaticPtr instance are called static constraints.

In general, it's sometimes useful to compose static constraints to get more static constraints. StaticPtr is not composable, but Closure is. so what distributed-closure actually does is define a similar class, that we'll call,

class GimmeClosure c where
  gimmeClosure :: Closure (Dict c)

Now we can define closurePure in a similar way that you did:

closurePure :: (Typeable a, GimmeClosure (Binary a)) => a -> Closure a

It would be great if in the future, the compiler could resolve GimmeClosure constraints on-the-fly by generating static pointers as needed. But for now, the thing that comes closest is Template Haskell. distributed-closure provides a module to autogenerate GimmeClosure (Cls a) constraints at the definition site for class Cls. See withStatic here.

Incidentally, Edsko de Vries gave a great talk about distributed-closure and the ideas embodied therein.


问:
How do I call a SignalR hub method from the outside?
This is my Hub code:

public class Pusher : Hub, IPusher
{
    readonly IHubContext _hubContext = GlobalHost.ConnectionManager.GetHubContext<Pusher>();

    public virtual Task PushToOtherInGroup(dynamic group, dynamic data)
    {
        return _hubContext.Clients.Group(group).GetData(data);
    }
}
```

<p>I want call this method in another project with this code:</p>

<pre class="lang-c# prettyprint-override"><code>var pusher = new Pusher.Pusher();
pusher.PushToOtherInGroup("Test", new {exchangeTypeId, price});
</code>```

I want call PushToOtherInGroup,when calling the method i don't get any error.but pusher does not work.

This is my Ui Code:

$(function() {
    hub = $.connection.pusher;
    $.connection.hub.start()
        .done(function() {
            hub.server.subscribe('newPrice');
            console.log('Now connected, connection ID=' + $.connection.hub.id);
        })
        .fail(function() { console.log('Could not Connect!'); });
});

(function() {
    hub.client.GetData = function (data) {
        debugger;
    };
});
```

What is my problem?

答:
Take a look at this link at the topic of (How to call client methods and manage groups from outside the Hub class).

Code example simply creates a singleton instance of the caller class and pass in the IHubContext into it's constructor. Then you have access to desired context.Clients in caller class's methods:

```<code>// This sample only shows code related to getting and using the SignalR context.
public class StockTicker
{
    // Singleton instance
    private readonly static Lazy<StockTicker> _instance = new     Lazy<StockTicker>(() => new StockTicker(GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>()));

private IHubContext _context;

private StockTicker(IHubContext context)
{
    _context = context;
}

// This method is invoked by a Timer object.
private void UpdateStockPrices(object state)
{
    foreach (var stock in _stocks.Values)
    {
        if (TryUpdateStockPrice(stock))
        {
            _context.Clients.All.updateStockPrice(stock);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is my Hub code:

public class Pusher : Hub, IPusher
{
    readonly IHubContext _hubContext = GlobalHost.ConnectionManager.GetHubContext<Pusher>();

    public virtual Task PushToOtherInGroup(dynamic group, dynamic data)
    {
        return _hubContext.Clients.Group(group).GetData(data);
    }
}

I want call this method in another project with this code:

var pusher = new Pusher.Pusher();
pusher.PushToOtherInGroup("Test", new {exchangeTypeId, price});

I want call PushToOtherInGroup,when calling the method i don't get any error.but pusher does not work.

This is my Ui Code:

$(function() {
    hub = $.connection.pusher;
    $.connection.hub.start()
        .done(function() {
            hub.server.subscribe('newPrice');
            console.log('Now connected, connection ID=' + $.connection.hub.id);
        })
        .fail(function() { console.log('Could not Connect!'); });
});

(function() {
    hub.client.GetData = function (data) {
        debugger;
    };
});

What is my problem?

Body:
Take a look at this link at the topic of (How to call client methods and manage groups from outside the Hub class).

Code example simply creates a singleton instance of the caller class and pass in the IHubContext into it's constructor. Then you have access to desired context.Clients in caller class's methods:

// This sample only shows code related to getting and using the SignalR context.
public class StockTicker
{
    // Singleton instance
    private readonly static Lazy<StockTicker> _instance = new     Lazy<StockTicker>(() => new StockTicker(GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>()));

private IHubContext _context;

private StockTicker(IHubContext context)
{
    _context = context;
}

// This method is invoked by a Timer object.
private void UpdateStockPrices(object state)
{
    foreach (var stock in _stocks.Values)
    {
        if (TryUpdateStockPrice(stock))
        {
            _context.Clients.All.updateStockPrice(stock);
        }
    }
}


问:
Return script content that has src attribute
i am having a bit of a problem here and i don't even know if it is possible at all, here's my dilema:

I have this script code:

```<code><script id='script1' src='http://link.to.js'></script>
</code>```

While using firebug, i can clearly see that the script has bee loaded between those tags, like this

```<code><script id='script1' src='http://link.to.js'>
  function something(){
    alert('hi');}
</script>
</code>```

What i want to do is, by means of another script, get the content between those tags, something like

```<code>var x = document.getElementById('script1').innerHtml;
document.getElementById('somedividhere').innerHtml = x;
</code>```

That works perfectly WHEN the code is already part of the html, not when its loaded from src.

I have been looking for this for hours and i have not found any hint, hope someone can help me on this.

答:
I think Firebug only shows you that for convenience sake. If you want to get the code from the script, you'll have to use AJAX.

You could do something like this:

```<code>function ajaxFunction(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            var scriptcontent = ajaxRequest.responseText;
            //Do something with the content
        }
    }
    ajaxRequest.open("GET", document.getElementById('script1').src, true);
    ajaxRequest.send(null);
}
</code>```

Just a few notes:

This will only work for scripts
located on your site due to the
same origin
policy.

I took the ajax code from this
site
and modified it.

This would be a lot
easier with
jQuery

ContentLicense: CC BY-SA 2.5

Body:
i am having a bit of a problem here and i don't even know if it is possible at all, here's my dilema:

I have this script code:

While using firebug, i can clearly see that the script has bee loaded between those tags, like this

What i want to do is, by means of another script, get the content between those tags, something like

var x = document.getElementById('script1').innerHtml;
document.getElementById('somedividhere').innerHtml = x;

That works perfectly WHEN the code is already part of the html, not when its loaded from src.

I have been looking for this for hours and i have not found any hint, hope someone can help me on this.

Body:
I think Firebug only shows you that for convenience sake. If you want to get the code from the script, you'll have to use AJAX.

You could do something like this:

function ajaxFunction(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            var scriptcontent = ajaxRequest.responseText;
            //Do something with the content
        }
    }
    ajaxRequest.open("GET", document.getElementById('script1').src, true);
    ajaxRequest.send(null);
}

Just a few notes:

This will only work for scripts
located on your site due to the
same origin
policy.

I took the ajax code from this
site
and modified it.

This would be a lot
easier with
jQuery


问:
Dropdown CSS with local storage

A user can pick a theme from the dropdown and selected theme would be stored in local storage. While it can save the dropdown value in localstorage, it's not calling the stylesheet. Please help, thanks!

Pardon the Frankenstein type of code. JS's foreign to me, I'm a designer by trade.

```<code><html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <link href="style1.css" rel="stylesheet" type="text/css" title="s1" id="s1"/>
</head>
<body>

<select id="mySelect" class="test">
    <option value="style1.css">Option A</option>
    <option value="style2.css">Option B</option>
    <option value="style3.css">Option C</option>
</select>

<!--local storage-->
<script>
 $('.test').change(function() {
    localStorage.setItem(this.id, this.value);
}).val(function() {
    return localStorage.getItem(this.id)
});
</script>
<!--dropdown css-->

 <script>
        function setStyleSource (linkID, sourceLoc) {
      var theLink = document.getElementById(linkID);
      theLink.href = sourceLoc;
      console.log(theLink.href);
    }

    document.getElementById("mySelect").addEventListener("change", function(){
        var selected = this.options[this.selectedIndex].value;
        setStyleSource ("s1", selected)
    });
    </script>

</body>
</html>
</code>```

1.the dropdown to change css works.
2.localstorage for selected option works.
But the stored selected option doesn't actually show its own css sheet (it's displaying the default css instead).

答:
Changing dropdownvalue with val() doesnt trigger change event, you will have to trigger it manually after setting the value by doing:

```<code>$('.test').val(localStorage.getItem(this.id)).trigger('change'); // OR .change()
</code>```

Also add event listener for change before triggering the same:

```<code>function setStyleSource(linkID, sourceLoc) {
  var theLink = document.getElementById(linkID);
  theLink.href = sourceLoc;
  console.log(theLink.href);
}

document.getElementById("mySelect").addEventListener("change", function() {
  var selected = this.options[this.selectedIndex].value;
  setStyleSource("s1", selected)
});

$('.test').change(function() {
  localStorage.setItem(this.id, this.value);
}).val(function() {
  return localStorage.getItem(this.id)
}).trigger('change');
</code>```

Title: Dropdown CSS with local storage

Body:
A user can pick a theme from the dropdown and selected theme would be stored in local storage. While it can save the dropdown value in localstorage, it's not calling the stylesheet. Please help, thanks!

Pardon the Frankenstein type of code. JS's foreign to me, I'm a designer by trade.

    <link href="style1.css" rel="stylesheet" type="text/css" title="s1" id="s1"/>

<select id="mySelect" class="test">
    <option value="style1.css">Option A</option>
    <option value="style2.css">Option B</option>
    <option value="style3.css">Option C</option>
</select>

1.the dropdown to change css works.
2.localstorage for selected option works.
But the stored selected option doesn't actually show its own css sheet (it's displaying the default css instead).

Body:
Changing dropdownvalue with val() doesnt trigger change event, you will have to trigger it manually after setting the value by doing:

$('.test').val(localStorage.getItem(this.id)).trigger('change'); // OR .change()

Also add event listener for change before triggering the same:

function setStyleSource(linkID, sourceLoc) {
  var theLink = document.getElementById(linkID);
  theLink.href = sourceLoc;
  console.log(theLink.href);
}

document.getElementById("mySelect").addEventListener("change", function() {
  var selected = this.options[this.selectedIndex].value;
  setStyleSource("s1", selected)
});

$('.test').change(function() {
  localStorage.setItem(this.id, this.value);
}).val(function() {
  return localStorage.getItem(this.id)
}).trigger('change');


问:
Pygame – Creating multiple lines with the same function while keeping individual functionality
I'm creating a game for my cs class right now and the model is Tron. Basically, I have my two players going at all times and they can either turn left or right (at 90° angles) whilst creating lines behind them. I want to create a function that will draw those lines given the last position of the player. However, what I can't figure out is how to create new lines when the player turns while keeping the old one functioning as it should (I will get to what this means in a bit). Also, since I will be calling this "draw lines" function from the same variable every time, will I be able to detect a collision between the player and any given line by calling that one variable, even though the lines are all technically different? Is this an optmical situation for a dictionary?

So far me and my partner have tried elongating one rect, creating a list (although I don't have much experience in this area, so maybe I just messed it up royally) and otherwise literally creating mulitple variables...

My code (if you decide to check out the code and play the game just keep in mind the next button from the instructions screen is broken for some reason and requires spam clicking).

答:
You could do something like this: Use pygame.Rects for the lines because they have useful collision detection methods. When the player moves, you just increase the size of the current rect and when the direction is changed, you can append this rect to a list of rects and create a new one. For the collision detection you would iterate over the rects list and use the player rect's .colliderect method.

Here's a complete solution:

```<code>import pygame as pg
from pygame.math import Vector2

def main():
    screen = pg.display.set_mode((800, 600))
    clock = pg.time.Clock()

    background_color = (30, 30, 30)
    blue = pg.Color('dodgerblue1')
    lightblue = pg.Color('cadetblue3')
    sienna = pg.Color('sienna1')
    player_color = lightblue

    player = pg.Rect(400, 300, 10, 10)
    vel = Vector2(3, 0)
    current_rect = pg.Rect(400, 300, 0, 10)
    rects = [current_rect]

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_d:
                    vel.x = 3
                    vel.y = 0
                    # A new rect with 0 width.
                    current_rect = pg.Rect(player.topleft, (0, 10))
                elif event.key == pg.K_a:
                    vel.x = -3
                    vel.y = 0
                    current_rect = pg.Rect(player.topright, (0, 10))
                elif event.key == pg.K_w:
                    vel.y = -3
                    vel.x = 0
                    current_rect = pg.Rect(player.bottomleft, (10, 0))
                elif event.key == pg.K_s:
                    vel.y = 3
                    vel.x = 0
                    current_rect = pg.Rect(player.topleft, (10, 0))
                if event.key in (pg.K_d, pg.K_a, pg.K_w, pg.K_s):
                    # Append the new current rect.
                    rects.append(current_rect)

        # Update the position of the player.
        player[0] += vel.x
        player[1] += vel.y

        # Need to adjust the rect position if we're moving up or left.
        if vel.x < 0:
            current_rect.x += vel.x
        elif vel.y < 0:
            current_rect.y += vel.y
        # Increase the size of the current rect.
        # abs is needed to avoid negative width & height.
        current_rect.w += abs(vel.x)
        current_rect.h += abs(vel.y)

        player_color = lightblue
        # Collision detection with the rects.
        for line_rect in rects:
            if player.colliderect(line_rect):
                player_color = sienna
                break

        screen.fill(background_color)
        # Draw all rects in the list.
        for line_rect in rects:
            pg.draw.rect(screen, blue, line_rect)
        # Draw the player rect.
        pg.draw.rect(screen, player_color, player)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
</code>```

Body:
You could do something like this: Use pygame.Rects for the lines because they have useful collision detection methods. When the player moves, you just increase the size of the current rect and when the direction is changed, you can append this rect to a list of rects and create a new one. For the collision detection you would iterate over the rects list and use the player rect's .colliderect method.

Here's a complete solution:

import pygame as pg
from pygame.math import Vector2

def main():
    screen = pg.display.set_mode((800, 600))
    clock = pg.time.Clock()

    background_color = (30, 30, 30)
    blue = pg.Color('dodgerblue1')
    lightblue = pg.Color('cadetblue3')
    sienna = pg.Color('sienna1')
    player_color = lightblue

    player = pg.Rect(400, 300, 10, 10)
    vel = Vector2(3, 0)
    current_rect = pg.Rect(400, 300, 0, 10)
    rects = [current_rect]

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_d:
                    vel.x = 3
                    vel.y = 0
                    # A new rect with 0 width.
                    current_rect = pg.Rect(player.topleft, (0, 10))
                elif event.key == pg.K_a:
                    vel.x = -3
                    vel.y = 0
                    current_rect = pg.Rect(player.topright, (0, 10))
                elif event.key == pg.K_w:
                    vel.y = -3
                    vel.x = 0
                    current_rect = pg.Rect(player.bottomleft, (10, 0))
                elif event.key == pg.K_s:
                    vel.y = 3
                    vel.x = 0
                    current_rect = pg.Rect(player.topleft, (10, 0))
                if event.key in (pg.K_d, pg.K_a, pg.K_w, pg.K_s):
                    # Append the new current rect.
                    rects.append(current_rect)

        # Update the position of the player.
        player[0] += vel.x
        player[1] += vel.y

        # Need to adjust the rect position if we're moving up or left.
        if vel.x < 0:
            current_rect.x += vel.x
        elif vel.y < 0:
            current_rect.y += vel.y
        # Increase the size of the current rect.
        # abs is needed to avoid negative width & height.
        current_rect.w += abs(vel.x)
        current_rect.h += abs(vel.y)

        player_color = lightblue
        # Collision detection with the rects.
        for line_rect in rects:
            if player.colliderect(line_rect):
                player_color = sienna
                break

        screen.fill(background_color)
        # Draw all rects in the list.
        for line_rect in rects:
            pg.draw.rect(screen, blue, line_rect)
        # Draw the player rect.
        pg.draw.rect(screen, player_color, player)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()


问:
How do I run a copied project in Node.js
https://github.com/gleitz/mahjong

I want to run this app on my windows,
the directions say:
-Install dependencies with npm update
-Start the application with node app.js

it's sound easy so I try myself.

1.Fist of all , I install node.js on it's official website (https://nodejs.org/en/)
I　download the 8.9.3 version.

after installing node.js
2.open the command line and go to the project path.

3.then I input the command npm update.
it works,and the node_modules folder is created.But there are some warn message

4.finally input the command node app.js... it's not work with many error message

following is wrong message

I wonder know how should I do.Is any thing I didn't installed?

Please help me.I really want to research this mahjong project.

答:
Before running npm update in the directory where you have your project, you should run npm install first to install all the required dependencies needed for the project to run.

So I advice to delete the node_modules directory that was created after you ran npm update, after which you can then run npm install. This should solve your issue.


问:
How can you use a WebSocket client in a Flutter app?
Is there a way to open a WebSocket client in a Flutter app? Flutter doesn't allow you to import dart:html, which is the normal way of using a WebSocket client.</p>

答:
In Flutter you can use dart:io which supports WebSocket

https://api.dartlang.org/stable/1.24.2/dart-io/WebSocket-class.html


问:
Facebook graph api audience fbid does not accept
I want to integrate the facebook audience sdk.Documents are very difficult to solve. I'm stuck in a place

```<code>FacebookAdsApi.init(app_id=APP_ID,app_secret=APP_SECRET,access_token=ACCES

_TOKEN)
ad_account = AdAccount(fbid=FACEBOOK_ID)

params = {
    CustomAudience.Field.subtype: CustomAudience.Subtype.custom,
    CustomAudience.Field.name: 'My new CA',
    CustomAudience.Field.description: 'People who bought on my website',
}
audience = ad_account.create_custom_audience(params=params)
</code>```

When I send reqeust on python The bottom warning comes to me. But Im sure my fbid is true I got the necessary permissions but still the same situation

```<code>Status:  400
  Response:
    {
      "error": {
        "fbtrace_id": "HyhfMfSiw3S",
        "type": "GraphMethodException",
        "message": "Unsupported post request. Object with ID 'act_xxxxxxxx' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
        "error_subcode": 33,
        "code": 100
      }
    }
</code>```

答: You need to make sure the app access token you are using should have access to your facebook ad project.</p>

Body:
I want to integrate the facebook audience sdk.Documents are very difficult to solve. I'm stuck in a place

FacebookAdsApi.init(app_id=APP_ID,app_secret=APP_SECRET,access_token=ACCES

_TOKEN)
ad_account = AdAccount(fbid=FACEBOOK_ID)

params = {
    CustomAudience.Field.subtype: CustomAudience.Subtype.custom,
    CustomAudience.Field.name: 'My new CA',
    CustomAudience.Field.description: 'People who bought on my website',
}
audience = ad_account.create_custom_audience(params=params)

When I send reqeust on python The bottom warning comes to me. But Im sure my fbid is true I got the necessary permissions but still the same situation

Status:  400
  Response:
    {
      "error": {
        "fbtrace_id": "HyhfMfSiw3S",
        "type": "GraphMethodException",
        "message": "Unsupported post request. Object with ID 'act_xxxxxxxx' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
        "error_subcode": 33,
        "code": 100
      }
    }


问:
Loop through dictionary keys to get values based on input
1) In my program I start with prompting a user for input.

2) I would then like to loop through the users input to get all the characters in that string, query each character individually against the dictionaries keys.

3) If a character from the input matches a key in the dictionary, I want that key's value returned.

4) This needs to be repeated for each character and the result should print those values returned in a string

To try and explain further, here is my dictionary:

```<code>dataDict = {
"a":"1",
"b":"2",
"c":"3",
}
</code>```

For example:

If my input is abc, my result should be 123

If my input is cba, my result should be 321

and so on...

So far, this works if the string is only one character using the below code.
If i enter two characters, it just returns nothing.

```<code>dataInput=input("Enter stuff: ")

for key,value in dataDict.items():
    if dataInput == key:
    print(value)
</code>```

How can I acheive the results i'm after?

答:
You should be iterating over the input string, not the dictionary. Also, you might want to use .get() in case the users enters a characters that's not in the dictionary:

```<code>for letter in dataInput:
    print(dataDict.get(letter,"X"))
</code>```

This will print each letter on its individual line. If you want to print them in a single line, you can add the end="" parameter to the print function (and print an empty line after you're done).

The comparison you're doing would never work (in the first iteration, it would amount to if "abc" == "a", I hope that makes it obvious).

Body:
1) In my program I start with prompting a user for input.

2) I would then like to loop through the users input to get all the characters in that string, query each character individually against the dictionaries keys.

3) If a character from the input matches a key in the dictionary, I want that key's value returned.

4) This needs to be repeated for each character and the result should print those values returned in a string

To try and explain further, here is my dictionary:

dataDict = {
"a":"1",
"b":"2",
"c":"3",
}

For example:

If my input is abc, my result should be 123

If my input is cba, my result should be 321

and so on...

So far, this works if the string is only one character using the below code.
If i enter two characters, it just returns nothing.

dataInput=input("Enter stuff: ")

for key,value in dataDict.items():
    if dataInput == key:
    print(value)

How can I acheive the results i'm after?

Body:
You should be iterating over the input string, not the dictionary. Also, you might want to use .get() in case the users enters a characters that's not in the dictionary:

for letter in dataInput:
    print(dataDict.get(letter,"X"))

This will print each letter on its individual line. If you want to print them in a single line, you can add the end="" parameter to the print function (and print an empty line after you're done).

The comparison you're doing would never work (in the first iteration, it would amount to if "abc" == "a", I hope that makes it obvious).


答: You're iterating through the wrong thing. You should be iterating through the input. You don't need to iterate through the dict, because you can just look up by key.</p>

Title: Loop through dictionary keys to get values based on input


问:
How do I delete duplicate rows in this (mildly) complicated MySQL database situation?
Ok.  Please bear with me, I suck at explaining things.

I have a database of contact information that is gathered through a form on a website.  Obviously, people press submit more than once accidentally (or on purpose, but fixing is a different issue) so there are a LOT of duplicate rows in this database.

So, table1 holds contact information as such:

```<code>ID  |  date  |  unique ID code  |  first name, blah blah
1      stuff    20110101ba78b      joe
</code>```

And table2 holds related data joined by the unique ID code field, as such:

```<code>ID  |  data  |  unique ID code
1      a        20110101ba78b
2      b        20110101ba78b
</code>```

So, table2 holds multiple values for each person.  That's the structure of the table (and there are about a million rows in table2, so I'd rather not change the structure right now).

So my dilemma is this:  I know it's easy to make a temporary table and SELECT DISTINCT(all fields), but I want to keep the unique ID field for at least 1 of the duplicate rows.  If I keep the unique ID field though, it is unique for each row, even if the other data is exactly the same so SELECT DISTINCT(all fields) will not work, it will keep every row.  Hopefully I explained this thoroughly.  Please ask me for more information if needed.

EDIT:  I'm sure I could get rid of the ID field for each table, but as far as I'm concerned it's just .... there to be there.

答:
With the first clarification and a little reading between the lines, we can guess that it will be satisfactory to keep just the first or last entry for a given 'Unique ID Code' in Table1, where first or last means oldest or newest entry.  The queries are the same except for MAX vs MIN.  I'm assuming the 'date' column contains a fine enough (1 second or smaller) granularity that you don't get the same Unique ID Code twice in a time quantum; this is unlikely to be the case if the 'date' column really only contains a DATE (year, month, day) value, but probably is the case if you have a TIMESTAMP(3) and might well be the case with TIMESTAMP.

As always with SQL, build the query up in stages, nice and gently.

Find the newest entry for each Unique ID Code with multiple entries

```<code>SELECT Unique_ID_Code, MAX(date) AS Newest
  FROM Table1
 GROUP BY Unique_ID_Code
HAVING COUNT(*) > 1
</code>```

Find the details for the Unique ID Code matching the newest entry

```<code>SELECT T1.*
  FROM Table1 AS T1
  JOIN (SELECT Unique_ID_Code, MAX(date) AS Newest
          FROM Table1
         GROUP BY Unique_ID_Code
        HAVING COUNT(*) > 1
       ) AS M
    ON M.Unique_ID_Code = T1.Unique_ID_Code AND M.Newest = T1.Date
</code>```

Now the tricky stuff

What you do next depends on how much you trust the transaction support in your DBMS and how big the Table1 is, and on whether you have ON DELETE CASCADE constraints on your foreign keys, and ...

You could create a temporary table with the rows selected by the second query above (MySQL syntax, I believe; other DBMS use different notations for this).

```<code>CREATE TEMPORARY TABLE KeepTheseRows
    SELECT T1.*
      FROM Table1 AS T1
      JOIN (SELECT Unique_ID_Code, MAX(date) AS Newest
              FROM Table1
             GROUP BY Unique_ID_Code
            HAVING COUNT(*) > 1
           ) AS M
        ON M.Unique_ID_Code = T1.Unique_ID_Code AND M.Newest = T1.Date;
</code>```

then delete all the rows from Table1 that match the duplicate unique ID codes:

```<code>DELETE FROM Table1
    WHERE Unique_ID_Code IN (SELECT Unique_ID_Code FROM KeepTheseRows);
</code>```

and then reinstate the rows to be kept:

```<code>INSERT INTO Table
    SELECT * FROM KeepTheseRows;
</code>```

You may need to defer constraint checking while this happens, or you may need to drop the foreign key constraints while this occurs.  You need to worry about activity while this operation occurs; it would be best if people were not inserting rows into Table1 while this is running.  If they are modifying the table as you run, you may find that you have to do the processing several times.  You should add a unique constraint to Table1.Unique_ID_Code just as soon as possible so you don't get into the mess again.  (And don't forget to re-enable any deferred constraints or recreate and dropped foreign keys.)

There probably are other equivalent ways to do this; this relies only on standard (SQL-92) SQL apart from the temporary table notation.

Experiment with a copy of your production database.

Body:
Ok.  Please bear with me, I suck at explaining things.

I have a database of contact information that is gathered through a form on a website.  Obviously, people press submit more than once accidentally (or on purpose, but fixing is a different issue) so there are a LOT of duplicate rows in this database.

So, table1 holds contact information as such:

ID  |  date  |  unique ID code  |  first name, blah blah
1      stuff    20110101ba78b      joe

And table2 holds related data joined by the unique ID code field, as such:

ID  |  data  |  unique ID code
1      a        20110101ba78b
2      b        20110101ba78b

So, table2 holds multiple values for each person.  That's the structure of the table (and there are about a million rows in table2, so I'd rather not change the structure right now).

So my dilemma is this:  I know it's easy to make a temporary table and SELECT DISTINCT(all fields), but I want to keep the unique ID field for at least 1 of the duplicate rows.  If I keep the unique ID field though, it is unique for each row, even if the other data is exactly the same so SELECT DISTINCT(all fields) will not work, it will keep every row.  Hopefully I explained this thoroughly.  Please ask me for more information if needed.

EDIT:  I'm sure I could get rid of the ID field for each table, but as far as I'm concerned it's just .... there to be there.

Body:
With the first clarification and a little reading between the lines, we can guess that it will be satisfactory to keep just the first or last entry for a given 'Unique ID Code' in Table1, where first or last means oldest or newest entry.  The queries are the same except for MAX vs MIN.  I'm assuming the 'date' column contains a fine enough (1 second or smaller) granularity that you don't get the same Unique ID Code twice in a time quantum; this is unlikely to be the case if the 'date' column really only contains a DATE (year, month, day) value, but probably is the case if you have a TIMESTAMP(3) and might well be the case with TIMESTAMP.

As always with SQL, build the query up in stages, nice and gently.

Find the newest entry for each Unique ID Code with multiple entries

SELECT Unique_ID_Code, MAX(date) AS Newest
  FROM Table1
 GROUP BY Unique_ID_Code
HAVING COUNT(*) > 1

Find the details for the Unique ID Code matching the newest entry

SELECT T1.*
  FROM Table1 AS T1
  JOIN (SELECT Unique_ID_Code, MAX(date) AS Newest
          FROM Table1
         GROUP BY Unique_ID_Code
        HAVING COUNT(*) > 1
       ) AS M
    ON M.Unique_ID_Code = T1.Unique_ID_Code AND M.Newest = T1.Date

Now the tricky stuff

What you do next depends on how much you trust the transaction support in your DBMS and how big the Table1 is, and on whether you have ON DELETE CASCADE constraints on your foreign keys, and ...

You could create a temporary table with the rows selected by the second query above (MySQL syntax, I believe; other DBMS use different notations for this).

CREATE TEMPORARY TABLE KeepTheseRows
    SELECT T1.*
      FROM Table1 AS T1
      JOIN (SELECT Unique_ID_Code, MAX(date) AS Newest
              FROM Table1
             GROUP BY Unique_ID_Code
            HAVING COUNT(*) > 1
           ) AS M
        ON M.Unique_ID_Code = T1.Unique_ID_Code AND M.Newest = T1.Date;

then delete all the rows from Table1 that match the duplicate unique ID codes:

DELETE FROM Table1
    WHERE Unique_ID_Code IN (SELECT Unique_ID_Code FROM KeepTheseRows);

and then reinstate the rows to be kept:

INSERT INTO Table
    SELECT * FROM KeepTheseRows;

You may need to defer constraint checking while this happens, or you may need to drop the foreign key constraints while this occurs.  You need to worry about activity while this operation occurs; it would be best if people were not inserting rows into Table1 while this is running.  If they are modifying the table as you run, you may find that you have to do the processing several times.  You should add a unique constraint to Table1.Unique_ID_Code just as soon as possible so you don't get into the mess again.  (And don't forget to re-enable any deferred constraints or recreate and dropped foreign keys.)

There probably are other equivalent ways to do this; this relies only on standard (SQL-92) SQL apart from the temporary table notation.

Experiment with a copy of your production database.


问:
How to put a folder which has large files (.avi and .pdf) as well as source files (.py, .m) in multiple directories under git source control?
I have a large folder of ~ 4 GB. This folder has python source code, Matlab source code, a lot ~50-80 MB video files as well as pdf files. I was originally planning to put them all under .git source control and put them in github, but I found that it made everything really slow. Further, github started complaining that I am using too much of their bandwidth.

I am thinking that a better approach would be to keep the .avi or other large files in the similar structure, but to only put the source files under git control by adding the lines

```<code>*.avi
*.pdf
*.mp4
!*.py
!*.m
</code>```

The above line will not put .avi, .pdf and .mp4 files under source control, but always put .py and .m files under source control.

The .pdf, .mp4 files are important, but I just don’t want to upload to github. I would also want to change or checkout differenct branches of the repository at certain times in future.

 Questions

Say I have a folder now called videos under a certain subdirectory such as

Videos/
         Oop.avi

Say the previous version of the folder doesn’t have this. Will the Videos directory be completely overwritten if I checkout the previous branch?

I am sure there will be other permutations and combinations of the above scenario which might happen.

What is the best practice for such cases, when the large files are mixed in with source files in various directories? But you don’t want to necessarily share the large files, but don’t want to lose them either, if you checkout a previous branch which didn’t have the large files.

答:
Files that match a gitignore pattern are ignored by git: it won't touch them. So ignored files won't be deleted. (BTW, it's also the case for any untracked files, ignored ones will just be not visible in git status)

The only way to delete ignored files through git is with git clean -x

Body:
I have a large folder of ~ 4 GB. This folder has python source code, Matlab source code, a lot ~50-80 MB video files as well as pdf files. I was originally planning to put them all under .git source control and put them in github, but I found that it made everything really slow. Further, github started complaining that I am using too much of their bandwidth.

I am thinking that a better approach would be to keep the .avi or other large files in the similar structure, but to only put the source files under git control by adding the lines

*.avi
*.pdf
*.mp4
!*.py
!*.m

The above line will not put .avi, .pdf and .mp4 files under source control, but always put .py and .m files under source control.

The .pdf, .mp4 files are important, but I just don’t want to upload to github. I would also want to change or checkout differenct branches of the repository at certain times in future.

 Questions

Say I have a folder now called videos under a certain subdirectory such as

Videos/
         Oop.avi

Say the previous version of the folder doesn’t have this. Will the Videos directory be completely overwritten if I checkout the previous branch?

I am sure there will be other permutations and combinations of the above scenario which might happen.

What is the best practice for such cases, when the large files are mixed in with source files in various directories? But you don’t want to necessarily share the large files, but don’t want to lose them either, if you checkout a previous branch which didn’t have the large files.


问:
sql query to get all sub-categories and their sub-categories and so on of a category
my categories table is

```<code>id          parent_id
----------   -----------
1           0
2           1
3           1
4           2
5           3
6           2
7           4
8           3
9           5
10          6
11          7
12          4
13          10
14          9
</code>```

suppose I want to get categories of category_id 2 then output should be like as

```<code>id 2,4,6,7,10,11,12,13
</code>```

and for category 3 o/p should be

```<code>id 3,5,8,9,14
</code>```

and for 1 should be

```<code>id 1,2,3,4,5,6,7,8,9,10,11,12,13,14
</code>```

and for 4 should be

```<code>id 4,7,11,12
</code>```

please help to get this query

答:
after a lot of searched, I got this solution and it's working for me if anyone has a better solution then please share and you also can comment drawback of this below query on this answer</p>

```<code>select id from (select * from categories order by parent_id, id) categories, (select @pv := '2') initialisation where find_in_set(parent_id, @pv) > 0 and @pv := concat(@pv, ',', id)
</code>```

Body:
my categories table is

id          parent_id
----------   -----------
1           0
2           1
3           1
4           2
5           3
6           2
7           4
8           3
9           5
10          6
11          7
12          4
13          10
14          9

suppose I want to get categories of category_id 2 then output should be like as

id 2,4,6,7,10,11,12,13

and for category 3 o/p should be

id 3,5,8,9,14

and for 1 should be

id 1,2,3,4,5,6,7,8,9,10,11,12,13,14

and for 4 should be

id 4,7,11,12

please help to get this query

Body:
after a lot of searched, I got this solution and it's working for me if anyone has a better solution then please share and you also can comment drawback of this below query on this answer

select id from (select * from categories order by parent_id, id) categories, (select @pv := '2') initialisation where find_in_set(parent_id, @pv) > 0 and @pv := concat(@pv, ',', id)


问:
How to create a button with function parameter?
I want to create a button by using function below, example createGetInfo(120,Test,1) I want the result become a 'Test' button with 120 width but the function below fail, How can I put the parameter inside the button tag?</p>

```<code>function createGetInfo(size,wording,filter) {
    var GetInfo = $("<button class='eqGroupBtn' type='button' class='btn' style='width:size'>wording</button>");
    secondLevelMenuDiv.append(GetInfo);
    GetInfo.click(function(){
        Do something...
    });
};
</code>```

答:
for binding event with dynamically created element you need to use on method of jquery, so your code will be as below

```<code>$( document ).ready(function() {
  var size=100;
    var GetInfo = $("<button class='eqGroupBtn' id='btnGetInfo' type='button' class='btn' style='width:"+size+"px;'>wording</button>");
    $("body").append(GetInfo);

     $( "#btnGetInfo" ).on( "click", function() {
              alert( $( this ).text() );
     });
});
</code>```

Working jsfiddle demo : https://jsfiddle.net/pranayamr/uuvtx5ga/

read more about on function here : http://api.jquery.com/on/

one more change in you code is always create element in html DOM with ID attribute , so i added Id for button which is btnGetInfo

Body:
I want to create a button by using function below, example createGetInfo(120,Test,1) I want the result become a 'Test' button with 120 width but the function below fail, How can I put the parameter inside the button tag?

function createGetInfo(size,wording,filter) {
    var GetInfo = $("<button class='eqGroupBtn' type='button' class='btn' style='width:size'>wording</button>");
    secondLevelMenuDiv.append(GetInfo);
    GetInfo.click(function(){
        Do something...
    });
};

Body:
for binding event with dynamically created element you need to use on method of jquery, so your code will be as below

$( document ).ready(function() {
  var size=100;
    var GetInfo = $("<button class='eqGroupBtn' id='btnGetInfo' type='button' class='btn' style='width:"+size+"px;'>wording</button>");
    $("body").append(GetInfo);

     $( "#btnGetInfo" ).on( "click", function() {
              alert( $( this ).text() );
     });
});

Working jsfiddle demo : https://jsfiddle.net/pranayamr/uuvtx5ga/

read more about on function here : http://api.jquery.com/on/

one more change in you code is always create element in html DOM with ID attribute , so i added Id for button which is btnGetInfo


问:
I was trying to find the magical number in the given range but its giving me error
This is giving me the error like i can't be used in std::is_floating_point because i is not a constant.  </p>

```<code>int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
     int k=18;
    int prime=0, nonprime=0;
    int N=100;
 int i=1, z=0, a=0, b=0;
 int req = 1;
    for(i=2; i<=N; i++){
         if(std::is_floating_point<i/10>){
            for(z=1; z<=i; z++){
                if((i/z) == i){
                    if((i/z) == 0){
                       prime=prime+1;
                    }else{
                        nonprime=nonprime+1;
                    }
</code>```

答:
If you adhere to use template, making a compile-time loop wheel is a must:

Here is a good reference with c++11(which reduces difficulties): https://www.codeproject.com/Articles/857354/Compile-Time-Loops-with-Cplusplus-Creating-a-Gener

Then, welcome to black magic : )

Body:
This is giving me the error like i can't be used in std::is_floating_point because i is not a constant.

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
     int k=18;
    int prime=0, nonprime=0;
    int N=100;
 int i=1, z=0, a=0, b=0;
 int req = 1;
    for(i=2; i<=N; i++){
         if(std::is_floating_point){
            for(z=1; z<=i; z++){
                if((i/z) == i){
                    if((i/z) == 0){
                       prime=prime+1;
                    }else{
                        nonprime=nonprime+1;
                    }


问:
how to select record based on max value and where clause in LINQ to Entities
i have following records in my table tbl_JobMaster

```<code>ID  CIN   JobNumber Version
1   ABC   100           1.0
2   ABC   100           2.0
3   ABC   200           1.0
4   ABC   200           2.0
5   ABC   200           3.0
6   XYZ   300           1.0
</code>```

i want list of records based on CIN column and MAX(Version) and unique JobNumber

for e.g. CIN=ABC
so output should be as follows

```<code>ID  CIN   JobNumber Version
2   ABC   100           2.0
5   ABC   200           3.0
</code>```

I tried following code but it isn't working

```<code>var result=(from job in entity.tbl_JobMaster
            where job.CIN=="ABC" && job.Version==entity.tbl_JobMaster.Where(p=>p.ID==job.ID).Max(p=>p.Version)
            select job).Distinct();
</code>```

答:
First group by the CIN and JobNumber

```<code>var temp = from job in entity.tbl_JobMaster
           where job.CIN == "ABC"
           group job by new { job.CIN, job.JobNumber } into g
           select g;
</code>```

Then order the items in groups by Version descending, and select the first one

```<code>var result = temp.Select(o => o.OrderByDescending(t => t.Version).First());
</code>```

Body:
i have following records in my table tbl_JobMaster

ID  CIN   JobNumber Version
1   ABC   100           1.0
2   ABC   100           2.0
3   ABC   200           1.0
4   ABC   200           2.0
5   ABC   200           3.0
6   XYZ   300           1.0

i want list of records based on CIN column and MAX(Version) and unique JobNumber

for e.g. CIN=ABC
so output should be as follows

ID  CIN   JobNumber Version
2   ABC   100           2.0
5   ABC   200           3.0

I tried following code but it isn't working

var result=(from job in entity.tbl_JobMaster
            where job.CIN=="ABC" && job.Version==entity.tbl_JobMaster.Where(p=>p.ID==job.ID).Max(p=>p.Version)
            select job).Distinct();

Body:
First group by the CIN and JobNumber

var temp = from job in entity.tbl_JobMaster
           where job.CIN == "ABC"
           group job by new { job.CIN, job.JobNumber } into g
           select g;

Then order the items in groups by Version descending, and select the first one

var result = temp.Select(o => o.OrderByDescending(t => t.Version).First());


问:
HTML JS canvas inside div not showing up
So, I'm trying to make a simple game with HTML/CSS/JS and there's a problem with canvas. My full code is at https://pastebin.com/DM2ChXR2 and it has a part like:

```<code><div>
...
</div>
<p id="footer"></p>
__________
document.body.insertBefore(this.canvas, document.getElementById("footer"));
</code>```

Right now it works as expected, drawing canvas on top of all contents when the "start" button is pressed. But if I put the anchor tag inside the div like:

```<code><div>
...
<p id="footer"></p>
</div>
</code>```

then the canvas would not show up. I can't see the logical reason for that, what am I missing?

答: Okay, the reason was improper usage of insertBefore(). Should have set up an id for div and used document.getElementById("mainDiv").appendChild(this.canvas); instead.

Body:
So, I'm trying to make a simple game with HTML/CSS/JS and there's a problem with canvas. My full code is at https://pastebin.com/DM2ChXR2 and it has a part like:

...

__________
document.body.insertBefore(this.canvas, document.getElementById("footer"));

Right now it works as expected, drawing canvas on top of all contents when the "start" button is pressed. But if I put the anchor tag inside the div like:

...

then the canvas would not show up. I can't see the logical reason for that, what am I missing?