问:
Getting "BadRequest" when posting data to SharePoint Online list with HttpClient
I am trying to post data to a list on SharePoint Online with the C# HttpClient. this is my code:

```<code>  using (var client = new SPHttpClient(webUri, userName, password))
        {
            var listTitle = "HttpClientList";
            var itemPayload = new
            {
                __metadata = new
                {
                    type = "SP.Data.HttpClientListListItem"
                },
                Title = "test3",<--column name "Title"
                _x0071_cr5 = "value3"<--column name "Value"
            };
            var endpointUrl = string.Format("{0}/_api/web/lists/getbytitle('{1}')/items", webUri, listTitle);
            var data = client.ExecuteJson(endpointUrl, HttpMethod.Post, itemPayload);
            Console.WriteLine("Task item '{0}' has been created", data["d"]["Title"]);
            Console.ReadLine();
</code>```

As of right now, I am getting status "400, BadRequest". My guess is that I am missing something or feeding the post request the wrong data.
I have been following this blogpost Blogpost
I can only execute the verb GET. All other verbs gives me "400, BadRequest"

答:
Solved it with varoius solutions.

Added the right ListItem HttpClientListListItem.
created all columns thru the ListSettings panel.
Replaced the client.ExecuteJson() with client.ExecuteJson(endpointUrl, HttpMethod.Post, headers, default(string));.
 Thanks for all the help!

Body:
I am trying to post data to a list on SharePoint Online with the C# HttpClient. this is my code:

  using (var client = new SPHttpClient(webUri, userName, password))
        {
            var listTitle = "HttpClientList";
            var itemPayload = new
            {
                __metadata = new
                {
                    type = "SP.Data.HttpClientListListItem"
                },
                Title = "test3",<--column name "Title"
                _x0071_cr5 = "value3"<--column name "Value"
            };
            var endpointUrl = string.Format("{0}/_api/web/lists/getbytitle('{1}')/items", webUri, listTitle);
            var data = client.ExecuteJson(endpointUrl, HttpMethod.Post, itemPayload);
            Console.WriteLine("Task item '{0}' has been created", data["d"]["Title"]);
            Console.ReadLine();

As of right now, I am getting status "400, BadRequest". My guess is that I am missing something or feeding the post request the wrong data.
I have been following this blogpost Blogpost
I can only execute the verb GET. All other verbs gives me "400, BadRequest"


来源: stackexchange

问:
Add image data to html file?
My goal is to create one HTML file, that contains everything that it needs for it's proper functioning.

I've added my .css's content to the html head between

ContentLicense: CC BY-SA 3.0

Title: Add image data to html file?

Body:
Convert image to base64 (however it is not recommended for large images)

For example

<img src="data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAKgALAAAAAA9AEQAAAj/AFEJHEiwoMGDCBMqXMiwocAbBww4nEhxoYkUpzJGrMixogkfGUNqlNixJEIDB0SqHGmyJSojM1bKZOmyop0gM3Oe2liTISKMOoPy7GnwY9CjIYcSRYm0aVKSLmE6nfq05QycVLPuhDrxBlCtYJUqNAq2bNWEBj6ZXRuyxZyDRtqwnXvkhACDV+euTeJm1Ki7A73qNWtFiF+/gA95Gly2CJLDhwEHMOUAAuOpLYDEgBxZ4GRTlC1fDnpkM+fOqD6DDj1aZpITp0dtGCDhr+fVuCu3zlg49ijaokTZTo27uG7Gjn2P+hI8+PDPERoUB318bWbfAJ5sUNFcuGRTYUqV/3ogfXp1rWlMc6awJjiAAd2fm4ogXjz56aypOoIde4OE5u/F9x199dlXnnGiHZWEYbGpsAEA3QXYnHwEFliKAgswgJ8LPeiUXGwedCAKABACCN+EA1pYIIYaFlcDhytd51sGAJbo3onOpajiihlO92KHGaUXGwWjUBChjSPiWJuOO/LYIm4v1tXfE6J4gCSJEZ7YgRYUNrkji9P55sF/ogxw5ZkSqIDaZBV6aSGYq/lGZplndkckZ98xoICbTcIJGQAZcNmdmUc210hs35nCyJ58fgmIKX5RQGOZowxaZwYA+JaoKQwswGijBV4C6SiTUmpphMspJx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+yXqqBANsgCtit4FWQAEkrNbpq7HSOmtwag5w57GrmlJBASEU18ADjUYb3ADTinIttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==">

To convert image to base64, you can use HTML5 canvas toDataUrl.


问:
Are Docker Volumes machine-specific
I'm new to Docker Swarm. As I understand, Docker Swarm allows you to abstract from clustering. Means you don't care on which hardriwe container is deployed.

On the other hand, the standard way to handle database in Docker - is to write data outside Docker container (to avoid copy-on-write behaviour). That's achieved by mounting a Volume and write db-related data to it. The important thing here - are Volumes machine-specific? Are Docker & Docker Swarm clever enough to mount a Volume on the machine it's needed?

Example:

I have 3 machines and 3 microservices/containers. All of them are deployed through Docker Swarm. Only one microservice/container must connect to a database. So I need to mount Volume only on one machine. But on which?

答:
Databases and similar stateful applications are still a hard thing to deal with when it comes to Docker swarm and other orchestration frameworks. Ideally, containers should be able to run on any node in the swarm, but the problem comes when you need to persist data beyond the container's lifecycle.

Mounting a volume is the Docker way to persist data, however this ties the container with a specific node as volumes are created on the specific nodes. There are many projects that try to solve this problem and provide some sort of distributed storage.

There was a project called Flocker that deals with the above problem (it’s no longer maintained). There is also a newer project called REXRAY.

Are Docker & Docker Swarm clever enough to mount a Volume on the machine it's needed?

By default, no. Docker swarm will choose one of the nodes and deploy the container on it. However, you can work around this problem:

First, you need to define a named volume in you Stackfile/Composefile under the service definition.
Second, you need to use node Placement Constraints to restrict where the database container should run.

If you do not you a distributed storage tool, then when it comes to databases and similar stateful containers that need volumes, you need to restrict the container to a specific nodes.

Title: Are Docker Volumes machine-specific


问:
Zxing lib. does not work above Android M
I have successfully integrated zxing core.jar library below android Marshmallow, but while integrating this into above Marshmallow, it gives me following error:

```<code>android.content.ActivityNotFoundException: NO activity found to handle
intent{act=com.google.zxing.client.android.SCAN}
</code>```

Thanks in advance.

答:
@ Kevin Robatel
my manifest

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

and following code executes onClick of button

```<code>try {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        //intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
        startActivityForResult(intent, BARCODE_CAPTURE_ACTIVITY);
    } catch (ActivityNotFoundException anfe) {
        Toast.makeText(mContext, "Scanner Not Found "+anfe.toString() , Toast.LENGTH_LONG).show();
    }
</code>```

Body:
I have successfully integrated zxing core.jar library below android Marshmallow, but while integrating this into above Marshmallow, it gives me following error:

android.content.ActivityNotFoundException: NO activity found to handle
intent{act=com.google.zxing.client.android.SCAN}

Thanks in advance.

Body:
@ Kevin Robatel
my manifest

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

and following code executes onClick of button

try {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        //intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
        startActivityForResult(intent, BARCODE_CAPTURE_ACTIVITY);
    } catch (ActivityNotFoundException anfe) {
        Toast.makeText(mContext, "Scanner Not Found "+anfe.toString() , Toast.LENGTH_LONG).show();
    }


问:
Native Heap Maximum size and release of memory
I am a little bit confused about the native heap on android, I would
like know the native heap max size, there is a way to know it?

Like

```<code>getRuntime().maxMemory()
</code>```

which I use for know the maximum limit  of VM heap.

Another question is relative at how the native heap memory is
released, I read that IS NOT the GC of Dalvik which free that memory,
is correct? If yes, when the memory of native heap is released?
Thanks a lot in advance for any suggestion.
pedr0

答:
I solved this issues.

For see the native heap in DDMS you have to run the DDMS standalone and add this line at the file ddms.cfg :

```<code>native=true
</code>```

After that you will see that "Native Heap" Tab in DDMS.

Bye!

ContentLicense: CC BY-SA 2.5

Body:
I am a little bit confused about the native heap on android, I would
like know the native heap max size, there is a way to know it?

Like

getRuntime().maxMemory()

which I use for know the maximum limit  of VM heap.

Another question is relative at how the native heap memory is
released, I read that IS NOT the GC of Dalvik which free that memory,
is correct? If yes, when the memory of native heap is released?
Thanks a lot in advance for any suggestion.
pedr0

Body:
I solved this issues.

For see the native heap in DDMS you have to run the DDMS standalone and add this line at the file ddms.cfg :

native=true

After that you will see that "Native Heap" Tab in DDMS.

Bye!


问:
Use of Base64 class in JDK7
I am trying to use Base64 class in JDK 7 but I am getting the error:

Base64 cannot be resolved

Why does eclipse throw this error?

I am using the code below:

```<code>byte[] imageData = Base64.getDecoder().decode(readFile(imagePart.getInputStream()));
</code>```

even import statement also shows the same error : import java.util.Base64;

Is this class not available in JDK 7?

答:
If it is needed to specifically use JDK7 for your project, and you still need to use java.util.Base64 class, you can include in your project the code for that class from OpenJDK.

Source for this class is available at:

http://www.grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Base64.java?av=f

Base64.java file can be downloaded at:

http://www.grepcode.com/file_/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Base64.java/?v=source&disposition=attachment

ContentLicense: CC BY-SA 4.0

Title: Use of Base64 class in JDK7

Body:
I am trying to use Base64 class in JDK 7 but I am getting the error:

Base64 cannot be resolved

Why does eclipse throw this error?

I am using the code below:

byte[] imageData = Base64.getDecoder().decode(readFile(imagePart.getInputStream()));

even import statement also shows the same error : import java.util.Base64;

Is this class not available in JDK 7?


问:
Stop ConfigParser adding spaces to delims after upgrade from python 2.7.3 to 2.7.9
After being forced to use a later version of python, ConfigParser now insists on adding spaces to each side of any delims when modifying a configuration file.

e.g.
setting=90   becomes: setting = 90

This was not the behavior in the earlier version, and I cannot find a way of controlling this behavior, can anyone help?

My test code looks like this:

```<code>import ConfigParser
import os

config   = ConfigParser.ConfigParser()
cfgfile  = '/home/osmc/bin/test/config.txt'
os.system('sudo echo "[section]" > ' + cfgfile)
os.system('sudo echo "setting=0" >> ' + cfgfile)

config.read(cfgfile)
config.set('section','setting', '1' )

with open(cfgfile, 'wb') as newcfgfile:
    config.write(newcfgfile)
</code>```

Thanks in advance.

答:
I ran into this problem to and I came up with an additional solution as posted here.

I didn't want to replace the function as future versions of Python might change the internal function structures of RawConfigParser.

I also didn't want to read the file back in right after it was written because that seemed wasteful

Instead I wrote a wrapper around the file object which simply replaces " = " with "=" in all lines written though it.

```<code>class EqualsSpaceRemover:
    output_file = None
    def __init__( self, new_output_file ):
        self.output_file = new_output_file

    def write( self, what ):
        self.output_file.write( what.replace( " = ", "=", 1 ) )

config.write( EqualsSpaceRemover( cfgfile ) )
</code>```

Body:
After being forced to use a later version of python, ConfigParser now insists on adding spaces to each side of any delims when modifying a configuration file.

e.g.
setting=90   becomes: setting = 90

This was not the behavior in the earlier version, and I cannot find a way of controlling this behavior, can anyone help?

My test code looks like this:

import ConfigParser
import os

config   = ConfigParser.ConfigParser()
cfgfile  = '/home/osmc/bin/test/config.txt'
os.system('sudo echo "[section]" > ' + cfgfile)
os.system('sudo echo "setting=0" >> ' + cfgfile)

config.read(cfgfile)
config.set('section','setting', '1' )

with open(cfgfile, 'wb') as newcfgfile:
    config.write(newcfgfile)

Thanks in advance.

Body:
I ran into this problem to and I came up with an additional solution as posted here.

I didn't want to replace the function as future versions of Python might change the internal function structures of RawConfigParser.

I also didn't want to read the file back in right after it was written because that seemed wasteful

Instead I wrote a wrapper around the file object which simply replaces " = " with "=" in all lines written though it.

class EqualsSpaceRemover:
    output_file = None
    def __init__( self, new_output_file ):
        self.output_file = new_output_file

    def write( self, what ):
        self.output_file.write( what.replace( " = ", "=", 1 ) )

config.write( EqualsSpaceRemover( cfgfile ) )


问:
Kendo UI - Angular - Formatting a date column
I'm trying a simple thing as displaying a date column in a kendo ui grid in Angular using the following:

```<code><kendo-grid-column field="date" title="Date" type="date" format="{0:d}"></kendo-grid-column>
</code>```

However the result is:

'2017-04-30T09:00:00'

答:
I guess you are using the data received from your backend. It that case your should convert your date field to Date type manually.  </p>

```<code>return this.http.get("url")
        .map((res: Response) => {
            let result = res.json();
            result.forEach((x) => {
                x.dateField= new Date(x.dateField);
            });

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

Body:
I'm trying a simple thing as displaying a date column in a kendo ui grid in Angular using the following:

<kendo-grid-column field="date" title="Date" type="date" format="{0:d}"></kendo-grid-column>

However the result is:

'2017-04-30T09:00:00'

Body:
I guess you are using the data received from your backend. It that case your should convert your date field to Date type manually.

return this.http.get("url")
        .map((res: Response) => {
            let result = res.json();
            result.forEach((x) => {
                x.dateField= new Date(x.dateField);
            });

            return result;
        })


问:
javascript replace instance of string
I want to replace all instance of particular string using javascript/jquery.

My source string is '\\n' and my desired output is '\n'.

this should happen at all instance with in a string.

答:
var str = "hii All, \\n I am sambo. \\n Thank you for listening.";
var res = str.replace(/\\n/gi, "\n");
console.log(str);```

Use replace with regex.

Title: javascript replace instance of string

Body:
var str = "hii All, \\n I am sambo. \\n Thank you for listening.";
var res = str.replace(/\\n/gi, "\n");
console.log(str);

Use replace with regex.


问:
Combine Lists with Same Heads in a 2D List (OCaml)
I'm working with a list of lists in OCaml, and I'm trying to write a function that combines all of the lists that share the same head. This is what I have so far, and I make use of the List.hd built-in function, but not surprisingly, I'm getting the failure "hd" error:

```<code>let rec combineSameHead list nlist = match list with
 | [] -> []@nlist
 | h::t -> if List.hd h = List.hd (List.hd t)
    then combineSameHead t nlist@uniq(h@(List.hd t))
    else combineSameHead t nlist@h;;
</code>```

So for example, if I have this list:

```<code>[[Sentence; Quiet]; [Sentence; Grunt]; [Sentence; Shout]]
</code>```

I want to combine it into:

```<code>[[Sentence; Quiet; Grunt; Shout]]
</code>```

The function uniq I wrote just removes all duplicates within a list. Please let me know how I would go about completing this. Thanks in advance!

答:
You can do a lot just using the standard library:

```<code>(* compares the head of a list to a supplied value.  Used to partition a lists of lists *)
let partPred x = function h::_ -> h = x
  | _ -> false

let rec combineHeads = function [] -> []
  | []::t -> combineHeads t (* skip empty lists *)
  | (hh::_ as h)::t -> let r, l = List.partition (partPred hh) t in (* split into lists with the same head as the first, and lists with different heads *)
  (List.fold_left (fun x y -> x @ (List.tl y)) h r)::(combineHeads l) (* combine all the lists with the same head, then recurse on the remaining lists *)

combineHeads [[1;2;3];[1;4;5;];[2;3;4];[1];[1;5;7];[2;5];[3;4;6]];;
- : int list list = [[1; 2; 3; 4; 5; 5; 7]; [2; 3; 4; 5]; [3; 4; 6]]
</code>```

This won't be fast (partition, fold_left and concat are all O(n)) however.

Body:
I'm working with a list of lists in OCaml, and I'm trying to write a function that combines all of the lists that share the same head. This is what I have so far, and I make use of the List.hd built-in function, but not surprisingly, I'm getting the failure "hd" error:

let rec combineSameHead list nlist = match list with
 | [] -> []@nlist
 | h::t -> if List.hd h = List.hd (List.hd t)
    then combineSameHead t nlist@uniq(h@(List.hd t))
    else combineSameHead t nlist@h;;

So for example, if I have this list:

[[Sentence; Quiet]; [Sentence; Grunt]; [Sentence; Shout]]

I want to combine it into:

[[Sentence; Quiet; Grunt; Shout]]

The function uniq I wrote just removes all duplicates within a list. Please let me know how I would go about completing this. Thanks in advance!

Body:
You can do a lot just using the standard library:

(* compares the head of a list to a supplied value.  Used to partition a lists of lists *)
let partPred x = function h::_ -> h = x
  | _ -> false

let rec combineHeads = function [] -> []
  | []::t -> combineHeads t (* skip empty lists *)
  | (hh::_ as h)::t -> let r, l = List.partition (partPred hh) t in (* split into lists with the same head as the first, and lists with different heads *)
  (List.fold_left (fun x y -> x @ (List.tl y)) h r)::(combineHeads l) (* combine all the lists with the same head, then recurse on the remaining lists *)

combineHeads [[1;2;3];[1;4;5;];[2;3;4];[1];[1;5;7];[2;5];[3;4;6]];;
- : int list list = [[1; 2; 3; 4; 5; 5; 7]; [2; 3; 4; 5]; [3; 4; 6]]

This won't be fast (partition, fold_left and concat are all O(n)) however.


问:
Remove a wrapper function in IntelliJ IDEA?
I have a foreach block that wraps multiple statements such as:

$outputArr[$type . "_" . "orgName"] = urlencode($this->params[$prefix."companyname"]);

Is there any shortcut handy that will just remove the urlencode wrapper, in this example, without me having to manually go to end of line, delete the end bracket?

Bonus point: Do it in one command for all the same repeating wrapping urlencode lines in the block :)

