问:
BLOB/TEXT column 'bestilling' used in key specification without a key length
I am trying to make a order system, but I am stuck right now.
In the mysql tabel right now, I am using varchar(255) in a column named "bestillinger", but it can only store 255 chars. So I searched a bit, and remembered that i could use longtext or just text, but now when i try to do it, i get a error saying:

```<code>#1170 - BLOB/TEXT column 'bestilling' used in key specification without a key length
</code>```

I have tried to search here and in Google, but got no luck with me.

My MySQL tabel is:

```<code>CREATE TABLE IF NOT EXISTS `bestillinger` (
  `id` int(11) NOT NULL,
  `bestilling` TEXT NOT NULL PRIMARY KEY,
  `accepted` varchar(255) DEFAULT NULL,
  UNIQUE KEY `id_bestilling` (`id`,`bestilling`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code>```

I am using UNIQUE KEY because I am using "ON DUPLICATE KEY UPDATE" in my PHP part. But don't mind that.

Thanks in advance.

答:
I think the following example will best explain this problem.

I got the problem because I was trying to set a text field to UNIQUE. I fixed the problem by changing data type of email(TEXT) to email(VARCHAR(254)).

```<code>mysql> desc users;
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| id          | int(11)     | NO   | PRI | NULL    | auto_increment |
| fname       | varchar(50) | NO   |     | NULL    |                |
| lname       | varchar(50) | NO   |     | NULL    |                |
| uname       | varchar(20) | NO   |     | NULL    |                |
| email       | text        | NO   |     | NULL    |                |
| contact     | bigint(12)  | NO   |     | NULL    |                |
| profile_pic | text        | NO   |     | NULL    |                |
| password    | varchar(20) | NO   |     | admin   |                |
+-------------+-------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

mysql> ALTER TABLE users ADD UNIQUE(email);
ERROR 1170 (42000): BLOB/TEXT column 'email' used in key specification without a key length
mysql>
mysql> ALTER  TABLE users MODIFY email VARCHAR(254);
Query OK, 9 rows affected (0.02 sec)
Records: 9  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE users ADD UNIQUE(email);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc users;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| fname       | varchar(50)  | NO   |     | NULL    |                |
| lname       | varchar(50)  | NO   |     | NULL    |                |
| uname       | varchar(20)  | NO   |     | NULL    |                |
| email       | varchar(254) | YES  | UNI | NULL    |                |
| contact     | bigint(12)   | NO   |     | NULL    |                |
| profile_pic | text         | NO   |     | NULL    |                |
| password    | varchar(20)  | NO   |     | admin   |                |
+-------------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

mysql>
</code>```

Body:
I am trying to make a order system, but I am stuck right now.
In the mysql tabel right now, I am using varchar(255) in a column named "bestillinger", but it can only store 255 chars. So I searched a bit, and remembered that i could use longtext or just text, but now when i try to do it, i get a error saying:

#1170 - BLOB/TEXT column 'bestilling' used in key specification without a key length

I have tried to search here and in Google, but got no luck with me.

My MySQL tabel is:

CREATE TABLE IF NOT EXISTS `bestillinger` (
  `id` int(11) NOT NULL,
  `bestilling` TEXT NOT NULL PRIMARY KEY,
  `accepted` varchar(255) DEFAULT NULL,
  UNIQUE KEY `id_bestilling` (`id`,`bestilling`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

I am using UNIQUE KEY because I am using "ON DUPLICATE KEY UPDATE" in my PHP part. But don't mind that.

Thanks in advance.

Body:
I think the following example will best explain this problem.

I got the problem because I was trying to set a text field to UNIQUE. I fixed the problem by changing data type of email(TEXT) to email(VARCHAR(254)).

mysql> desc users;
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| id          | int(11)     | NO   | PRI | NULL    | auto_increment |
| fname       | varchar(50) | NO   |     | NULL    |                |
| lname       | varchar(50) | NO   |     | NULL    |                |
| uname       | varchar(20) | NO   |     | NULL    |                |
| email       | text        | NO   |     | NULL    |                |
| contact     | bigint(12)  | NO   |     | NULL    |                |
| profile_pic | text        | NO   |     | NULL    |                |
| password    | varchar(20) | NO   |     | admin   |                |
+-------------+-------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

mysql> ALTER TABLE users ADD UNIQUE(email);
ERROR 1170 (42000): BLOB/TEXT column 'email' used in key specification without a key length
mysql>
mysql> ALTER  TABLE users MODIFY email VARCHAR(254);
Query OK, 9 rows affected (0.02 sec)
Records: 9  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE users ADD UNIQUE(email);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc users;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| fname       | varchar(50)  | NO   |     | NULL    |                |
| lname       | varchar(50)  | NO   |     | NULL    |                |
| uname       | varchar(20)  | NO   |     | NULL    |                |
| email       | varchar(254) | YES  | UNI | NULL    |                |
| contact     | bigint(12)   | NO   |     | NULL    |                |
| profile_pic | text         | NO   |     | NULL    |                |
| password    | varchar(20)  | NO   |     | admin   |                |
+-------------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

mysql>


来源: stackexchange

问:
MS Access Database Multiple rows of static/constant data
So, this is a bit of a ridiculous questions, however, I have not been able to find an answer anywhere on the interwebs!

I have a MS Access DB which I am using in Access 2016. It is from a client and being used to provide data for another system.

Anyway, I am trying to mock some database data being returned from the table without changing the database data. So, I figured I would just do a select of constants, as I would in SQL or any other db language.

All I want returned is 2+ rows of data for 3 columns.

E.g.
Name, Value, Target
aaa, 1, 2,
bbb, 3, 4,
ccc, 5, 6,
...

I can do:
SELECT 'aaa' AS [Name], 2 AS [Target], 3 AS [Value]

however, any other attempt I use to return more than one row of data just gives me errors.
I've tried Unions, values(), multiple selects, etc, and none seem to work.

For sanity, can someone confirm that this is not possible, or am I missing something??

Many Thanks

答:
You don't even need a custom table. You can hijack a system table:</p>

```<code>SELECT TOP 1 'aaa' AS [Name], 1 AS [Value]
FROM MSysObjects
UNION ALL
SELECT TOP 1 'bbb' AS [Name], 2 AS [Value]
FROM MSysObjects
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You don't even need a custom table. You can hijack a system table:

SELECT TOP 1 'aaa' AS [Name], 1 AS [Value]
FROM MSysObjects
UNION ALL
SELECT TOP 1 'bbb' AS [Name], 2 AS [Value]
FROM MSysObjects


问:
how to get object value in side of [http post] in mvc 4
```<code>[HttpGet]
        public ActionResult Delete(string ID)
        {
            return View(objDB.SelectDatabyID(ID));
        }

[HttpPost]
        public ActionResult Delete(Customer objCustomer)
        {
            string result = objDB.DeleteData(objCustomer);
            ViewData["result"] = result;
            ModelState.Clear(); //clearing model
            return View();
        }
</code>```

in this code [httppost] side not gettig value..it will be show null value in objCustomer..basically Customer is a modelclass..how to get customerid value in [httppost] side..

答:
Basically you need to pass Customer model from view check below code :

First Method with Form Serialization :

$("#SubmitBtn").click(function () {
    $.ajax(
                   {
                       url: '@Url.Action("Delete", "ControllerName")',
                       type: "Post",
                       async: false,
                        dataType: "html",
                       contentType: "application/json;charset=utf-8",
                       data: $('form').serialize(), //here you have to pass your form name for pass all data to controller action
                     contentType: "application/json;charset=utf-8",
                       success: function (data) {
                            $('#PartialResultDivName').html(data);
                       }
                   });
 });
```

<p><strong>Second Solution with without Form Serialization :</strong></p>

<pre class="lang-js prettyprint-override"><code> var Customer = {
        "Name": $("#Name").val(),
        "Address": $("#Address").val()
        //Add all properties
    };
    $.ajax(
     {
         url: '/YourControllerName/Delete/',
         type: "Post",
         async: false,
         dataType: "html",
         data: JSON.stringify(Customer),
         contentType: "application/json;charset=utf-8",
         success: function (result) {
             //Return Result
         }
     });
</code>```

Cheers !!

Body:
[HttpGet]
        public ActionResult Delete(string ID)
        {
            return View(objDB.SelectDatabyID(ID));
        }

[HttpPost]
        public ActionResult Delete(Customer objCustomer)
        {
            string result = objDB.DeleteData(objCustomer);
            ViewData["result"] = result;
            ModelState.Clear(); //clearing model
            return View();
        }

in this code [httppost] side not gettig value..it will be show null value in objCustomer..basically Customer is a modelclass..how to get customerid value in [httppost] side..

Body:
Basically you need to pass Customer model from view check below code :

First Method with Form Serialization :

$("#SubmitBtn").click(function () {
    $.ajax(
                   {
                       url: '@Url.Action("Delete", "ControllerName")',
                       type: "Post",
                       async: false,
                        dataType: "html",
                       contentType: "application/json;charset=utf-8",
                       data: $('form').serialize(), //here you have to pass your form name for pass all data to controller action
                     contentType: "application/json;charset=utf-8",
                       success: function (data) {
                            $('#PartialResultDivName').html(data);
                       }
                   });
 });

Second Solution with without Form Serialization :

 var Customer = {
        "Name": $("#Name").val(),
        "Address": $("#Address").val()
        //Add all properties
    };
    $.ajax(
     {
         url: '/YourControllerName/Delete/',
         type: "Post",
         async: false,
         dataType: "html",
         data: JSON.stringify(Customer),
         contentType: "application/json;charset=utf-8",
         success: function (result) {
             //Return Result
         }
     });

Cheers !!


问:
Automatically create a value for every User in Firebase Database
I have created A User Login And register Android App.  I used Firebase Auth For User Register. I want that when an user Register A counter value will be added to my database For that user. It will be created for all user. Counter Value Will be "0".</p>

答:
I think firebase cloud functions would work great for this. Could you have a look at the authentication triggers?

Your nodeJS code would something like this, have a look at the getting started section here

exports.incrementUserount = functions.auth.user().onCreate(event => {
  // increment the counter in the database here
});


问:
Cassandra runs OOM when writing
I'm wondering why Cassandra is running out of memory on write-only workload.
It's a single node, version 3.10, with default configuration (except added graphite reporter). The machine has 30GB RAM so Cassandra starts with 8GB heap.

I don't know much about Cassandra, but none of the relevant metrics seem suspicious and I don't see anything obvious in the heapdump (just a lot of byte arrays with written data taking space).

Here are the metrics that might be relevant. Notice that heap usage is increasing constantly and soon the process will die due to OOM:

(few-sec spikes in GC time are irrelevant, I did force GC several times)

cassandra.yaml: https://gist.github.com/mabn/3b02fe94c819a9dddf3152bcecc00f24

答:
In order to use more than 8GB, you should move offheap memtables. This is an important step because will allow you to use more memory, but stick the JVM to the 8GB upper bound, so you won't experience long GC-stop-of-the-world pauses usually triggered with big heaps under pressure.

You move memtables offheap by changing the memtable_allocation_type from heap_buffers to one of offheap_buffers or offheap_objects, each one having its own reasons behind. You then tune memtable_offheap_space_in_mb to a reasonable value for your system.

In addition, moving memtables offheap frees space in the heap that you can use for key/row caches, improving read performances.

Have a look at these articles:

Off-heap memtables in Cassandra 2.1

The cassandra.yaml configuration file

Title: Cassandra runs OOM when writing


问:
span class locator is not visible/clickable - selenium
Following is the HTML for span: </p>

```<code><td class="header-logout-btn">
 <a href="logout.htm" class="btn switch-btn">
  <i class="fa fa-times"></i><span class="hidden-xs">Home</span>
 </a>
</td>
</code>```

<p>Tried with: </p>

```<code>driver.findElement(By.linkText("HOME"));
driver.findElement(By.xpath("//div[@class="header-logout-btn"]/span[@class="hidden-xs"]));
driver.findElement(By.xpath("//span"));
driver.findElement(By.className("hidden-xs"));
</code>```

答:
Normally the logout button will be submenu or it will be visible only if you click or mouse over on main menu usually the main menu is profile icon. I assume this logout button visible only after clicking on main/profile button. This may be the reason the button is hidden or not clickable.  The solutions are given below.
1. First click or mouse over on main/profile menu then click on logout button.
2. Still you want to click on hidden button. You may be try with JavaScript executor as given below.</p>

```<code>Webelement eleLogout=driver.find element(By.class name("switch-btn"));
JavaScriptExecutor js=(JavaScriptExecutor)driver;
js.executeScript("arguments [0].click()",eleLogout);`
</code>```

Body:
Following is the HTML for span:

  Home

Tried with:

driver.findElement(By.linkText("HOME"));
driver.findElement(By.xpath("//div[@class="header-logout-btn"]/span[@class="hidden-xs"]));
driver.findElement(By.xpath("//span"));
driver.findElement(By.className("hidden-xs"));

Body:
Normally the logout button will be submenu or it will be visible only if you click or mouse over on main menu usually the main menu is profile icon. I assume this logout button visible only after clicking on main/profile button. This may be the reason the button is hidden or not clickable.  The solutions are given below.
1. First click or mouse over on main/profile menu then click on logout button.
2. Still you want to click on hidden button. You may be try with JavaScript executor as given below.

Webelement eleLogout=driver.find element(By.class name("switch-btn"));
JavaScriptExecutor js=(JavaScriptExecutor)driver;
js.executeScript("arguments [0].click()",eleLogout);`


问:
Why does a match never use the second match arm?
I am trying to make reimplementation of first 2 Final Fantasy games using original data from various platforms. I want to get 2 program arguments using the getopts crate and handle both of them by using match but it just executes the first match element. I think I screwed up something with types.

Maybe there is another way to do it? I am lost using the official Rust docs and any tutorials on internet are not really noob-friendly.

Here is the code:

```<code>let args: Vec<String> = env::args().map(|x| x.to_string()).collect();

if(args.len() < 3) {
    println!("=====ERROR=====\nInvalid number of parameters\nExpected: <gamename> <gamerom>\nType in: 'help me' to get some help.");
    process::exit(1);
}

let ref game = args[1];
let ref rom = args[2];

match game {
    help => {
        println!("=====HELP======");

        match rom {
            list => println!("Available games: ff1, ff2\nAvailable roms: ff1_j_msx, ff1_j_nes, ff1_u, ff1and2, ff2_j, ff2_u_proto"),
            me => println!("Available help commands:\nlist -> List of available games and roms.\nme -> This help"),
            _ => println!("=====ERROR=====\nInvalid help command.")
        }
    },
    _ => println!("=====ERROR=====\nInvalid game, type in 'help me' to get some help.")
}
</code>```

答:
You really need to read the compilers error and warning messages. This code has seven warnings. If you had addressed any of them you'd be a lot closer to fixing the problem yourself. If you'd fixed all of them, your problem would be gone.

Here's a representative warning where the compiler tells you exactly what the problem is:

warning: unreachable pattern
  --> src/main.rs:24:5
   |
24 |     _ => println!("=====ERROR=====\nInvalid game, type in 'help me' to get some help.")
   |     ^ this is an unreachable pattern
   |
   = note: #[warn(unreachable_patterns)] on by default
note: this pattern matches any value
  --> src/main.rs:15:5
   |
15 |     help => {
   |     ^^^^
```

<p>When you use just <code>help</code>, that creates a new variable with the value you are matching on. In this case, it matches <em>everything</em>, so the subsequent arms can never match.</p>

<p>Instead, you need to match against a string literal:</p>

```match game.as_str() {
    "help" => {
        match rom.as_str() {
            "list" => /* ... */,
            "me" => /* ... */,
            _ => /* ... */,
        }
    },
    _ => /* ... */,
}
```

I'd strongly encourage you to go back and re-read The Rust Programming Language. It's where a lot of the beginner documentation is kept. Specifically, you should read from the beginning and then up through the chapter on match and the chapter on patterns.

Body:
I am trying to make reimplementation of first 2 Final Fantasy games using original data from various platforms. I want to get 2 program arguments using the getopts crate and handle both of them by using match but it just executes the first match element. I think I screwed up something with types.

Maybe there is another way to do it? I am lost using the official Rust docs and any tutorials on internet are not really noob-friendly.

Here is the code:

let args: Vec<String> = env::args().map(|x| x.to_string()).collect();

if(args.len() < 3) {
    println!("=====ERROR=====\nInvalid number of parameters\nExpected: <gamename> <gamerom>\nType in: 'help me' to get some help.");
    process::exit(1);
}

let ref game = args[1];
let ref rom = args[2];

match game {
    help => {
        println!("=====HELP======");

        match rom {
            list => println!("Available games: ff1, ff2\nAvailable roms: ff1_j_msx, ff1_j_nes, ff1_u, ff1and2, ff2_j, ff2_u_proto"),
            me => println!("Available help commands:\nlist -> List of available games and roms.\nme -> This help"),
            _ => println!("=====ERROR=====\nInvalid help command.")
        }
    },
    _ => println!("=====ERROR=====\nInvalid game, type in 'help me' to get some help.")
}

Body:
You really need to read the compilers error and warning messages. This code has seven warnings. If you had addressed any of them you'd be a lot closer to fixing the problem yourself. If you'd fixed all of them, your problem would be gone.

Here's a representative warning where the compiler tells you exactly what the problem is:

warning: unreachable pattern
  --> src/main.rs:24:5
   |
24 |     _ => println!("=====ERROR=====\nInvalid game, type in 'help me' to get some help.")
   |     ^ this is an unreachable pattern
   |
   = note: #[warn(unreachable_patterns)] on by default
note: this pattern matches any value
  --> src/main.rs:15:5
   |
15 |     help => {
   |     ^^^^

When you use just help, that creates a new variable with the value you are matching on. In this case, it matches everything, so the subsequent arms can never match.

Instead, you need to match against a string literal:

match game.as_str() {
    "help" => {
        match rom.as_str() {
            "list" => /* ... */,
            "me" => /* ... */,
            _ => /* ... */,
        }
    },
    _ => /* ... */,
}

I'd strongly encourage you to go back and re-read The Rust Programming Language. It's where a lot of the beginner documentation is kept. Specifically, you should read from the beginning and then up through the chapter on match and the chapter on patterns.


问:
String vs string

Possible Duplicate:

  In C# what is the difference between String and string

Should I use string or String when declaring a basic string variable in c# and does it matter?

答: I like string because VS highlights it in dark blue (which makes it awesomer).

Title: String vs string

ContentLicense: CC BY-SA 2.5


问:
Writing a C program to call another program without using any built-in libraries
I am trying to write a simple 'go-command' for boot-loader that takes me to specific address in RAM say 0x18000000 and it should execute a program that blinks led. I have two .c files say led.c and go.c in which led.c blinks two leds. But I am wondering and don't know that how can I pass a control/invoke its main() to this go.c file to go to that address and start blinking leds? But it should be done without including other header files, libraries, etc. Kindly help me!! Thanks in advance. Below code is for led.c

```<code>void delay ()
{
    volatile int i;
    for(i=0;i<1000000;i++)
    {}

}
int main(void)
{
    *led0=0;
    *led1=0;
    while(1)
    {
        *led0=1;
        delay();
        *led0=0;
        *led1=1;
        delay();
        *led1=0;
    }
}
</code>```

In my go.c file I want to pass a control to invoke this led.c main() func

答:
GCC has an extension that allows jumping to an arbitrary address, so if you know the address of your led.c main you could do something like that:

```<code>void *func_ptr = (void *)0x1234567;  // address of your led routine
goto *func_ptr;
</code>```

However, you probably don't have the address of the led routine and it is not a very safe operation. Jumping to some unknown address will probably result in a crash!!

Body:
I am trying to write a simple 'go-command' for boot-loader that takes me to specific address in RAM say 0x18000000 and it should execute a program that blinks led. I have two .c files say led.c and go.c in which led.c blinks two leds. But I am wondering and don't know that how can I pass a control/invoke its main() to this go.c file to go to that address and start blinking leds? But it should be done without including other header files, libraries, etc. Kindly help me!! Thanks in advance. Below code is for led.c

void delay ()
{
    volatile int i;
    for(i=0;i<1000000;i++)
    {}

}
int main(void)
{
    *led0=0;
    *led1=0;
    while(1)
    {
        *led0=1;
        delay();
        *led0=0;
        *led1=1;
        delay();
        *led1=0;
    }
}

In my go.c file I want to pass a control to invoke this led.c main() func

Body:
GCC has an extension that allows jumping to an arbitrary address, so if you know the address of your led.c main you could do something like that:

void *func_ptr = (void *)0x1234567;  // address of your led routine
goto *func_ptr;

However, you probably don't have the address of the led routine and it is not a very safe operation. Jumping to some unknown address will probably result in a crash!!


问:
POST method is not set
During debug, I realize that all the request property and method I set is not executed at all. Can anyone explain why?

Because of this, whenever I request an output from URLConnection, that line will create a runtime error.

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        url = new URL("https://ussouthcentral.services.azureml.net/workspaces/80b0369fe0df48308d956e2ddce52806/services/6379155db28f4c91b84e78d268a927f9/execute?api-version=2.0&format=swagger");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        urlConnection = (URLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
       // urlConnection.setRequestMethod("POST");

        String api_key = "Bearer api_key";
        urlConnection.setDoInput(true);

        urlConnection.addRequestProperty("Authorization", api_key);
        urlConnection.addRequestProperty("Content-Type", "application/json");
        urlConnection.addRequestProperty("Accept", "application/json");
         } catch (IOException e) {
        e.printStackTrace();
    }

   try {
        urlConnection.connect();
        urlConnection.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

答:
First of all you are doing network operations on UI thread which android OS does not allow so, you should put your code in an async task

like so :

```<code>AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            URL url = null;
            URLConnection urlConnection = null;
            try {
                url = new URL("https://ussouthcentral.services.azureml.net/workspaces/80b0369fe0df48308d956e2ddce52806/services/6379155db28f4c91b84e78d268a927f9/execute?api-version=2.0&format=swagger");
                urlConnection = (URLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                // urlConnection.setRequestMethod("POST");

                String api_key = "Bearer api_key";
                urlConnection.setDoInput(true);

                urlConnection.addRequestProperty("Authorization", api_key);
                urlConnection.addRequestProperty("Content-Type", "application/json");
                urlConnection.addRequestProperty("Accept", "application/json");
                urlConnection.connect();
                urlConnection.getContent();
            }
            catch (IOException exc) {
                exc.printStackTrace();
            }
            return null;
        }
    };

    task.execute();
</code>```

also make sure you have intenet permission in the manifest

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

also your api key "Bearer api_key" is not a valid api key

Title: POST method is not set

Body:
During debug, I realize that all the request property and method I set is not executed at all. Can anyone explain why?

Because of this, whenever I request an output from URLConnection, that line will create a runtime error.

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

    try {
        url = new URL("https://ussouthcentral.services.azureml.net/workspaces/80b0369fe0df48308d956e2ddce52806/services/6379155db28f4c91b84e78d268a927f9/execute?api-version=2.0&format=swagger");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        urlConnection = (URLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
       // urlConnection.setRequestMethod("POST");

        String api_key = "Bearer api_key";
        urlConnection.setDoInput(true);

        urlConnection.addRequestProperty("Authorization", api_key);
        urlConnection.addRequestProperty("Content-Type", "application/json");
        urlConnection.addRequestProperty("Accept", "application/json");
         } catch (IOException e) {
        e.printStackTrace();
    }

   try {
        urlConnection.connect();
        urlConnection.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }

Body:
First of all you are doing network operations on UI thread which android OS does not allow so, you should put your code in an async task

like so :

AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            URL url = null;
            URLConnection urlConnection = null;
            try {
                url = new URL("https://ussouthcentral.services.azureml.net/workspaces/80b0369fe0df48308d956e2ddce52806/services/6379155db28f4c91b84e78d268a927f9/execute?api-version=2.0&format=swagger");
                urlConnection = (URLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                // urlConnection.setRequestMethod("POST");

                String api_key = "Bearer api_key";
                urlConnection.setDoInput(true);

                urlConnection.addRequestProperty("Authorization", api_key);
                urlConnection.addRequestProperty("Content-Type", "application/json");
                urlConnection.addRequestProperty("Accept", "application/json");
                urlConnection.connect();
                urlConnection.getContent();
            }
            catch (IOException exc) {
                exc.printStackTrace();
            }
            return null;
        }
    };

    task.execute();

also make sure you have intenet permission in the manifest

<uses-permission android:name="android.permission.INTERNET" />

also your api key "Bearer api_key" is not a valid api key


问:
sqlite update multiple columns with Values List
i have a simple table named "test" in an sqlite DB

columns: id, foo, bar

row1: 1, 5 , 6

row2: 2, 7 , 8

I want to update the rows with the following sqlite statement:

UPDATE test SET (foo, bar) = ( 8, 9 )

according to https://sqlite.org/lang_update.html and the picture there it should be possible. It is also recommended in UPDATE syntax in SQLite

Unfortunately i get

near "(": syntax error:

A Syntax like:

UPDATE test SET foo=8, bar=9

works, but is not the solution here.

Can somebody explain why the list query is wrong?

Thank you!

答:
Issue was with the sqlite3 Version in Python (even latest version) has dll with sqlite3.sqlite_version = 3.14

Feature became available with sqlite 3.15...


答:
```<code>select to_timestamp( round( ( extract ('epoch' from ts) ) /30 ) * 30 )
</code>```

Title: Postgresql round timestamp to nearest 30 seconds

Body:
is possible in postgres to round timestamp to nearest 30 seconds?
For example:

source -> result

2017-06-07 14:11:20 -> 2017-06-07 14:11:00
2017-06-07 14:11:40 -> 2017-06-07 14:11:30
2017-06-07 14:12:10 -> 2017-06-07 14:12:00


问:
how to convert latitude and longitude to pixels
I have two sets of Lat and Long values corresponding to two corners of a rectangle (top left and bottom right). I want to load a image in the rectangle and as the user clicks on the locations on the rectangle/image, it should return a latitude and longitude (from the detected pixel's coordinates). What should be the calculation to convert pixels to lat and long, given the above spot of inputs.

答:
You should know what geodetic projection has been used to create that map and how rectangular coordinates correspond to geographic ones.

For small map pieces you can use linear approximation, so coordinates might be calculated with linear interpolation.

Example for x-coordinate and longitude:

```<code>Lon = LonLeft + X * (LonRight - LonLeft) / Width
</code>```

Body:
You should know what geodetic projection has been used to create that map and how rectangular coordinates correspond to geographic ones.

For small map pieces you can use linear approximation, so coordinates might be calculated with linear interpolation.

Example for x-coordinate and longitude:

Lon = LonLeft + X * (LonRight - LonLeft) / Width


问:
codeigniter database caching 'TRUE' stop webpage
I want to turn on database caching into my CodeIgniter website for this I have used following code in database.php file.

```<code>    $db['default']['cache_on'] = FALSE;
    $db['default']['cachedir'] = 'application.cache';
</code>```

And I have already created a folder, name cache inside application directory and give permission 0777.

when I run my website, it shows error - this web page isn't working.

the same code is perfect works on my localhost (xampp server).

Did I forget to include anything?   Please help me out

答:
You have to use a relative path instead of '.'[dot].

But if you want to enabled database query caching then make your 'cache_on' to TRUE

```<code>$db['default']['cache_on'] = TRUE;
$db['default']['cachedir'] = 'application/cache';
</code>```

if above line not works try this:

```<code>$db['default']['cachedir'] = APPPATH . 'cache';
</code>```

After that whichever query you want to store in cache use this feature

```<code> // Turn caching on
 $this->db->cache_on();

 // Turn caching off for this one query
 $this->db->cache_off();
</code>```

Notes:

CodeIgniter’s query caching system happens dynamically when your
pages are viewed. When caching is enabled, the first time a web page is loaded, the query result object will be serialized and stored in a
text file on your server. The next time the page is loaded the cache file will be used instead of accessing your database.

Only read-type (SELECT) queries can be cached not Write-type (INSERT, UPDATE, etc.) queries

The caching system permits you clear caches So whenever DB updated clear related catching also.When the page loaded it again caching updated queries.

Read this for deleting caching

Body:
I want to turn on database caching into my CodeIgniter website for this I have used following code in database.php file.

    $db['default']['cache_on'] = FALSE;
    $db['default']['cachedir'] = 'application.cache';

And I have already created a folder, name cache inside application directory and give permission 0777.

when I run my website, it shows error - this web page isn't working.

the same code is perfect works on my localhost (xampp server).

Did I forget to include anything?   Please help me out

Body:
You have to use a relative path instead of '.'[dot].

But if you want to enabled database query caching then make your 'cache_on' to TRUE

$db['default']['cache_on'] = TRUE;
$db['default']['cachedir'] = 'application/cache';

if above line not works try this:

$db['default']['cachedir'] = APPPATH . 'cache';

After that whichever query you want to store in cache use this feature

 // Turn caching on
 $this->db->cache_on();

 // Turn caching off for this one query
 $this->db->cache_off();

Notes:

CodeIgniter’s query caching system happens dynamically when your
pages are viewed. When caching is enabled, the first time a web page is loaded, the query result object will be serialized and stored in a
text file on your server. The next time the page is loaded the cache file will be used instead of accessing your database.

Only read-type (SELECT) queries can be cached not Write-type (INSERT, UPDATE, etc.) queries

The caching system permits you clear caches So whenever DB updated clear related catching also.When the page loaded it again caching updated queries.

Read this for deleting caching


问:
Crystal Report Shows blank Page on Windows server 2012
I have crystal report files that i push data to from dataset and then transmit the report to pdf or word or excel depending on user selection. I don't show it with crystal report viewer at all.
Just yesterday, on one windows server 2012 web server, it started showing blank pages for every report after updating the web application. Nothing has changed on the server.
I use crystal report 2008_x86, sap says the 2008 version should not work on server 2012 but it has always been the one on it and it has been working till yesterday.
When i connect to the server with my dev machine it shows, but on the server itself, it is not.
Please any help will be good since it's mission critical.
An example of how the data is sent is here

```<code>```
private void BindRpt()
    {
        eReports obj = new eReports();
        DataSet oData = obj.rptClassTeacher(TeacherID, TermID, YearID);
        rd = new ReportDocument();
        string path = "School/ClassTeacher.rpt";
        reportPath(rd, path);
        rd.SetDataSource(oData);
        Response.Clear();
        Response.Buffer = true;
        userPreference(rd);
    }

private void userPreference(ReportDocument rd)
    {
        rd.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, false, "Report");
    }
```

答:
Finally i found the culprit to this, taken a long time but thought i will put the answer that worked for me here to in case someone faces this same issue.

I uninstalled Windows Update KB3102429. And behold, it's working again.
You can read about it here. Though Adam Fowler talks about how it affects Outlook, it solved the blank page in crystal report export.
Hope this helps

Body:
I have crystal report files that i push data to from dataset and then transmit the report to pdf or word or excel depending on user selection. I don't show it with crystal report viewer at all.
Just yesterday, on one windows server 2012 web server, it started showing blank pages for every report after updating the web application. Nothing has changed on the server.
I use crystal report 2008_x86, sap says the 2008 version should not work on server 2012 but it has always been the one on it and it has been working till yesterday.
When i connect to the server with my dev machine it shows, but on the server itself, it is not.
Please any help will be good since it's mission critical.
An example of how the data is sent is here

private void BindRpt()
    {
        eReports obj = new eReports();
        DataSet oData = obj.rptClassTeacher(TeacherID, TermID, YearID);
        rd = new ReportDocument();
        string path = "School/ClassTeacher.rpt";
        reportPath(rd, path);
        rd.SetDataSource(oData);
        Response.Clear();
        Response.Buffer = true;
        userPreference(rd);
    }

private void userPreference(ReportDocument rd)
    {
        rd.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, false, "Report");
    }


问:
p vs puts in Ruby
Is there any difference between p and puts in Ruby?

答:
From ruby-2.4.1 document

puts

puts(obj, ...) → nil

Writes the given object(s) to ios. Writes a newline after any that
  do not already end with a newline sequence. Returns nil.

The stream must be opened for writing. If called with an array
  argument, writes each element on a new line. Each given object
  that isn’t a string or array will be converted by calling its to_s
  method. If called without arguments, outputs a single newline.

let's try it on irb

```<code># always newline in the end
>> puts # no arguments

=> nil # return nil and writes a newline
>> puts "sss\nsss\n" # newline in string
sss
sss
=> nil
>> puts "sss\nsss" # no newline in string
sss
sss
=> nil

# for multiple arguments and array
>> puts "a", "b"
a
b
=> nil
>> puts "a", "b", ["c", "d"]
a
b
c
d
=> nil
</code>```

p

p(obj) → obj click to toggle source

  p(obj1, obj2, ...) → [obj, ...]
  p() → nil

  For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

in irb

```<code># no arguments
>> p
=> nil # return nil, writes nothing
# one arguments
>> p "sss\nsss\n"
"sss\nsss\n"
=> "aaa\naaa\n"
# multiple arguments and array
>> p "a", "b"
"a"
"b"
=> ["a", "b"] # return a array
>> p "a", "b", ["c", "d"]
"a"
"b"
["c", "d"]
=> ["a", "b", ["c", "d"]] # return a nested array
</code>```

Title: p vs puts in Ruby

Body:
From ruby-2.4.1 document

puts

puts(obj, ...) → nil

Writes the given object(s) to ios. Writes a newline after any that
  do not already end with a newline sequence. Returns nil.

The stream must be opened for writing. If called with an array
  argument, writes each element on a new line. Each given object
  that isn’t a string or array will be converted by calling its to_s
  method. If called without arguments, outputs a single newline.

let's try it on irb

# always newline in the end
>> puts # no arguments

=> nil # return nil and writes a newline
>> puts "sss\nsss\n" # newline in string
sss
sss
=> nil
>> puts "sss\nsss" # no newline in string
sss
sss
=> nil

# for multiple arguments and array
>> puts "a", "b"
a
b
=> nil
>> puts "a", "b", ["c", "d"]
a
b
c
d
=> nil

p

p(obj) → obj click to toggle source

  p(obj1, obj2, ...) → [obj, ...]
  p() → nil

  For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

in irb

# no arguments
>> p
=> nil # return nil, writes nothing
# one arguments
>> p "sss\nsss\n"
"sss\nsss\n"
=> "aaa\naaa\n"
# multiple arguments and array
>> p "a", "b"
"a"
"b"
=> ["a", "b"] # return a array
>> p "a", "b", ["c", "d"]
"a"
"b"
["c", "d"]
=> ["a", "b", ["c", "d"]] # return a nested array


问:
KnockoutJS - show accumulate value for each item
How can I display in a table the accumulate value for each item in a observableArray with KnockoutJS?

I need somethin like:

function ViewModel(){
var self = this;

self.Item = function(day,note){
this.day = ko.observable(day);
this.note = ko.observable(note);
};
}

var itemsFromServer = [
{day:'Mo', note:1},
{day:'Tu', note:2},
{day:'We', note:3},
{day:'Th', note:4},
{day:'Fr', note:5},
{day:'Su', note:6},
];

var vm = new ViewModel();

var arrItems = ko.utils.arrayMap(itemsFromServer, function(item) {
    return new vm.Item(item.day, item.note);
    });

ko.applyBindings(vm);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<table>
    <thead>
        <tr><th>Day</th><th>Note</th><th>Accumulate</th></tr>
    </thead>
    <tbody data-bind="foreach: arrItems">
        <tr>
            <td data-bind="text: day"></td>
            <td data-bind="text: note"></td>
           <td >the currente 'note' + the anterior 'note'</td>
        </tr>
    </tbody>
</table></code>```

The last column should display the sum of current item + anterior item.
Thanks.

答:
I'm not exactly sure what value you want the third column to be, but the main approach remains the same:

Give your Item class access to their "sibling items" by passing a reference to the array

In a computed property, do a "look behind" by looking up the items own index.

Perform some sort of calculation between two (or more) Item instances and return the value

For example, this acc property returns the acc of the previous Item and ones own note property:

var Item = function(day, note, siblings){
  this.day = ko.observable(day);
  this.note = ko.observable(note);

  this.acc = ko.pureComputed(function() {
    var allItems = siblings();
    var myIndex = allItems.indexOf(this);

    var base = myIndex > 0
      ? allItems[myIndex - 1].acc()
      : 0

    return base + this.note();
  }, this);
};

function ViewModel() {
  var self = this;

  self.items = ko.observableArray([]);

  self.items(itemsFromServer.map(function(item) {
      return new Item(item.day, item.note, self.items);
    })
  );
}

var itemsFromServer = [
  {day:'Mo', note:1},
  {day:'Tu', note:2},
  {day:'We', note:3},
  {day:'Th', note:4},
  {day:'Fr', note:5},
  {day:'Su', note:6},
];

ko.applyBindings(new ViewModel());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<table>
  <thead>
    <tr>
      <th>Day</th>
      <th>Note</th>
      <th>Accumulate</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: items">
    <tr>
      <td data-bind="text: day"></td>
      <td data-bind="text: note"></td>
      <td data-bind="text: acc"></td>
    </tr>
  </tbody>
</table></code>```

Body:
How can I display in a table the accumulate value for each item in a observableArray with KnockoutJS?

I need somethin like:

function ViewModel(){
var self = this;

self.Item = function(day,note){
this.day = ko.observable(day);
this.note = ko.observable(note);
};
}

var itemsFromServer = [
{day:'Mo', note:1},
{day:'Tu', note:2},
{day:'We', note:3},
{day:'Th', note:4},
{day:'Fr', note:5},
{day:'Su', note:6},
];

var vm = new ViewModel();

var arrItems = ko.utils.arrayMap(itemsFromServer, function(item) {
    return new vm.Item(item.day, item.note);
    });

ko.applyBindings(vm);

Day	Note	Accumulate

           the currente 'note' + the anterior 'note'

The last column should display the sum of current item + anterior item.
Thanks.

Body:
I'm not exactly sure what value you want the third column to be, but the main approach remains the same:

Give your Item class access to their "sibling items" by passing a reference to the array

In a computed property, do a "look behind" by looking up the items own index.

Perform some sort of calculation between two (or more) Item instances and return the value

For example, this acc property returns the acc of the previous Item and ones own note property:

var Item = function(day, note, siblings){
  this.day = ko.observable(day);
  this.note = ko.observable(note);

  this.acc = ko.pureComputed(function() {
    var allItems = siblings();
    var myIndex = allItems.indexOf(this);

    var base = myIndex > 0
      ? allItems[myIndex - 1].acc()
      : 0

    return base + this.note();
  }, this);
};

function ViewModel() {
  var self = this;

  self.items = ko.observableArray([]);

  self.items(itemsFromServer.map(function(item) {
      return new Item(item.day, item.note, self.items);
    })
  );
}

var itemsFromServer = [
  {day:'Mo', note:1},
  {day:'Tu', note:2},
  {day:'We', note:3},
  {day:'Th', note:4},
  {day:'Fr', note:5},
  {day:'Su', note:6},
];

ko.applyBindings(new ViewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<table>
  <thead>
    <tr>
      <th>Day</th>
      <th>Note</th>
      <th>Accumulate</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: items">
    <tr>
      <td data-bind="text: day"></td>
      <td data-bind="text: note"></td>
      <td data-bind="text: acc"></td>
    </tr>
  </tbody>
</table>


问:
Pages showing up in search console as invalid AMP pages even though they amphtml meta tags pointing at valid AMP version
I have this page https://www.timbuktutravel.com/safari/malawi-travel which uses some AMP tags but in the source code points at https://www.timbuktutravel.com/safari/malawi-travel.amp as the amp version of the with the following meta tags:

```<code><link rel="canonical" href="https://www.timbuktutravel.com/safari/malawi-travel">
<link rel="amphtml" href="https://www.timbuktutravel.com/safari/malawi-travel.amp">
</code>```

In my Google search console the https://www.timbuktutravel.com/safari/malawi-travel page and other pages like it show up as failing AMP validation. Is there any way to stop this from happening? That page uses some amp technology but there it points at a fully compliant AMP page.

Ideally these pages shouldn't show up in the AMP section of the Google search console. Only their specific AMP versions should be there

Thanks for any ideas

答:
https://www.timbuktutravel.com/safari/malawi-travel contains:

```<code><html amp= lang="en" amp-version="1496360274808" ...
</code>```

so you are declaring that as an AMP page.

I would advise to make this canonical page as a page with no AMP (remove amp from <html amp and all the AMP components you are using) and then keep the AMP one and the linking you already have.

Body:
I have this page https://www.timbuktutravel.com/safari/malawi-travel which uses some AMP tags but in the source code points at https://www.timbuktutravel.com/safari/malawi-travel.amp as the amp version of the with the following meta tags:

<link rel="canonical" href="https://www.timbuktutravel.com/safari/malawi-travel">
<link rel="amphtml" href="https://www.timbuktutravel.com/safari/malawi-travel.amp">

In my Google search console the https://www.timbuktutravel.com/safari/malawi-travel page and other pages like it show up as failing AMP validation. Is there any way to stop this from happening? That page uses some amp technology but there it points at a fully compliant AMP page.

Ideally these pages shouldn't show up in the AMP section of the Google search console. Only their specific AMP versions should be there

Thanks for any ideas

Body:
https://www.timbuktutravel.com/safari/malawi-travel contains:

<html amp= lang="en" amp-version="1496360274808" ...

so you are declaring that as an AMP page.

I would advise to make this canonical page as a page with no AMP (remove amp from <html amp and all the AMP components you are using) and then keep the AMP one and the linking you already have.


问:
Postgres birthdays selection
I work with a Postgres database. This DB has a table with users, who have a birthdate (date field). Now I want to get all users who have their birthday in the upcoming week....

My first attempt: SELECT id FROM public.users WHERE id IN (lange reeks) AND birthdate > NOW() AND birthdate < NOW() + interval '1 week'

But this does not result, obviously because off the year. How can I work around this problem?

And does anyone know what happen to PG would go with the cases at 29-02 birthday?

答:
I know this post is old, but I had the same issue and came up with this simple and elegant solution:
It is pretty easy with age() and accounts for lap years... for the people who had their birthdays in the last 20 days:</p>

```<code>SELECT * FROM c
WHERE date_trunc('year', age(birthdate)) != date_trunc('year', age(birthdate + interval '20 days'))
</code>```

Title: Postgres birthdays selection

Body:
I know this post is old, but I had the same issue and came up with this simple and elegant solution:
It is pretty easy with age() and accounts for lap years... for the people who had their birthdays in the last 20 days:

SELECT * FROM c
WHERE date_trunc('year', age(birthdate)) != date_trunc('year', age(birthdate + interval '20 days'))


问:
Alternative for Canvas.drawText() in PrintedPdfDocument
I had gone through this link to create a sample.pdf file which contains text.

But as this API provides method to write text using only Canvas class. So I can't able to select text (as we can normally do in other PDF files) from generated sample.pdf file (as it is treated as image). Also that text gets pixelated on max Zoom (because of course those are images of letters instead of vector-like-texts).

So my question: Is there any way through which I can just write text
  in PDF without Canvas in PrintedPdfDocument?

答:
You are welcome to generate some HTML, then print it using a WebView.

Or, you are welcome to use any number of PDF generation libraries. This category in the Android Arsenal lists some, alongside PDF viewers and other utilities related to PDFs.


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

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

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

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

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

答:
I'd say consistency is more important than saving a few bytes. I always include semicolons.

On the other hand, I'd like to point out there are many places where the semicolon is not syntactically required, even if a compressor is nuking all available whitespace. e.g. at then end of a block.

```<code>if (a) { b() }
</code>```

OwnerDisplayName: anon

LastEditorDisplayName: anon

Body:
I'd say consistency is more important than saving a few bytes. I always include semicolons.

On the other hand, I'd like to point out there are many places where the semicolon is not syntactically required, even if a compressor is nuking all available whitespace. e.g. at then end of a block.

if (a) { b() }


问:
Android: What is the fastest way to load several bitmaps/thumbs via http?
I need to know : What is the fastest way to download several thumbs in a row, lets say 10 images. It seems like the built-in browser does this in a very clever way.

I have Google'd and found that most developers are using the HttpUrlConnection class to download a jpeg to display it in a ImageView, inside an ListAdapter etc.

Some developers implements the download by using DefaultHttpClient class as it has better support for timeouts etc. In fact Google recommends to use the Apache Http client, and not the native Java HttpUrlConnection. That said, both startegies mentioned works fine, but thay are very slow compared to how the build in browser on my HTC desire download thumbnails. The built in browser seems to download images about 5x-10x faster then when try to download the same bitmaps with my own code. And yes, I always do the download/http work on a separate worker thread (not GUI thread).

Do anybody know how the built-in browser is downloading thumbs, or at least what is the fastest way to download several images from a server ?

I have tried using this code:

```<code>DefaultHttpClient client = new DefaultHttpClient();
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, SO_TIMEOUT);
client.setParams(httpParameters);
client.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
    @Override
    public long getKeepAliveDuration(HttpResponse response, HttpContext context)
    {
        return 5000;
    }
});
</code>```

Now, i use this connection to fetch several bitmaps / thumbs in a for-loop:

```<code>public static Bitmap downloadBitmap(String url, DefaultHttpClient client){

  HttpResponse response = null;
  HttpGet get = new HttpGet(url);
  try {
      response = client.execute(get);
      return BitmapFactory.decodeStream(response.getEntity().getContent());
  }
  catch (ClientProtocolException e1) {
      e1.printStackTrace();
  }
  catch (IllegalStateException e){
      e.printStackTrace();
  }
  catch (IOException e1) {
      e1.printStackTrace();
  }

  return null;
}
</code>```

I created a testpage.html with 10 bitmaps and loaded it with the built-in browser. The browser renders the page with all the thumbs within 1 seconds. And I'm sure they are not cached in the browser, as i randomize the 10 images for every page-refresh.

When i try to make a simple activity that downloads and displays the same thumbs, its a lot slower.

I hope the Google Android Team picks up this and includes it in one of their video speaks on the next developer conference.

They should define a best-practise for this, as it seems that every developer tries to solve this "download-bitmap" use-case their own way, when we in fact are all trying to do the same thing.

I have also tested using the same DefaultHttpClient object to fetch several images by calling execute() with diffrent urls (HttpGet objects), but its still far from the speed to the built-in browser. I see that my requests has sat the connection keep-alive flag, but it does not seem to make any difference.

答:
There are two reasons why the built-in browser is faster as your code:

The browser is mainly implemented in native code (e.g. WebKit)

Multiple downloads are performed simultaneously (multiple threads)

Body:
I need to know : What is the fastest way to download several thumbs in a row, lets say 10 images. It seems like the built-in browser does this in a very clever way.

I have Google'd and found that most developers are using the HttpUrlConnection class to download a jpeg to display it in a ImageView, inside an ListAdapter etc.

Some developers implements the download by using DefaultHttpClient class as it has better support for timeouts etc. In fact Google recommends to use the Apache Http client, and not the native Java HttpUrlConnection. That said, both startegies mentioned works fine, but thay are very slow compared to how the build in browser on my HTC desire download thumbnails. The built in browser seems to download images about 5x-10x faster then when try to download the same bitmaps with my own code. And yes, I always do the download/http work on a separate worker thread (not GUI thread).

Do anybody know how the built-in browser is downloading thumbs, or at least what is the fastest way to download several images from a server ?

I have tried using this code:

DefaultHttpClient client = new DefaultHttpClient();
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, SO_TIMEOUT);
client.setParams(httpParameters);
client.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
    @Override
    public long getKeepAliveDuration(HttpResponse response, HttpContext context)
    {
        return 5000;
    }
});

Now, i use this connection to fetch several bitmaps / thumbs in a for-loop:

public static Bitmap downloadBitmap(String url, DefaultHttpClient client){

  HttpResponse response = null;
  HttpGet get = new HttpGet(url);
  try {
      response = client.execute(get);
      return BitmapFactory.decodeStream(response.getEntity().getContent());
  }
  catch (ClientProtocolException e1) {
      e1.printStackTrace();
  }
  catch (IllegalStateException e){
      e.printStackTrace();
  }
  catch (IOException e1) {
      e1.printStackTrace();
  }

  return null;
}

I created a testpage.html with 10 bitmaps and loaded it with the built-in browser. The browser renders the page with all the thumbs within 1 seconds. And I'm sure they are not cached in the browser, as i randomize the 10 images for every page-refresh.

When i try to make a simple activity that downloads and displays the same thumbs, its a lot slower.

I hope the Google Android Team picks up this and includes it in one of their video speaks on the next developer conference.

They should define a best-practise for this, as it seems that every developer tries to solve this "download-bitmap" use-case their own way, when we in fact are all trying to do the same thing.

I have also tested using the same DefaultHttpClient object to fetch several images by calling execute() with diffrent urls (HttpGet objects), but its still far from the speed to the built-in browser. I see that my requests has sat the connection keep-alive flag, but it does not seem to make any difference.


问:
Identify python errors
Can someone assist with identifying the errors in this loop?

I am completely new to Python.

```<code>for p in players:
    x = len(p)
    dice = random.randint(0, x*2)
    print p + " rolls a " + dice + " out of " + str(x*2)
    if dice > x:
       print p + " wins!"
    elif dice == x:
           print p + "gets a tie."
    else:
           print p + " loses."}
</code>```

Thanks!!

答:
Works in Python 3.x

```<code>import random

players = ["Player 1", "Player 2"]

for p in players:
    x = len(p)
    dice = random.randint(0, x*2)
    print(str(p) + " rolls a " + str(dice) + " out of " + str(x*2))
    if dice > x:
        print(p + " wins!")
    elif dice == x:
        print(p + "gets a tie.")
    else:
        print(p + " loses.")
</code>```

For Python 2.x

```<code>import random

players = ["Player 1", "Player 2"]

for p in players:
    x = len(p)
    dice = random.randint(0, x*2)
    print(str(p) + " rolls a " + str(dice) + " out of " + str(x*2))
    if dice > x:
        print p + " wins!"
    elif dice == x:
        print p + "gets a tie."
    else:
        print p + " loses."
</code>```

or add from __future__ import print_function to first example to ensure compability between Python 3 and 2.

Title: Identify python errors

Body:
Can someone assist with identifying the errors in this loop?

I am completely new to Python.

for p in players:
    x = len(p)
    dice = random.randint(0, x*2)
    print p + " rolls a " + dice + " out of " + str(x*2)
    if dice > x:
       print p + " wins!"
    elif dice == x:
           print p + "gets a tie."
    else:
           print p + " loses."}

Thanks!!

Body:
Works in Python 3.x

import random

players = ["Player 1", "Player 2"]

for p in players:
    x = len(p)
    dice = random.randint(0, x*2)
    print(str(p) + " rolls a " + str(dice) + " out of " + str(x*2))
    if dice > x:
        print(p + " wins!")
    elif dice == x:
        print(p + "gets a tie.")
    else:
        print(p + " loses.")

For Python 2.x

import random

players = ["Player 1", "Player 2"]

for p in players:
    x = len(p)
    dice = random.randint(0, x*2)
    print(str(p) + " rolls a " + str(dice) + " out of " + str(x*2))
    if dice > x:
        print p + " wins!"
    elif dice == x:
        print p + "gets a tie."
    else:
        print p + " loses."

or add from __future__ import print_function to first example to ensure compability between Python 3 and 2.


问:
Inserting Data into MONGODB with POST request
I'm using npm request to insert data into MongoDB - like a direct injection using the variables of a form. This is what I can see in the browser after I click the submit button:
FORM DATA

And this is the script I'm using to insert credentials into the DB:

```<code>request.post(
            'http://127.0.0.1:8081/process_post', {
                json: {
                    fname: 'john',
                surname:'smtith',
                age:100,
                password: '123as',
                email: 'email@email.com',
                phone: 9283746,
                city: 'anywhere',
                country: 'AZSW',
                postal_code: 117058,
                picture: 'something.jpg',
                description:'description'
            },
            function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    console.log(body)
                }
            }
        );
</code>```

This the server side function:

```<code>app.post('/process_post', urlencodedParser, function (req, res) {
    var response = {fname: req.body.fname, surname: req.body.surname, age: req.body.age,
password: req.body.password,email: req.body.email, phone: req.body.phone,
city: req.body.city, country: req.body.country, postal_code: req.body.postal_code,
description: req.body.description, picture:req.body.picture};

//etc
</code>```

The issue is that the server gets all messed up with the variables and does a random match of the sent data. Also, in the mongo shell I can see that data comes as "undefined"...Is it because I'm sending a Json and the server side is set to capture variables?

EDIT: these are the logs of the server

答:
First do the json parse of the request body:

```<code>let reqBody = JSON.parse(req.body)
</code>```

Next create your data Model, for example, user:

```<code>newUser = new User({
    'attr1': reqBody.attr1,
    'attr2': reqBody.attr2,
    'attrN': reqBody.attrN
});

newUser.save(function storeUser(err, user) {
   //TODO: check if the user was saved correctly.
});
</code>```

Body:
I'm using npm request to insert data into MongoDB - like a direct injection using the variables of a form. This is what I can see in the browser after I click the submit button:
FORM DATA

And this is the script I'm using to insert credentials into the DB:

request.post(
            'http://127.0.0.1:8081/process_post', {
                json: {
                    fname: 'john',
                surname:'smtith',
                age:100,
                password: '123as',
                email: 'email@email.com',
                phone: 9283746,
                city: 'anywhere',
                country: 'AZSW',
                postal_code: 117058,
                picture: 'something.jpg',
                description:'description'
            },
            function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    console.log(body)
                }
            }
        );

This the server side function:

app.post('/process_post', urlencodedParser, function (req, res) {
    var response = {fname: req.body.fname, surname: req.body.surname, age: req.body.age,
password: req.body.password,email: req.body.email, phone: req.body.phone,
city: req.body.city, country: req.body.country, postal_code: req.body.postal_code,
description: req.body.description, picture:req.body.picture};

//etc

The issue is that the server gets all messed up with the variables and does a random match of the sent data. Also, in the mongo shell I can see that data comes as "undefined"...Is it because I'm sending a Json and the server side is set to capture variables?

EDIT: these are the logs of the server

Body:
First do the json parse of the request body:

let reqBody = JSON.parse(req.body)

Next create your data Model, for example, user:

newUser = new User({
    'attr1': reqBody.attr1,
    'attr2': reqBody.attr2,
    'attrN': reqBody.attrN
});

newUser.save(function storeUser(err, user) {
   //TODO: check if the user was saved correctly.
});


问:
Ember pushObjects() not notifying computed property
I'm trying to use ember-light-table and I'm having some troubles on updating my array of objects.

When I use the action updateList(), I can see both arrays changing (adding/removing objects to the list), but the computed property tableModel is not triggered!

I thought pushObjects() would do the trick, but it's not notifying for some reason (it's adding). I also tried to initialize select_people with Ember.A(), although [] should already be an ember array...

My mixin:

```<code>// table-testing
import Ember from 'ember';
import Table from 'ember-light-table';

export default Ember.Mixin.create({
  table: null,
  tableColumns: null,
  tableModel: null,
  init() {
    this._super(...arguments);
    let table = new Table(this.get('tableColumns'), this.get('tableModel'), { enableSync: this.get('enableSync') });
    this.set('table', table);
  }
});
</code>```

My controller

```<code>import Ember from 'ember';
import TableTesting from '../mixins/table-testing';
const { computed } = Ember;

export default Ember.Controller.extend(TableTesting, {
  tableColumns: computed(function() {
    return [{
      label: 'First Name',
      valuePath: 'firstName',
      width: '50%',
      sortable: false,
    }, {
      label: 'Last Name'
      valuePath: 'lastName',
      width: '50%'
    }]
  }),
  tableModel: computed('selected_people.@each.firstName', function() {
    // THIS MESSAGE ONLY SHOW WHEN VIEW IS RENDERED
    // I've tried .[], .@each, .length... none of them worked and I believe @each.firstName would be the most appropriated from what I've read
    console.log('computed method not showing',this.get('selected_people'));
    return this.get('selected_people');
  }),
  init() {
    this._super(...arguments);
    this.set('selected_people',[]);
  },
  actions: {
    updateList(item, moveToList) {
      let removeFromList, fromList, toList;
      if (moveToList === 'people') {
        removeFromList = 'selected_people'
      } else if (moveToList === "selected_people") {
        removeFromList = 'people';
      }
      // get the object lists
      fromList = this.get(removeFromList);
      toList = this.get(moveToList);
      // update list ---> HERE I UPDATE USING KOVL METHOD
      toList.pushObjects(item);
      fromList.removeObjects(item);
      console.log('update!',this.get('selected_people'));
    }
}
</code>```

答:
Just make sure tableModel should be accessed/required by the template or in code.

Computed property is lazy, so it will be calculated when you ask for it either inside the code or in a template. otherwise, it will not be called.
First time when we call, it will return result and it will be cached. and subsequent access will get it from cache. Changing any of the dependent properties causes the cache to invalidate so that the computed function runs again on the next access.

Mostlty copied from guides.emberjs

Body:
I'm trying to use ember-light-table and I'm having some troubles on updating my array of objects.

When I use the action updateList(), I can see both arrays changing (adding/removing objects to the list), but the computed property tableModel is not triggered!

I thought pushObjects() would do the trick, but it's not notifying for some reason (it's adding). I also tried to initialize select_people with Ember.A(), although [] should already be an ember array...

My mixin:

// table-testing
import Ember from 'ember';
import Table from 'ember-light-table';

export default Ember.Mixin.create({
  table: null,
  tableColumns: null,
  tableModel: null,
  init() {
    this._super(...arguments);
    let table = new Table(this.get('tableColumns'), this.get('tableModel'), { enableSync: this.get('enableSync') });
    this.set('table', table);
  }
});

My controller

import Ember from 'ember';
import TableTesting from '../mixins/table-testing';
const { computed } = Ember;

export default Ember.Controller.extend(TableTesting, {
  tableColumns: computed(function() {
    return [{
      label: 'First Name',
      valuePath: 'firstName',
      width: '50%',
      sortable: false,
    }, {
      label: 'Last Name'
      valuePath: 'lastName',
      width: '50%'
    }]
  }),
  tableModel: computed('selected_people.@each.firstName', function() {
    // THIS MESSAGE ONLY SHOW WHEN VIEW IS RENDERED
    // I've tried .[], .@each, .length... none of them worked and I believe @each.firstName would be the most appropriated from what I've read
    console.log('computed method not showing',this.get('selected_people'));
    return this.get('selected_people');
  }),
  init() {
    this._super(...arguments);
    this.set('selected_people',[]);
  },
  actions: {
    updateList(item, moveToList) {
      let removeFromList, fromList, toList;
      if (moveToList === 'people') {
        removeFromList = 'selected_people'
      } else if (moveToList === "selected_people") {
        removeFromList = 'people';
      }
      // get the object lists
      fromList = this.get(removeFromList);
      toList = this.get(moveToList);
      // update list ---> HERE I UPDATE USING KOVL METHOD
      toList.pushObjects(item);
      fromList.removeObjects(item);
      console.log('update!',this.get('selected_people'));
    }
}


问:
How to check existing environment variable using a var in bash?

Context

I am writting a .sh file which read a .config file. In this .config file (which I can't edit) there are some variables. I want to test if those variables are defined as environment variables.

.config file:

```<code>APPLICATION_PATH=/var/www/application
MONGO_DATA_PATH=/var/lib/mongodb
MYSQL_DATA_PATH=/var/lib/mysql
</code>```

test.sh file:

```<code>#!/bin/sh
if test -e ../my_folder/.config                      # Test if the .config file exists
then
    cat ../my_folder/.config | while read line; do   # Read the .config file line per line

        env_var="${line%=*}"                         # Get the part before the '=' character of the current line (e.G. APPLICATION_PATH)
        echo $env_var                                # Display the var (e.G. APPLICATION_PATH)

                                                     # Here, I would like to display the env var,
                                                     # e.G. like it would do using echo $APPLICATION_PATH
                                                     # but using the $env_var

        ( "echo \$$env_var" )                        # Throw an error
    done
fi
</code>```

Problem

It seems that ( "echo \$$env_var" ) is not possible. When I run test.sh, it displays this:

APPLICATION_PATH

./test.sh: ligne 13: echo $APPLICATION_PATH : not found

MONGO_DATA_PATH

./test.sh: ligne 13: echo $MONGO_DATA_PATH : not found

MYSQL_DATA_PATH

./test.sh: ligne 13: echo $MYSQL_DATA_PATH : not found

Question

How can I test if there is an environment variable using $env_var?

答:
If you can sacrifice portability, you should use indirect parameter expansion. The availability and exact syntax varies from shell to shell; this is how you would do it in bash:

```<code>while IFS== read -r varname _; do
  printf '%s\n' "${!varname}"
done < ../my_folder/.config
</code>```

If you want to sacrifice safety, you would do use eval:

```<code>while IFS== read -r varname _; do
  eval "printf '%s\n' \$$varname"
done < ../my_folder/.config
</code>```

Sacrificing simplicity is beyond the scope of Stack Overflow. One possibility, though, is to use expr to ensure that varname only contains a valid shell identifier before using eval.

```<code>while IFS== read -r varname _; do
  expr "$varname" : '[[:alpha:]_][[:alnum:]_]*' || continue
  eval "printf '%s\n' \$$varname"
done < ../my_folder/.config
</code>```

Body:
Context

I am writting a .sh file which read a .config file. In this .config file (which I can't edit) there are some variables. I want to test if those variables are defined as environment variables.

.config file:

APPLICATION_PATH=/var/www/application
MONGO_DATA_PATH=/var/lib/mongodb
MYSQL_DATA_PATH=/var/lib/mysql

test.sh file:

#!/bin/sh
if test -e ../my_folder/.config                      # Test if the .config file exists
then
    cat ../my_folder/.config | while read line; do   # Read the .config file line per line

        env_var="${line%=*}"                         # Get the part before the '=' character of the current line (e.G. APPLICATION_PATH)
        echo $env_var                                # Display the var (e.G. APPLICATION_PATH)

                                                     # Here, I would like to display the env var,
                                                     # e.G. like it would do using echo $APPLICATION_PATH
                                                     # but using the $env_var

        ( "echo \$$env_var" )                        # Throw an error
    done
fi

Problem

It seems that ( "echo \$$env_var" ) is not possible. When I run test.sh, it displays this:

APPLICATION_PATH

./test.sh: ligne 13: echo $APPLICATION_PATH : not found

MONGO_DATA_PATH

./test.sh: ligne 13: echo $MONGO_DATA_PATH : not found

MYSQL_DATA_PATH

./test.sh: ligne 13: echo $MYSQL_DATA_PATH : not found

Question

How can I test if there is an environment variable using $env_var?

Body:
If you can sacrifice portability, you should use indirect parameter expansion. The availability and exact syntax varies from shell to shell; this is how you would do it in bash:

while IFS== read -r varname _; do
  printf '%s\n' "${!varname}"
done < ../my_folder/.config

If you want to sacrifice safety, you would do use eval:

while IFS== read -r varname _; do
  eval "printf '%s\n' \$$varname"
done < ../my_folder/.config

Sacrificing simplicity is beyond the scope of Stack Overflow. One possibility, though, is to use expr to ensure that varname only contains a valid shell identifier before using eval.

while IFS== read -r varname _; do
  expr "$varname" : '[[:alpha:]_][[:alnum:]_]*' || continue
  eval "printf '%s\n' \$$varname"
done < ../my_folder/.config


问:
Submitting Python file and Java jars to Spark- Error: No main class set in JAR; please specify one with --class
I have to execute a python file with user defined Java functions using py4j.
I am using a spark-submit command to send the pyfiles and jars to the executors. The code I've written for Py4j will handle the rest.

However I received an error

Error: No main class set in JAR; please specify one with --class

The command is as follows:

```<code> spark-submit  --files /home/USER/PATH/SOMEFILE.txt --conf spark.executor.extraClassPath= /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar  --executor-memory 512m  --driver-class-path /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar  --master local[*]  --jars /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar  --driver-memory 512m  --py-files /home/USER/PATH/eggs/kafka.egg,/home/USER/PATH/eggs/redis.egg,/home/USER/PATH/helloworld.egg,/home/USER/PATH/helloworld.py
</code>```

My problem is that I don't have a Java class to specify. I have python files, so what am I supposed to exactly specify?

Also I have used the --jars, --conf spark.executor.extraClassPath, --driver-class-path options to send the jar to the executors as it contains the user defined functions.

Simply mentioning --jars or --driver-class-path wasn't doing the job so tried the third parameter, which raised the error.

Thanks in advance.

答:
There was a space between "--conf spark.executor.extraClassPath=" and  "/home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar" as seen below-

--conf spark.executor.extraClassPath= /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar

Also moved the --conf settings to the start of the spark-submit command, like so:

```<code>spark-submit --conf spark.executor.extraClassPath=/home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar   --files /home/USER/PATH/SOMEFILE.txt --executor-memory 512m  --driver-class-path /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar  --master local[*]  --jars /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar  --driver-memory 512m  --py-files /home/USER/PATH/eggs/kafka.egg,/home/USER/PATH/eggs/redis.egg,/home/USER/PATH/helloworld.egg,/home/USER/PATH/helloworld.py
</code>```

This sorted my issue.

Body:
I have to execute a python file with user defined Java functions using py4j.
I am using a spark-submit command to send the pyfiles and jars to the executors. The code I've written for Py4j will handle the rest.

However I received an error

Error: No main class set in JAR; please specify one with --class

The command is as follows:

 spark-submit  --files /home/USER/PATH/SOMEFILE.txt --conf spark.executor.extraClassPath= /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar  --executor-memory 512m  --driver-class-path /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar  --master local[*]  --jars /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar  --driver-memory 512m  --py-files /home/USER/PATH/eggs/kafka.egg,/home/USER/PATH/eggs/redis.egg,/home/USER/PATH/helloworld.egg,/home/USER/PATH/helloworld.py

My problem is that I don't have a Java class to specify. I have python files, so what am I supposed to exactly specify?

Also I have used the --jars, --conf spark.executor.extraClassPath, --driver-class-path options to send the jar to the executors as it contains the user defined functions.

Simply mentioning --jars or --driver-class-path wasn't doing the job so tried the third parameter, which raised the error.

Thanks in advance.

Body:
There was a space between "--conf spark.executor.extraClassPath=" and  "/home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar" as seen below-

--conf spark.executor.extraClassPath= /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar

Also moved the --conf settings to the start of the spark-submit command, like so:

spark-submit --conf spark.executor.extraClassPath=/home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar   --files /home/USER/PATH/SOMEFILE.txt --executor-memory 512m  --driver-class-path /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar  --master local[*]  --jars /home/USER/DEFINED_FUNCTIONS/IN JAVA/XYZ/XYZ.jar  --driver-memory 512m  --py-files /home/USER/PATH/eggs/kafka.egg,/home/USER/PATH/eggs/redis.egg,/home/USER/PATH/helloworld.egg,/home/USER/PATH/helloworld.py

This sorted my issue.