答:
Regarding this, I have 3 approaches, which I miss them all since I switched to Neovim -- that's like another world of text editing.

Back to IntelliJ, here are my 3 approaches:

1. Multicaret (Alt+Shift+Drag)

If the lines are neighboring and similar, though for a single line this is in no sense easier, it saves time when the same operation has to be done on a lot of lines.

2. Expand Selection (Ctrl+W)

Instead of getting to the end and delete the ), locate the caret in the part you want to save (like params) and click Expand Selection till $this->params[$prefix."companyname"] is selected.

Do a copy (Ctrl+C) and keep on expand selection until urlencode is also selected.  Paste it so the inner content replaced the whole selected part -- unwrapped.

It is long when described in words, but in action it's like <C-W><C-W><C-W><C-C><C-W><C-W><C-V> looking at the screen.

Faster than moving the right hand to another side of the keyboard and pressing <End> and <Left> and <Backspace>.

3. Regex Replacement in Selection (With Live Preview!)

It'll be like selecting the lines and <C-R> <M-I> (which is Alt+I for In Selection) <M-G> (for Regex) and replace urlencode\(([^)]*)\) with $1.  Some (or most) feel that using Regex is creating a harder problem for an easier problem.

P.S. I am on a Mac and I use Ctrl+A & Ctrl+E for Home & End. Ctrl+P & Ctrl+N for up & down, and Ctrl+B& Ctrl+F for left & right.  Feeling "handy" enough as my hands don't have to move away from the home row.


问:
Python Implementation of Viterbi Algorithm
I'm doing a Python project in which I'd like to use the Viterbi Algorithm.  Does anyone know of a complete Python implementation of the Viterbi algorithm?  The correctness of the one on Wikipedia seems to be in question on the talk page.  Does anyone have a pointer?</p>

答:
I have modified @Rhubarb's answer for the condition where the marginal probabilities are already known (e.g by computing the Forward Backward algorithm).</p>

```<code>def viterbi (transition_probabilities, conditional_probabilities):
    # Initialise everything
    num_samples = conditional_probabilities.shape[1]
    num_states = transition_probabilities.shape[0] # number of states

    c = np.zeros(num_samples) #scale factors (necessary to prevent underflow)
    viterbi = np.zeros((num_states,num_samples)) # initialise viterbi table
    best_path_table = np.zeros((num_states,num_samples)) # initialise the best path table
    best_path = np.zeros(num_samples).astype(np.int32) # this will be your output

    # B- appoint initial values for viterbi and best path (bp) tables - Eq (32a-32b)
    viterbi[:,0] = conditional_probabilities[:,0]
    c[0] = 1.0/np.sum(viterbi[:,0])
    viterbi[:,0] = c[0] * viterbi[:,0] # apply the scaling factor

    # C- Do the iterations for viterbi and psi for time>0 until T
    for t in range(1, num_samples): # loop through time
        for s in range (0,num_states): # loop through the states @(t-1)
            trans_p = viterbi[:, t-1] * transition_probabilities[:,s] # transition probs of each state transitioning
            best_path_table[s,t], viterbi[s,t] = max(enumerate(trans_p), key=operator.itemgetter(1))
            viterbi[s,t] = viterbi[s,t] * conditional_probabilities[s][t]

        c[t] = 1.0/np.sum(viterbi[:,t]) # scaling factor
        viterbi[:,t] = c[t] * viterbi[:,t]

    ## D - Back-tracking
    best_path[num_samples-1] =  viterbi[:,num_samples-1].argmax() # last state
    for t in range(num_samples-1,0,-1): # states of (last-1)th to 0th time step
        best_path[t-1] = best_path_table[best_path[t],t]
    return best_path
</code>```

Body:
I have modified @Rhubarb's answer for the condition where the marginal probabilities are already known (e.g by computing the Forward Backward algorithm).

def viterbi (transition_probabilities, conditional_probabilities):
    # Initialise everything
    num_samples = conditional_probabilities.shape[1]
    num_states = transition_probabilities.shape[0] # number of states

    c = np.zeros(num_samples) #scale factors (necessary to prevent underflow)
    viterbi = np.zeros((num_states,num_samples)) # initialise viterbi table
    best_path_table = np.zeros((num_states,num_samples)) # initialise the best path table
    best_path = np.zeros(num_samples).astype(np.int32) # this will be your output

    # B- appoint initial values for viterbi and best path (bp) tables - Eq (32a-32b)
    viterbi[:,0] = conditional_probabilities[:,0]
    c[0] = 1.0/np.sum(viterbi[:,0])
    viterbi[:,0] = c[0] * viterbi[:,0] # apply the scaling factor

    # C- Do the iterations for viterbi and psi for time>0 until T
    for t in range(1, num_samples): # loop through time
        for s in range (0,num_states): # loop through the states @(t-1)
            trans_p = viterbi[:, t-1] * transition_probabilities[:,s] # transition probs of each state transitioning
            best_path_table[s,t], viterbi[s,t] = max(enumerate(trans_p), key=operator.itemgetter(1))
            viterbi[s,t] = viterbi[s,t] * conditional_probabilities[s][t]

        c[t] = 1.0/np.sum(viterbi[:,t]) # scaling factor
        viterbi[:,t] = c[t] * viterbi[:,t]

    ## D - Back-tracking
    best_path[num_samples-1] =  viterbi[:,num_samples-1].argmax() # last state
    for t in range(num_samples-1,0,-1): # states of (last-1)th to 0th time step
        best_path[t-1] = best_path_table[best_path[t],t]
    return best_path


问:
trouble with two locations in nginx config
I have 2 links: myserver.org and myserver.org/support
I need first link follow to /var/www/myserver.org and second to /var/www/support
My config now:
first file & link

```<code>server {
    listen 80 default_server;

    server_name groupmanager.org;
    charset utf-8;

    root /var/www/groupmanager.org;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    access_log /var/log/nginx/groupmanager.org_access.log;
    error_log /var/log/nginx/groupmanager.org_error.log;

    include /etc/nginx/templates/php-fpm.conf;
}

server {
  listen 80;

  server_name www.groupmanager.org;
  rewrite ^(.*) http://groupmanager.org$1 permanent;
}
</code>```

Second file & link:

```<code>server {
  listen 80;

  server_name 163.172.88.31/support;
  charset utf-8;

  root /var/www/support;
  index index.php;

  access_log /var/log/nginx/support_access.log;
  error_log /var/log/nginx/support_error.log;

  include /etc/nginx/templates/php-fpm.conf;
}

server {

  listen 80;

  server_name www.163.172.88.31/support;
  rewrite ^(.*) http://163.172.88.31/support$1 permanent;
}
</code>```

php-fpm.conf

```<code>location ~ \.php$ {
   try_files $uri =404;
   fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
   fastcgi_index index.php;
   include fastcgi_params;
   fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

location ~ /\.ht {
   deny all;
}

location ~* \.(gif|jpeg|jpg|txt|png|tif|tiff|ico|jng|bmp|doc|pdf|rtf|xls|ppt|rar|rpm|swf|zip|bin|exe|dll|deb|cur)$ {
  expires 168h;
}

location ~* \.(css|js)$ {
  expires 180m;
}
</code>```

First link works fine, second - no. I see '403 Forbidden'
What is not rigth?
Permissions for folders are the same, I think, they are right.

答:
For both /var/www/myserver.org and /var/www/support you have to make two separate nginx config file with two different roots and server names .

besides , if you just want to show two links you can setup nginx for one and link the second one with just an internal link ( if they are in the same page)

Body:
I have 2 links: myserver.org and myserver.org/support
I need first link follow to /var/www/myserver.org and second to /var/www/support
My config now:
first file & link

server {
    listen 80 default_server;

    server_name groupmanager.org;
    charset utf-8;

    root /var/www/groupmanager.org;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    access_log /var/log/nginx/groupmanager.org_access.log;
    error_log /var/log/nginx/groupmanager.org_error.log;

    include /etc/nginx/templates/php-fpm.conf;
}

server {
  listen 80;

  server_name www.groupmanager.org;
  rewrite ^(.*) http://groupmanager.org$1 permanent;
}

Second file & link:

server {
  listen 80;

  server_name 163.172.88.31/support;
  charset utf-8;

  root /var/www/support;
  index index.php;

  access_log /var/log/nginx/support_access.log;
  error_log /var/log/nginx/support_error.log;

  include /etc/nginx/templates/php-fpm.conf;
}

server {

  listen 80;

  server_name www.163.172.88.31/support;
  rewrite ^(.*) http://163.172.88.31/support$1 permanent;
}

php-fpm.conf

location ~ \.php$ {
   try_files $uri =404;
   fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
   fastcgi_index index.php;
   include fastcgi_params;
   fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

location ~ /\.ht {
   deny all;
}

location ~* \.(gif|jpeg|jpg|txt|png|tif|tiff|ico|jng|bmp|doc|pdf|rtf|xls|ppt|rar|rpm|swf|zip|bin|exe|dll|deb|cur)$ {
  expires 168h;
}

location ~* \.(css|js)$ {
  expires 180m;
}

First link works fine, second - no. I see '403 Forbidden'
What is not rigth?
Permissions for folders are the same, I think, they are right.


问:
How to write algorithm for Sequencing n jobs on n machines?
I am just trying to write an algorithm.To Sequencing n jobs on n machines.
for ex:-

```<code> job1->2s;
 job2->1s;
 job3->5s;
</code>```

first we have to sort that job with time (desc)

```<code> job3->5s;
 job1->1s;
 job2->2s;
</code>```

Suppose we have 2 machines

```<code>machine1->job3
machine2->job2
</code>```

job 2 will first finished wirte the next step should be

```<code>machine1->job3 => 5s
machine2->job2+job1(2s+1s) => 3s
</code>```

And i want that total working for that machine1
which is 5s it is the longest working machine right i want that answer.
How to write algorithm for this...
what i've done so far is sorting that objects in time order...
then i don't how to imporve this algorithm to work with n number of machines with n number of jobs..

thanks in advance

run.js

```<code> var sorty = require('sorty');
    var njobs = [
        {
            jobname:"j1",
            time:42
        },
        {
            jobname:"j2",
            time:56
        },
        {
            jobname:"j3",
            time:78
        },
        {
            jobname:"j4",
            time:68
        },
        {
            jobname:"j5",
            time:43
        },
        {
            jobname:"j6",
            time:99
        },
        {
            jobname:"j7",
            time:88
        }
    ];
    var machines = 4;
    //sort desc with time
    var order = sorty([
        {name:'time',dir: 'desc',type:'number'}

    ],njobs);

    for(i=0;i<order.length;i++){
            console.log('job Name :'+order[i].jobname+' job Time to finish :'+order[i].time+' alloting machines to job');

    }
</code>```

答:
@user3297291 great implementation, but your technique only consider (n) number of jobs, but not (m) number of machines.

Here is another implementation which is capable to calculate for any number of Jobs (n) or Machines (m) where (n&m > 1). It validates the given data set and not only apply Johnson's rule but also uses CDS Algorithm to dig deep and calculate more complex alternatives with less possible makespan. Later you can export the entire timeline to excel or pdf format for further use.

The tool is completely free to use https://job-sequencing.appspot.com
Feel free to experiment!

Body:
I am just trying to write an algorithm.To Sequencing n jobs on n machines.
for ex:-

 job1->2s;
 job2->1s;
 job3->5s;

first we have to sort that job with time (desc)

 job3->5s;
 job1->1s;
 job2->2s;

Suppose we have 2 machines

machine1->job3
machine2->job2

job 2 will first finished wirte the next step should be

machine1->job3 => 5s
machine2->job2+job1(2s+1s) => 3s

And i want that total working for that machine1
which is 5s it is the longest working machine right i want that answer.
How to write algorithm for this...
what i've done so far is sorting that objects in time order...
then i don't how to imporve this algorithm to work with n number of machines with n number of jobs..

thanks in advance

run.js

 var sorty = require('sorty');
    var njobs = [
        {
            jobname:"j1",
            time:42
        },
        {
            jobname:"j2",
            time:56
        },
        {
            jobname:"j3",
            time:78
        },
        {
            jobname:"j4",
            time:68
        },
        {
            jobname:"j5",
            time:43
        },
        {
            jobname:"j6",
            time:99
        },
        {
            jobname:"j7",
            time:88
        }
    ];
    var machines = 4;
    //sort desc with time
    var order = sorty([
        {name:'time',dir: 'desc',type:'number'}

    ],njobs);

    for(i=0;i<order.length;i++){
            console.log('job Name :'+order[i].jobname+' job Time to finish :'+order[i].time+' alloting machines to job');

    }


问:
In C, when would type casting a char to an integer not return a value between 0 and 127?
A common interview question asks to write an algorithm that detects duplicates in a string.
Using a character array of length 128 to keep track of the characters already seen is a good way to solve this problem in linear time.

In C we would type something like

```<code>char seen_chars[128];
unsigned char c;

/* set seen_chars to all zeros, assign c */

seen_chars[ c ] = 1;
</code>```

To mark character c as seen. Of course this relies on

```<code>(int) c
</code>```

returning a value between 0 and 127.

I'm wondering when would this fail? What are the assumptions that make this code work correctly?

答:
On most implementations, an unsigned char has a value going from 0 to 255. Now, ASCII defines values from 0 to 127, but if your string contains characters from an "extended ASCII" character set (Latin1, for instance), then you might get character values above 127.

So, if your text is american, you're safe. Otherwise, you will overflow your buffer.

Body:
A common interview question asks to write an algorithm that detects duplicates in a string.
Using a character array of length 128 to keep track of the characters already seen is a good way to solve this problem in linear time.

In C we would type something like

char seen_chars[128];
unsigned char c;

/* set seen_chars to all zeros, assign c */

seen_chars[ c ] = 1;

To mark character c as seen. Of course this relies on

(int) c

returning a value between 0 and 127.

I'm wondering when would this fail? What are the assumptions that make this code work correctly?


问:
Fabricjs Fixed TextBox
How can I fix the size of a textBox in order to prevent it to overflow its size when typing (fixed width and height)?

```<code>var canvas = window._canvas = new fabric.Canvas('c');

var text = new fabric.Textbox('MyText', {
    width: 300,
    height: 300,
    top: 5,
    left: 5,
    hasControls: false,
    fontSize: 30,
    fixedWidth: 300,
    fixedFontSize: 30
});
canvas.add(text);
</code>```

http://jsfiddle.net/643qazk0/2/

答:
You can override insertChars method and check text overflow.

See snippet below.

// Create canvas
const canvas = new fabric.Canvas(document.querySelector('canvas'));

// Define `LimitedTextbox` class which extends `Textbox`
const LimitedTextbox = fabric.util.createClass(fabric.Textbox, {

  // Override `insertChars` method
  insertChars: function(chars) {

    if (this.maxWidth) {
      const textWidthUnderCursor = this._getLineWidth(this.ctx, this.get2DCursorLocation().lineIndex);
      if (textWidthUnderCursor + this.ctx.measureText(chars).width > this.maxWidth) {
        chars = '\n' + chars;
      }
    }

    if (this.maxLines) {
      const newLinesLength = this._wrapText(this.ctx, this.text + chars).length;
      if (newLinesLength > this.maxLines) {
        return;
      }
    }

    // Call parent class method
    this.callSuper('insertChars', chars);
  }

});

// Create limited text box with max width 300px and max 2 lines
canvas.add(
  new LimitedTextbox('text', {
    top: 10,
    left: 10,
    width: 300,
    maxWidth: 300,
    maxLines: 2
  })
);

canvas.renderAll();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.canvas-container {
  border: 1px solid gray;
}</code>```

<canvas width="600" height="300"></canvas>```

Tested with Fabric 1.7.20

Title: Fabricjs Fixed TextBox

Body:
How can I fix the size of a textBox in order to prevent it to overflow its size when typing (fixed width and height)?

var canvas = window._canvas = new fabric.Canvas('c');

var text = new fabric.Textbox('MyText', {
    width: 300,
    height: 300,
    top: 5,
    left: 5,
    hasControls: false,
    fontSize: 30,
    fixedWidth: 300,
    fixedFontSize: 30
});
canvas.add(text);

http://jsfiddle.net/643qazk0/2/

Body:
You can override insertChars method and check text overflow.

See snippet below.

// Create canvas
const canvas = new fabric.Canvas(document.querySelector('canvas'));

// Define `LimitedTextbox` class which extends `Textbox`
const LimitedTextbox = fabric.util.createClass(fabric.Textbox, {

  // Override `insertChars` method
  insertChars: function(chars) {

    if (this.maxWidth) {
      const textWidthUnderCursor = this._getLineWidth(this.ctx, this.get2DCursorLocation().lineIndex);
      if (textWidthUnderCursor + this.ctx.measureText(chars).width > this.maxWidth) {
        chars = '\n' + chars;
      }
    }

    if (this.maxLines) {
      const newLinesLength = this._wrapText(this.ctx, this.text + chars).length;
      if (newLinesLength > this.maxLines) {
        return;
      }
    }

    // Call parent class method
    this.callSuper('insertChars', chars);
  }

});

// Create limited text box with max width 300px and max 2 lines
canvas.add(
  new LimitedTextbox('text', {
    top: 10,
    left: 10,
    width: 300,
    maxWidth: 300,
    maxLines: 2
  })
);

canvas.renderAll();

.canvas-container {
  border: 1px solid gray;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script>

<canvas width="600" height="300"></canvas>

Tested with Fabric 1.7.20


问:
Copying array to array using pointer
Like a question below, i have to use the pointer concept to copy array from one to another in mystrcpy2 function, unlike mystrcpy function that does not use the pointer concept. Anyway, I typed my answer, " dest = src;" which seemed to be overly simple but right answer for me. But when I type in the input, like "Hello World", it shows like  "Hello World ???" like strange letters in the back. But when I type short words like "abc", the result is exactly "abc."
Is it simply a matter of computer or did I do something wrong?

I"m also wondering if "while (*src) *dest++=*src++;" works as well?

/*Complete the mystrcpy2() function that copies the null-terminated string pointed by src to the string pointed by dest.
The mystrcpy2() should give the same result with the mystrcpy() that uses an index based array traversal approach.
Note that adding local variables are not allowed in implementing the mystrcpy2().
Write and submit the source code of your "mystrcpy2()" function.
*/

```<code>#include <stdio.h>
void mystrcpy(char dest[], char src[])
{
    int i=0,j=0;
    while (src[i])
        dest[j++] = src[i++];
}
void mystrcpy2(char *dest, char *src)
{
    dest = src;
}

int main(void)
{
    char mystr1[256];
    char mystr2[256];

    gets(mystr1);

mystrcpy(mystr2, mystr1);
puts(mystr2);

    mystrcpy2(mystr2, mystr1);
    puts(mystr2);
    return 0;
}
</code>```

答:
Your implementation of mystrcpy2 does not copy anything. In fact, it does nothing at all. When you execute dest = src, you are copying the memory location pointed to by the src variable, not the data at that location. To actually copy the data, you need to deference the pointer, using '*'. So you would do

```<code>*dest = *src;
</code>```

This copies the data from src to dest. But it only copies one character. You need to increment src and dest and then do this again to copy the next character, and you need to keep doing this until you hit the string terminator i.e. until *src == 0. Here's the full implementation.

```<code>void mystrcpy2(char *dest, char *src)
{
    while (*src != 0) {
        *dest = *src;
        dest++;
        src++;
    }
    // don't forget to add a terminator
    // to the copied string
    *dest = 0;
}
</code>```

And here's the exact same thing in a shorter version.

```<code>void mystrcpy2(char *dest, char *src)
{
    while (*(dest++) = *(src++));
}
</code>```

Title: Copying array to array using pointer

Body:
Like a question below, i have to use the pointer concept to copy array from one to another in mystrcpy2 function, unlike mystrcpy function that does not use the pointer concept. Anyway, I typed my answer, " dest = src;" which seemed to be overly simple but right answer for me. But when I type in the input, like "Hello World", it shows like  "Hello World ???" like strange letters in the back. But when I type short words like "abc", the result is exactly "abc."
Is it simply a matter of computer or did I do something wrong?

I"m also wondering if "while (*src) *dest++=*src++;" works as well?

/*Complete the mystrcpy2() function that copies the null-terminated string pointed by src to the string pointed by dest.
The mystrcpy2() should give the same result with the mystrcpy() that uses an index based array traversal approach.
Note that adding local variables are not allowed in implementing the mystrcpy2().
Write and submit the source code of your "mystrcpy2()" function.
*/

#include <stdio.h>
void mystrcpy(char dest[], char src[])
{
    int i=0,j=0;
    while (src[i])
        dest[j++] = src[i++];
}
void mystrcpy2(char *dest, char *src)
{
    dest = src;
}

int main(void)
{
    char mystr1[256];
    char mystr2[256];

    gets(mystr1);

mystrcpy(mystr2, mystr1);
puts(mystr2);

    mystrcpy2(mystr2, mystr1);
    puts(mystr2);
    return 0;
}

Body:
Your implementation of mystrcpy2 does not copy anything. In fact, it does nothing at all. When you execute dest = src, you are copying the memory location pointed to by the src variable, not the data at that location. To actually copy the data, you need to deference the pointer, using '*'. So you would do

*dest = *src;

This copies the data from src to dest. But it only copies one character. You need to increment src and dest and then do this again to copy the next character, and you need to keep doing this until you hit the string terminator i.e. until *src == 0. Here's the full implementation.

void mystrcpy2(char *dest, char *src)
{
    while (*src != 0) {
        *dest = *src;
        dest++;
        src++;
    }
    // don't forget to add a terminator
    // to the copied string
    *dest = 0;
}

And here's the exact same thing in a shorter version.

void mystrcpy2(char *dest, char *src)
{
    while (*(dest++) = *(src++));
}


问:
Assigning Unique IDs
I have a spreadsheet of tasks, each of which I'd like to assign an ID to (in column A). Each task falls within certain categories (contained in column B), and the ID should relate to this category. For example, if the category is '4', then the first ID should be 04.01, and the second task should be 04.02 etc. Are there any formulas that would work well here and ensure that each ID is unique?

The category is a lookup based on the value in column C, so at the moment my formula is:

```<code>=vlookup(C1,Lookups!A:B,2,false) & "." & text(row(C1:C) - row(C1) + 1, "00")
</code>```

答:
Sample data would have been helpful, but UNTESTED might be worth trying:</p>

```<code>=vlookup(C1,Lookups!A:B,2,0)&"."&text(countif(C$1:C1,C1),"00")
</code>```

Title: Assigning Unique IDs

Body:
I have a spreadsheet of tasks, each of which I'd like to assign an ID to (in column A). Each task falls within certain categories (contained in column B), and the ID should relate to this category. For example, if the category is '4', then the first ID should be 04.01, and the second task should be 04.02 etc. Are there any formulas that would work well here and ensure that each ID is unique?

The category is a lookup based on the value in column C, so at the moment my formula is:

=vlookup(C1,Lookups!A:B,2,false) & "." & text(row(C1:C) - row(C1) + 1, "00")

Body:
Sample data would have been helpful, but UNTESTED might be worth trying:

=vlookup(C1,Lookups!A:B,2,0)&"."&text(countif(C$1:C1,C1),"00")


问:
Laravel - asset() function noy working well
I have a problem with my laravel project.

In my link.blade.php file I have:

```<code><!-- Bootstrap core CSS -->
<link href="{!! asset(css/bootstrap.min.css) !!}" rel="stylesheet">
<link href="{!! asset(css/theme.css) !!}" rel="stylesheet">
<link href="{!! asset(css/bootstrap-reset.css) !!}" rel="stylesheet">
</code>```

and when a run my server I got:

```<code>Use of undefined constant css - assumed 'css' (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php)
</code>```

it's looks like the compiler can't get my css/bootstrap.min.css (located in public dir).

When I've removed this css file it's move to the second one and so on (also js files).

Public dir:
Link

What I should do, please help!!

答:
From your files structure you just need to reference to it directly no need to the asset()function

It would be like this

```<code><link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/theme.css" rel="stylesheet">
<link href="/css/bootstrap-reset.css" rel="stylesheet">
</code>```

Deu certo comigo retirando a função asset

Body:
I have a problem with my laravel project.

In my link.blade.php file I have:

<link href="{!! asset(css/bootstrap.min.css) !!}" rel="stylesheet">
<link href="{!! asset(css/theme.css) !!}" rel="stylesheet">
<link href="{!! asset(css/bootstrap-reset.css) !!}" rel="stylesheet">

and when a run my server I got:

Use of undefined constant css - assumed 'css' (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php)

it's looks like the compiler can't get my css/bootstrap.min.css (located in public dir).

When I've removed this css file it's move to the second one and so on (also js files).

Public dir:
Link

What I should do, please help!!

Body:
From your files structure you just need to reference to it directly no need to the asset()function

It would be like this

<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/theme.css" rel="stylesheet">
<link href="/css/bootstrap-reset.css" rel="stylesheet">

Deu certo comigo retirando a função asset


问:
flow type for react prop as either of two arrays
```<code>type PropTypes = {
  myProp: Array<{a: string}> | Array<{a: number}>
}
</code>```

If I create a compoennt with PropTypes as seen above I always get the following error:

```<code>myProp: *Array<{a: string}>* | Array<{a: number}>,
<<< object type. This type is incompatible with
myProp: Array<{a: string}> | *Array<{a: number}>*,
</code>```

This seems weird since using Array | Array construct generally works for simple function:

```<code>function foo(x: Array<First> | Array<Second>): string {
  return String(x[0]['a']);
}
No errors!
</code>```

EDIT:
MichaelDeBoey's answer pointed me in the right direction and turns out that the problem occurs when we try to map the prop to anything:

```<code>type PropTypes = {
  myProp: Array<{a: string}> | Array<{a: number}>
}

class TestComponent extends Component<PropTypes> {
  render () {
    this.props.myProp.map(prop => prop)
    return 'whatever'
  }
}
</code>```

答:
I ended up using a workaround. Instead of using map i used the iteration with (var i = 0...):
flow.org/try

Body:
type PropTypes = {
  myProp: Array<{a: string}> | Array<{a: number}>
}

If I create a compoennt with PropTypes as seen above I always get the following error:

myProp: *Array<{a: string}>* | Array<{a: number}>,
<<< object type. This type is incompatible with
myProp: Array<{a: string}> | *Array<{a: number}>*,

This seems weird since using Array | Array construct generally works for simple function:

function foo(x: Array<First> | Array<Second>): string {
  return String(x[0]['a']);
}
No errors!

EDIT:
MichaelDeBoey's answer pointed me in the right direction and turns out that the problem occurs when we try to map the prop to anything:

type PropTypes = {
  myProp: Array<{a: string}> | Array<{a: number}>
}

class TestComponent extends Component<PropTypes> {
  render () {
    this.props.myProp.map(prop => prop)
    return 'whatever'
  }
}


问:
Please share iOS 11.1 image file
Updated my iOS to 11.1 and now my Xcode can't run the app. Need to add iOS 11.1 image file to Device Support folder to run my app. But I can't find it online. Please someone who installed 'Xcode 9.1 beta' share it with me. Here is an instruction how to get it:

It should be 11.1 folder.

答:
This repository holds the device support files for the iOS, and it updates regularly.
https://github.com/iGhibli/iOS-DeviceSupport</p>

Title: Please share iOS 11.1 image file


问:
How to import keras from tf.keras in Tensorflow?
```<code>import tensorflow as tf
import tensorflow

from tensorflow import keras
from keras.layers import Dense
</code>```

I am getting the below error

```<code>from keras.layers import Input, Dense
Traceback (most recent call last):

  File "<ipython-input-6-b5da44e251a5>", line 1, in <module>
    from keras.layers import Input, Dense

ModuleNotFoundError: No module named 'keras'
</code>```

How do I solve this?

Note: I am using Tensorflow version 1.4

答:
Use the keras module from tensorflow like this:

import tensorflow as tf

Import classes

from tensorflow.python.keras.layers import Input, Dense

or use directly

dense = tf.keras.layers.Dense(...)

EDIT Tensorflow 2

from tensorflow.keras.layers import Input, Dense

and the rest stays the same.

Body:
import tensorflow as tf
import tensorflow

from tensorflow import keras
from keras.layers import Dense

I am getting the below error

from keras.layers import Input, Dense
Traceback (most recent call last):

  File "<ipython-input-6-b5da44e251a5>", line 1, in <module>
    from keras.layers import Input, Dense

ModuleNotFoundError: No module named 'keras'

How do I solve this?

Note: I am using Tensorflow version 1.4


问:
select single item from a collection : Python
I created a utility function to return the expected single item from an generator expression

```<code>print one(name for name in ('bob','fred') if name=='bob')
</code>```

Is this a good way to go about it?

```<code>def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')
</code>```

答:
Do you mean?

```<code>def one( someGenerator ):
    if len(list(someGenerator)) != 1: raise Exception( "Not a Singleton" )
</code>```

What are you trying to accomplish with all the extra code?

OwnerDisplayName: GHZ

Body:
I created a utility function to return the expected single item from an generator expression

print one(name for name in ('bob','fred') if name=='bob')

Is this a good way to go about it?

def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')

LastEditorDisplayName: nosklo

Body:
Do you mean?

def one( someGenerator ):
    if len(list(someGenerator)) != 1: raise Exception( "Not a Singleton" )

What are you trying to accomplish with all the extra code?


问:
Recommended way to edit dynamic JSON objects?
Is there a input field I can use to let the user edit dynamic JSON (large nested object without fixed schema)?
Or do I need to write my own?</p>

答: You'll have to implement your own component for that</p>


问:
Implementing history tracking in SaveChanges override
I am currently trying to implement history tracking on all of my tables in my app in a generic way by overriding the SaveChanges method and making use of reflection. As a simple case, let's say I have 2 classes/dbsets for my domain objects and a history table for each like the following:

```<code>DbSet<Cat> Cats { get; set; }
DbSet<CatHistory> CatHistories { get; set; }
DbSet<Dog> Dogs { get; set; }
DbSet<DogHistory> DogHistories { get; set; }
</code>```

The CatHistory class looks like the following (DogHistory follows the same scheme):

```<code>public class CatHistory : HistoricalEntity
{
  public int CatId { get; set; }

  public virtual Cat Cat{ get; set; }
}
</code>```

My Goal is when an object is saved, I would like to insert a record in the appropriate history table. I am having trouble overcoming type difference when using reflection. My current attempt is below and I seem to be stuck on the //TODO: line:

```<code>        var properties = entry.CurrentValues.PropertyNames.Where(x => entry.Property(x).IsModified).ToList();

        //get the history entry type from our calculated typeName
        var historyType = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(x => x.Name == historyTypeName);

        if(historyType != null)
        {

          //modified entries
          if (dbSet != null && historyDbSet != null && entry.State == EntityState.Modified)
          {
            var existingEntry = dbSet.Find(entry.Property("Id").CurrentValue);

            //create history record and add entry to table
            var newHistories = GetHistoricalEntities(existingEntry, type, entry);

            var listType = typeof(List<>).MakeGenericType(new[] { historyType });
            var typedHistories = (IList)Activator.CreateInstance(listType);

            //TODO: turn newHistories (type = List<HistoricalEntity>) into specific list type (List<MyObjectHistory>) so I can addrange on appropriate DbSet (MDbSet<MyObjectHistory>)

            historyDbSet.AddRange(newHistories);
          }
        }
</code>```

答:
I will try to explain the way I have implemented in my application.

I have created Models with name ending History for models for which application needs to insert before deleting the record from the original table.

BaseModel.cs

```<code>namespace ProductVersionModel.Model
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    /// <summary>
    /// all common properties of the tables are defined here
    /// </summary>
    public class BaseModel
    {
        /// <summary>
        /// id of the table
        /// </summary>
        [Key]
        public int Id { get; set; }

        /// <summary>
        /// user id of the user who modified last
        /// </summary>
        public string LastModifiedBy { get; set; }

        /// <summary>
        /// last modified time
        /// </summary>
        public DateTime LastModifiedTime { get; set; }

        /// <summary>
        /// record created user id
        /// </summary>
        [Required]
        public string CreatedBy { get; set; }

        /// <summary>
        /// record creation time
        /// </summary>
        public DateTime CreationTime { get; set; }

        /// <summary>
        /// Not mapped to database, only for querying used
        /// </summary>
        [NotMapped]
        public int RowNumber { get; set; }
    }
}
</code>```

Product.cs

```<code>namespace ProductVersionModel.Model
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    /// <summary>
    /// store detals of the product
    /// </summary>
    public class ProductStatus : BaseModel
    {
        /// <summary>
        /// Name of the product
        /// </summary>
        [Required, MaxLength(100)]
        public string Name { get; set; }

        /// <summary>
        /// product version validity start date
        /// </summary>

        public DateTime ValidFrom { get; set; }

        /// <summary>
        /// product version valid till
        /// </summary>
        public DateTime? ValidTill { get; set; }

        /// <summary>
        /// This field used to keep track of history of a product
        /// </summary>
        public int ProductNumber { get; set; }

    }
}
</code>```

HistoryBaseModel.cs

```<code>using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ProductVersionModel.Model.History
{
    public class HistroyBaseModel
    {

        /// <summary>
        /// id of the table
        /// </summary>
        [Key,  DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Id { get; set; }

        public string DeletedBy { get; set; }

        public DateTime? DeletedTime { get; set; }
        /// <summary>
        /// record created user id
        /// </summary>
        [Required]
        public string CreatedBy { get; set; }

        /// <summary>
        /// record creation time
        /// </summary>
        public DateTime CreationTime { get; set; }
    }
}
</code>```

ProductStatusHistory.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using ProductVersionModel.Model.History;

// ReSharper disable once CheckNamespace
namespace ProductVersionModel.Model.History
{
    public class ProductStatusHistory : HistroyBaseModel
    {

        /// <summary>
        /// Name of the product
        /// </summary>
        [MaxLength(100)]
        public string Name { get; set; }

        /// <summary>
        /// product version validity start date
        /// </summary>
        public DateTime ValidFrom { get; set; }

        /// <summary>
        /// product version valid till
        /// </summary>
        public DateTime? ValidTill { get; set; }

        /// <summary>
        /// This field used to keep track of history of a product
        /// </summary>
        public int ProductNumber { get; set; }

    }
}
</code>```

In Delete method of your CrudRepository

```<code>    public virtual int Delete(List<object> ids, string userName)
    {
        try
        {
            foreach (var id in ids)
            {
                var dbObject = _table.Find(id);
                HistroyBaseModel historyRecord = null;
                var modelAssembly = Assembly.Load(nameof(ProductVersionModel));
                var historyType =
                    modelAssembly.GetType(
                        // ReSharper disable once RedundantNameQualifier   - dont remove namespace it is required
                        $"{typeof(ProductVersionModel.Model.History.HistroyBaseModel).Namespace}.{typeof(TModel).Name}History");

                if (historyType != null)
                {
                    var historyObject = Activator.CreateInstance(historyType);

                    historyRecord = MapDeletingObjectToHistoyObject(dbObject, historyObject, userName);

                    DatabaseContext.Entry(historyRecord).State = EntityState.Added;
                }
                DatabaseContext.Entry(dbObject).State = EntityState.Deleted;
            }
            return DatabaseContext.SaveChanges();
        }
        catch (DbUpdateException ex)
        {
            throw HandleDbException(ex);
        }
    }

    protected virtual HistroyBaseModel MapDeletingObjectToHistoyObject(object inputObject, object outputObject, string userName)
    {
        var historyRecord = MapObjectToObject(inputObject, outputObject) as HistroyBaseModel;
        if (historyRecord != null)
        {
            historyRecord.DeletedBy = userName;
            historyRecord.DeletedTime = DateTime.UtcNow;
        }
        return historyRecord;
    }

    protected virtual object MapObjectToObject(object inputObject, object outputObject)
    {
        var inputProperties = inputObject.GetType().GetProperties();
        var outputProperties = outputObject.GetType().GetProperties();//.Where(x => !x.HasAttribute<IgnoreMappingAttribute>());
        outputProperties.ForEach(x =>
        {
            var prop =
                inputProperties.FirstOrDefault(y => y.Name.Equals(x.Name) && y.PropertyType == x.PropertyType);
            if (prop != null)
                x.SetValue(outputObject, prop.GetValue(inputObject));
        });

        return outputObject;
    }
</code>```

Where TModel is the type of the model

```<code>public class CrudRepository<TModel> : DataAccessBase, ICrudRepository<TModel> where TModel : class, new()
public class ProductStatusRepository : CrudRepository<ProductStatus>, IProductStatusRepository
</code>```

You can override methods MapDeletingObjectToHistoyObject and MapObjectToObject in your related repository if you want to map complex entitites like child element list.

Body:
I am currently trying to implement history tracking on all of my tables in my app in a generic way by overriding the SaveChanges method and making use of reflection. As a simple case, let's say I have 2 classes/dbsets for my domain objects and a history table for each like the following:

DbSet<Cat> Cats { get; set; }
DbSet<CatHistory> CatHistories { get; set; }
DbSet<Dog> Dogs { get; set; }
DbSet<DogHistory> DogHistories { get; set; }

The CatHistory class looks like the following (DogHistory follows the same scheme):

public class CatHistory : HistoricalEntity
{
  public int CatId { get; set; }

  public virtual Cat Cat{ get; set; }
}

My Goal is when an object is saved, I would like to insert a record in the appropriate history table. I am having trouble overcoming type difference when using reflection. My current attempt is below and I seem to be stuck on the //TODO: line:

        var properties = entry.CurrentValues.PropertyNames.Where(x => entry.Property(x).IsModified).ToList();

        //get the history entry type from our calculated typeName
        var historyType = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(x => x.Name == historyTypeName);

        if(historyType != null)
        {

          //modified entries
          if (dbSet != null && historyDbSet != null && entry.State == EntityState.Modified)
          {
            var existingEntry = dbSet.Find(entry.Property("Id").CurrentValue);

            //create history record and add entry to table
            var newHistories = GetHistoricalEntities(existingEntry, type, entry);

            var listType = typeof(List<>).MakeGenericType(new[] { historyType });
            var typedHistories = (IList)Activator.CreateInstance(listType);

            //TODO: turn newHistories (type = List<HistoricalEntity>) into specific list type (List<MyObjectHistory>) so I can addrange on appropriate DbSet (MDbSet<MyObjectHistory>)

            historyDbSet.AddRange(newHistories);
          }
        }

Body:
I will try to explain the way I have implemented in my application.

I have created Models with name ending History for models for which application needs to insert before deleting the record from the original table.

BaseModel.cs

namespace ProductVersionModel.Model
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    /// <summary>
    /// all common properties of the tables are defined here
    /// </summary>
    public class BaseModel
    {
        /// <summary>
        /// id of the table
        /// </summary>
        [Key]
        public int Id { get; set; }

        /// <summary>
        /// user id of the user who modified last
        /// </summary>
        public string LastModifiedBy { get; set; }

        /// <summary>
        /// last modified time
        /// </summary>
        public DateTime LastModifiedTime { get; set; }

        /// <summary>
        /// record created user id
        /// </summary>
        [Required]
        public string CreatedBy { get; set; }

        /// <summary>
        /// record creation time
        /// </summary>
        public DateTime CreationTime { get; set; }

        /// <summary>
        /// Not mapped to database, only for querying used
        /// </summary>
        [NotMapped]
        public int RowNumber { get; set; }
    }
}

Product.cs

namespace ProductVersionModel.Model
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    /// <summary>
    /// store detals of the product
    /// </summary>
    public class ProductStatus : BaseModel
    {
        /// <summary>
        /// Name of the product
        /// </summary>
        [Required, MaxLength(100)]
        public string Name { get; set; }

        /// <summary>
        /// product version validity start date
        /// </summary>

        public DateTime ValidFrom { get; set; }

        /// <summary>
        /// product version valid till
        /// </summary>
        public DateTime? ValidTill { get; set; }

        /// <summary>
        /// This field used to keep track of history of a product
        /// </summary>
        public int ProductNumber { get; set; }

    }
}

HistoryBaseModel.cs

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ProductVersionModel.Model.History
{
    public class HistroyBaseModel
    {

        /// <summary>
        /// id of the table
        /// </summary>
        [Key,  DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Id { get; set; }

        public string DeletedBy { get; set; }

        public DateTime? DeletedTime { get; set; }
        /// <summary>
        /// record created user id
        /// </summary>
        [Required]
        public string CreatedBy { get; set; }

        /// <summary>
        /// record creation time
        /// </summary>
        public DateTime CreationTime { get; set; }
    }
}

ProductStatusHistory.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using ProductVersionModel.Model.History;

// ReSharper disable once CheckNamespace
namespace ProductVersionModel.Model.History
{
    public class ProductStatusHistory : HistroyBaseModel
    {

        /// <summary>
        /// Name of the product
        /// </summary>
        [MaxLength(100)]
        public string Name { get; set; }

        /// <summary>
        /// product version validity start date
        /// </summary>
        public DateTime ValidFrom { get; set; }

        /// <summary>
        /// product version valid till
        /// </summary>
        public DateTime? ValidTill { get; set; }

        /// <summary>
        /// This field used to keep track of history of a product
        /// </summary>
        public int ProductNumber { get; set; }

    }
}

In Delete method of your CrudRepository

    public virtual int Delete(List<object> ids, string userName)
    {
        try
        {
            foreach (var id in ids)
            {
                var dbObject = _table.Find(id);
                HistroyBaseModel historyRecord = null;
                var modelAssembly = Assembly.Load(nameof(ProductVersionModel));
                var historyType =
                    modelAssembly.GetType(
                        // ReSharper disable once RedundantNameQualifier   - dont remove namespace it is required
                        $"{typeof(ProductVersionModel.Model.History.HistroyBaseModel).Namespace}.{typeof(TModel).Name}History");

                if (historyType != null)
                {
                    var historyObject = Activator.CreateInstance(historyType);

                    historyRecord = MapDeletingObjectToHistoyObject(dbObject, historyObject, userName);

                    DatabaseContext.Entry(historyRecord).State = EntityState.Added;
                }
                DatabaseContext.Entry(dbObject).State = EntityState.Deleted;
            }
            return DatabaseContext.SaveChanges();
        }
        catch (DbUpdateException ex)
        {
            throw HandleDbException(ex);
        }
    }

    protected virtual HistroyBaseModel MapDeletingObjectToHistoyObject(object inputObject, object outputObject, string userName)
    {
        var historyRecord = MapObjectToObject(inputObject, outputObject) as HistroyBaseModel;
        if (historyRecord != null)
        {
            historyRecord.DeletedBy = userName;
            historyRecord.DeletedTime = DateTime.UtcNow;
        }
        return historyRecord;
    }

    protected virtual object MapObjectToObject(object inputObject, object outputObject)
    {
        var inputProperties = inputObject.GetType().GetProperties();
        var outputProperties = outputObject.GetType().GetProperties();//.Where(x => !x.HasAttribute<IgnoreMappingAttribute>());
        outputProperties.ForEach(x =>
        {
            var prop =
                inputProperties.FirstOrDefault(y => y.Name.Equals(x.Name) && y.PropertyType == x.PropertyType);
            if (prop != null)
                x.SetValue(outputObject, prop.GetValue(inputObject));
        });

        return outputObject;
    }

Where TModel is the type of the model

public class CrudRepository<TModel> : DataAccessBase, ICrudRepository<TModel> where TModel : class, new()
public class ProductStatusRepository : CrudRepository<ProductStatus>, IProductStatusRepository

You can override methods MapDeletingObjectToHistoyObject and MapObjectToObject in your related repository if you want to map complex entitites like child element list.


问:
redefining a function with a template
How do I redefine a call like this via C preprocessor Instructions to snprintf?

```<code>sprintf_s<sizeof(dataFile)>(dataFile, arg2, arg3);
</code>```

I tried this (which doesn't work):

```<code>#define sprintf_s<sizeof(x)>(args...) snprintf<sizeof(x)>(args)
</code>```

Especially because I already need this for calls to sprintf_s without a template in the same files:

```<code>#define sprintf_s(args...) snprintf(args)
</code>```

答: This is simply not supported by the preprocessor. The preprocessor is largely the same as the C preprocessor and C has no notion of templates.</p>

Title: redefining a function with a template

Body:
How do I redefine a call like this via C preprocessor Instructions to snprintf?

sprintf_s<sizeof(dataFile)>(dataFile, arg2, arg3);

I tried this (which doesn't work):

#define sprintf_s<sizeof(x)>(args...) snprintf<sizeof(x)>(args)

Especially because I already need this for calls to sprintf_s without a template in the same files:

#define sprintf_s(args...) snprintf(args)


问:
PHP/HTML - Same size of column containing columns
I need some help to be able to match the same size between the first column and the group of four other columns. Yet I tried with solution MatchHeight and row-eq-height. i tried also with a table. The main problem is that it brake the responsive tool.

I'm using bootstrap 3.3.6

Here is the sample I'm working with:

```<code><div class="container">
  <div class="row">
    <div class="col-xs-6 bg-success">
      <div class="small-box">
        <div class="row">
          <div class="col-lg-12 col-xs-12">
            <h3>Colonne 1</h3>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ultrices massa ligula, a faucibus nisi scelerisque sit amet. Sed cursus, urna eu suscipit egestas, dui dui luctus purus, malesuada pellentesque dolor dolor ac augue. Duis ac rutrum massa,
            </p>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xs-6 bg-warning">
      <div class="small-box">
        <div class="row">
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 2</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 3</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 4</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 5</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

One of the constraint is to have two rows on the right. I can't just make one unique row.

A real thank to who would like to help and to those who are able to.

答:
I do not recommend you keep the same relation to small and extra small screen.
But there it is:

With Table:

```<code><style type="text/css">
  .first-col {
    width: 50%;
  }
  table th{
    width: 12.5%; /* (50/4) */
  }
</style>
<div class="responsive-table">
  <table>
    <thead>
      <tr>
        <th class="first-col"></td>
        <th></th>
        <th></th>
        <th></th>
      </tr>
    </thead>
  </table>
</div>
</code>```

Tableless:

```<code><div class="row">
  <!-- First Column -->
  <div class="col-xs-12 col-sm-6">
    <!-- Content -->
  </div>

  <!-- Small Ones -->
  <div class="col-xs-12 col-sm-6">
    <div class="row">
      <div class="col-xs-12 col-sm-3"></div>
      <div class="col-xs-12 col-sm-3"></div>
      <div class="col-xs-12 col-sm-3"></div>
      <div class="col-xs-12 col-sm-3"></div>
    </div>
  </div>
</div>
</code>```

Note: table-responsive creates a frame which keeps the size relation and maintain your content readable in small screens.

Body:
I need some help to be able to match the same size between the first column and the group of four other columns. Yet I tried with solution MatchHeight and row-eq-height. i tried also with a table. The main problem is that it brake the responsive tool.

I'm using bootstrap 3.3.6

Here is the sample I'm working with:

Colonne 1

              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ultrices massa ligula, a faucibus nisi scelerisque sit amet. Sed cursus, urna eu suscipit egestas, dui dui luctus purus, malesuada pellentesque dolor dolor ac augue. Duis ac rutrum massa,

Colonne 2

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

Colonne 3

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

Colonne 4

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

Colonne 5

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

One of the constraint is to have two rows on the right. I can't just make one unique row.

A real thank to who would like to help and to those who are able to.

Body:
I do not recommend you keep the same relation to small and extra small screen.
But there it is:

With Table:

<style type="text/css">
  .first-col {
    width: 50%;
  }
  table th{
    width: 12.5%; /* (50/4) */
  }
</style>
<div class="responsive-table">
  <table>
    <thead>
      <tr>
        <th class="first-col"></td>
        <th></th>
        <th></th>
        <th></th>
      </tr>
    </thead>
  </table>
</div>

Tableless:

<div class="row">
  <!-- First Column -->
  <div class="col-xs-12 col-sm-6">
    <!-- Content -->
  </div>

  <!-- Small Ones -->
  <div class="col-xs-12 col-sm-6">
    <div class="row">
      <div class="col-xs-12 col-sm-3"></div>
      <div class="col-xs-12 col-sm-3"></div>
      <div class="col-xs-12 col-sm-3"></div>
      <div class="col-xs-12 col-sm-3"></div>
    </div>
  </div>
</div>

Note: table-responsive creates a frame which keeps the size relation and maintain your content readable in small screens.


问:
Is python exception handling more efficient than PHP and/or other languages?
I have it drilled into my head that (at least in PHP) it is badbadmojo to use try... catch blocks for flow control.  What I've learned is to use them only to handle unexpected errors, not determine the logic flow of the program, because catch blocks are expensive.

Now that I'm learning python, I see a lot of exceptions everywhere and the EAFP principle.  Does this mean that python is more efficient at handling exceptions, so I don't need to be as worried about them for flow control, or does the principle still stand?  If not, is PHP the exception from the norm (as compared to other languages), or is Python?

答:
I've done a bit more reading, and have realized one other important thing no one has mentioned yet: in Python, there is no distinction between Errors and Exceptions.  I knew this, but I don't think I had grasped the significance until now.

In PHP, you can wrap $page->GetContent(); in try...catch blocks all you want, but if $page is not an object, your application will still come to a screeching halt with the resulting fatal error.  So in PHP (and any other language where errors cannot be caught), you need a certain level of LBYL.

Python basically says, "that's stupid, I should be able to catch those."  Just try to do what you need to do, and deal with any fallout in the except block.

Here is a great article on exception handling I came across.


问:
How to enqueue scripts in my plugin
I need to use JavaScript (JQuery) within my plugin. The enqueueing should not be inside the themes' function.php. Imagine telling your users "Please to add this line of code in your functions.php etc..."

/plugins/foo-plugin/foo-plugin.php:

```<code><?php
/**
 * Plugin Name: Foo Plugin
 * Plugin URI: foobar.com
 * Description: ___DEV___
 * Version: 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) exit;

function Foo_Plugin() {
    return Foo_Plugin::instance();
} // End Foo_Plugin()

add_action( 'plugins_loaded', 'Foo_Plugin' );

/**
 * Load Scrips
 */
function enqueue_js() {
    // JS
  wp_enqueue_script( 'foo', './assets/js/foo.js', false );
}

add_action('wp_enqueue_scripts', 'enqueue_js');

[...]
</code>```

I've followed this but I'm not getting my output:

```<code>//foo.js:
$(document).ready(function(){
  console.log("foo is ready")
})
</code>```

I have deactivated/reactivated the plugin and nothing. How to use JS/CSS in my plugin? As you've guested, it's my first time creating one ;)

Path to JS:

```<code>/plugins/foo-plugin/assets/js/foo.js
</code>```

答:
In the admin section, use the admin_enqueue_scripts action hook.

```<code>function enqueue_js() {
  wp_enqueue_script( 'foo', './assets/js/foo.js');
}

add_action('admin_enqueue_scripts', 'enqueue_js');
</code>```

Also, don't put that false in there. The default should be an empty array if there are no dependencies.

Title: How to enqueue scripts in my plugin

Body:
I need to use JavaScript (JQuery) within my plugin. The enqueueing should not be inside the themes' function.php. Imagine telling your users "Please to add this line of code in your functions.php etc..."

/plugins/foo-plugin/foo-plugin.php:

<?php
/**
 * Plugin Name: Foo Plugin
 * Plugin URI: foobar.com
 * Description: ___DEV___
 * Version: 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) exit;

function Foo_Plugin() {
    return Foo_Plugin::instance();
} // End Foo_Plugin()

add_action( 'plugins_loaded', 'Foo_Plugin' );

/**
 * Load Scrips
 */
function enqueue_js() {
    // JS
  wp_enqueue_script( 'foo', './assets/js/foo.js', false );
}

add_action('wp_enqueue_scripts', 'enqueue_js');

[...]

I've followed this but I'm not getting my output:

//foo.js:
$(document).ready(function(){
  console.log("foo is ready")
})

I have deactivated/reactivated the plugin and nothing. How to use JS/CSS in my plugin? As you've guested, it's my first time creating one ;)

Path to JS:

/plugins/foo-plugin/assets/js/foo.js

Body:
In the admin section, use the admin_enqueue_scripts action hook.

function enqueue_js() {
  wp_enqueue_script( 'foo', './assets/js/foo.js');
}

add_action('admin_enqueue_scripts', 'enqueue_js');

Also, don't put that false in there. The default should be an empty array if there are no dependencies.


问:
Python example of Joe's Erlang websocket example
I've just been working through the erlang websockets example from Joe Armstrong's blog I'm still quite new to erlang so I decided to write a simple server in python that would help teach me about websockets (and hopefully some erlang by interpreting joe's code). I'm having two issues:

1) Data I receive from the page includes a 'ÿ' as the last char. This doesn't appear in the erlang version and I can't work out where it's coming from Fixed - This was because the strings where encoded in utf-8 and I wasn't decoding them

2) I seem to be sending data from the server (through the websocket) - which can be confirmed by looking at how many bytes client.send() makes. But nothing is appearing on the page. Fixed, I wasn't encoding the string correctly

I've put all the code here. Here's my python version incase i'm missing anything obvious

```<code>import threading
import socket

def start_server():
    tick = 0
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 1234))
    sock.listen(100)
    while True:
        print 'listening...'
        csock, address = sock.accept()
        tick+=1
        print 'connection!'
        handshake(csock, tick)
        print 'handshaken'
        while True:
            interact(csock, tick)
            tick+=1

def handshake(client, tick):
    our_handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"+"Upgrade:     WebSocket\r\n"+"Connection: Upgrade\r\n"+"WebSocket-Origin:     http://localhost:8888\r\n"+"WebSocket-Location: "+" ws://localhost:1234/websession\r\n\r\n"
    shake = client.recv(255)
    print shake
    client.send(our_handshake)

def interact(client, tick):
    data = client.recv(255)
    print 'got:%s' %(data)
    client.send("clock ! tick%d\r" % (tick))
    client.send("out ! recv\r")

if __name__ == '__main__':
    start_server()
</code>```

For those who haven't run through joe's example but still want to help, you just need to serve up interact.html through a web server and then start your server (The code assumes the webserver is running on localhost:8888)

答: Eventlet has websocket support built in and stargate is a package for using websockets with the pyramid web framework: http://boothead.github.com/stargate/</p>

Body:
I've just been working through the erlang websockets example from Joe Armstrong's blog I'm still quite new to erlang so I decided to write a simple server in python that would help teach me about websockets (and hopefully some erlang by interpreting joe's code). I'm having two issues:

1) Data I receive from the page includes a 'ÿ' as the last char. This doesn't appear in the erlang version and I can't work out where it's coming from Fixed - This was because the strings where encoded in utf-8 and I wasn't decoding them

2) I seem to be sending data from the server (through the websocket) - which can be confirmed by looking at how many bytes client.send() makes. But nothing is appearing on the page. Fixed, I wasn't encoding the string correctly

I've put all the code here. Here's my python version incase i'm missing anything obvious

import threading
import socket

def start_server():
    tick = 0
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 1234))
    sock.listen(100)
    while True:
        print 'listening...'
        csock, address = sock.accept()
        tick+=1
        print 'connection!'
        handshake(csock, tick)
        print 'handshaken'
        while True:
            interact(csock, tick)
            tick+=1

def handshake(client, tick):
    our_handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"+"Upgrade:     WebSocket\r\n"+"Connection: Upgrade\r\n"+"WebSocket-Origin:     http://localhost:8888\r\n"+"WebSocket-Location: "+" ws://localhost:1234/websession\r\n\r\n"
    shake = client.recv(255)
    print shake
    client.send(our_handshake)

def interact(client, tick):
    data = client.recv(255)
    print 'got:%s' %(data)
    client.send("clock ! tick%d\r" % (tick))
    client.send("out ! recv\r")

if __name__ == '__main__':
    start_server()

For those who haven't run through joe's example but still want to help, you just need to serve up interact.html through a web server and then start your server (The code assumes the webserver is running on localhost:8888)


问:
Android app is crashing on AuthUI.getInstance() after upgrading
My app was working fine. I upgraded the Android Studio to 3.0 and the libraries as below.

```<code>compile 'com.google.firebase:firebase-core:11.4.2'
compile 'com.firebaseui:firebase-ui-auth:3.1.0'
</code>```

But now the app started crashing on this statement. Not able to find the issue.

```<code> startActivityForResult(
                        AuthUI.getInstance()
                                .createSignInIntentBuilder()
                                //          .setTheme(R.style.GreenTheme)
                                .setAvailableProviders(Arrays.asList(
                                        new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                                        new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()
                                ))
                                .setIsSmartLockEnabled(false)
                                .setLogo(R.drawable.web_hi_res_178)
                                .build(),
                        RC_SIGN_IN);
</code>```

Logcat -

```<code> No pending exception expected: java.lang.NoClassDefFoundError: com.firebase.ui.auth.provider.TwitterProvider
   at java.lang.Class dalvik.system.DexFile.defineClassNative(java.lang.String, java.lang.ClassLoader, java.lang.Object) (DexFile.java:-2)
   at java.lang.Class dalvik.system.DexFile.defineClass(java.lang.String, java.lang.ClassLoader, java.lang.Object, java.util.List) (DexFile.java:226)
   at java.lang.Class dalvik.system.DexFile.loadClassBinaryName(java.lang.String, java.lang.ClassLoader, java.util.List) (DexFile.java:219)
   at java.lang.Class dalvik.system.DexPathList.findClass(java.lang.String, java.util.List) (DexPathList.java:338)
   at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:54)
   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:511)
   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:469)
   at com.firebase.ui.auth.AuthUI com.firebase.ui.auth.AuthUI.getInstance() (AuthUI.java:160)
   at void com.xxxxxxx.xxxxxxx.LandingPage.onCreate(android.os.Bundle) (LandingPage.java:82)
   at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:6904)
   at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1136)
   at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:3266)
   at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:3415)
   at void android.app.ActivityThread.access$1100(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:229)
   at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1821)
   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:102)
   at void android.os.Looper.loop() (Looper.java:148)
   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:7325)
   at java.lang.Object java.lang.reflect.Method.invoke!(java.lang.Object, java.lang.Object[]) (Method.java:-2)
   at void com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run() (ZygoteInit.java:1230)
   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1120)

 Runtime aborting...

 Fatal signal 6 (SIGABRT), code -6 in tid 23572
</code>```

答:
I had the same issue and after solving the Twitter error, one related with Facebook came up!
Please add the following dependencies on your app level build.gradle file:

```<code>dependencies {
compile 'com.twitter.sdk.android:twitter-core:3.1.1'
compile 'com.facebook.android:facebook-login:4.28.0'
}
</code>```

That should do it!

ps:
I used the exact module for each to avoid unnecessary DEX library clutter.

In case the error persists you may need to add the entire Twitter and Facebook SDK's by using:

```<code>// Facebook Android SDK (everything)
compile 'com.facebook.android:facebook-android-sdk:4.28.0'
// Include all the Twitter APIs
compile 'com.twitter.sdk.android:twitter:3.1.1'
</code>```

Body:
My app was working fine. I upgraded the Android Studio to 3.0 and the libraries as below.

compile 'com.google.firebase:firebase-core:11.4.2'
compile 'com.firebaseui:firebase-ui-auth:3.1.0'

But now the app started crashing on this statement. Not able to find the issue.

 startActivityForResult(
                        AuthUI.getInstance()
                                .createSignInIntentBuilder()
                                //          .setTheme(R.style.GreenTheme)
                                .setAvailableProviders(Arrays.asList(
                                        new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                                        new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()
                                ))
                                .setIsSmartLockEnabled(false)
                                .setLogo(R.drawable.web_hi_res_178)
                                .build(),
                        RC_SIGN_IN);

Logcat -

 No pending exception expected: java.lang.NoClassDefFoundError: com.firebase.ui.auth.provider.TwitterProvider
   at java.lang.Class dalvik.system.DexFile.defineClassNative(java.lang.String, java.lang.ClassLoader, java.lang.Object) (DexFile.java:-2)
   at java.lang.Class dalvik.system.DexFile.defineClass(java.lang.String, java.lang.ClassLoader, java.lang.Object, java.util.List) (DexFile.java:226)
   at java.lang.Class dalvik.system.DexFile.loadClassBinaryName(java.lang.String, java.lang.ClassLoader, java.util.List) (DexFile.java:219)
   at java.lang.Class dalvik.system.DexPathList.findClass(java.lang.String, java.util.List) (DexPathList.java:338)
   at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:54)
   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:511)
   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:469)
   at com.firebase.ui.auth.AuthUI com.firebase.ui.auth.AuthUI.getInstance() (AuthUI.java:160)
   at void com.xxxxxxx.xxxxxxx.LandingPage.onCreate(android.os.Bundle) (LandingPage.java:82)
   at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:6904)
   at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1136)
   at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:3266)
   at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:3415)
   at void android.app.ActivityThread.access$1100(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:229)
   at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1821)
   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:102)
   at void android.os.Looper.loop() (Looper.java:148)
   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:7325)
   at java.lang.Object java.lang.reflect.Method.invoke!(java.lang.Object, java.lang.Object[]) (Method.java:-2)
   at void com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run() (ZygoteInit.java:1230)
   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1120)

 Runtime aborting...

 Fatal signal 6 (SIGABRT), code -6 in tid 23572

Body:
I had the same issue and after solving the Twitter error, one related with Facebook came up!
Please add the following dependencies on your app level build.gradle file:

dependencies {
compile 'com.twitter.sdk.android:twitter-core:3.1.1'
compile 'com.facebook.android:facebook-login:4.28.0'
}

That should do it!

ps:
I used the exact module for each to avoid unnecessary DEX library clutter.

In case the error persists you may need to add the entire Twitter and Facebook SDK's by using:

// Facebook Android SDK (everything)
compile 'com.facebook.android:facebook-android-sdk:4.28.0'
// Include all the Twitter APIs
compile 'com.twitter.sdk.android:twitter:3.1.1'


问:
insert data in dynamic table
i am usginf this but getting error can u provide a solution.</p>

```<code>DECLARE @TableName VARCHAR(500);
SET @TableName = N'CREATE TABLE businessmaster_'+
                 CONVERT(VARCHAR(10),GetDate()-1,112)+
                 N' ( contentid int,Businessname varchar(50) )';
print @TableName

  declare  @sql varchar(100)

  SET @sql = 'INSERT INTO'+ @TableName+' (contentid,Businessname) SELECT top 10 contentid,Businessname FROM businessmaster';
EXEC (@sql);
</code>```

答:
You did not create the table, it should look like this</p>

```<code>DECLARE @TableName VARCHAR(500);

SET @TableName = N'businessmaster_'+CONVERT(VARCHAR(10),GetDate()-1,112);

EXEC (N'CREATE TABLE '+@TableName +' ( contentid int,Businessname varchar(50) )')

print @TableName
declare  @sql varchar(100)

SET @sql = 'INSERT INTO '+ @TableName+' (contentid,Businessname) SELECT top 10 contentid,Businessname FROM businessmaster';
EXEC (@sql)
</code>```

Title: insert data in dynamic table

Body:
i am usginf this but getting error can u provide a solution.

DECLARE @TableName VARCHAR(500);
SET @TableName = N'CREATE TABLE businessmaster_'+
                 CONVERT(VARCHAR(10),GetDate()-1,112)+
                 N' ( contentid int,Businessname varchar(50) )';
print @TableName

  declare  @sql varchar(100)

  SET @sql = 'INSERT INTO'+ @TableName+' (contentid,Businessname) SELECT top 10 contentid,Businessname FROM businessmaster';
EXEC (@sql);

Body:
You did not create the table, it should look like this

DECLARE @TableName VARCHAR(500);

SET @TableName = N'businessmaster_'+CONVERT(VARCHAR(10),GetDate()-1,112);

EXEC (N'CREATE TABLE '+@TableName +' ( contentid int,Businessname varchar(50) )')

print @TableName
declare  @sql varchar(100)

SET @sql = 'INSERT INTO '+ @TableName+' (contentid,Businessname) SELECT top 10 contentid,Businessname FROM businessmaster';
EXEC (@sql)