问:
Flare ItemVisualisation
Using the latest Flare build originally built by prefuse, I am trying to get an indent field like the one in Layouts seen here. I am working with a list of objects that I pull from Google Firebase. While I can put them on a graph just fine and compare one and other values I can't find instructions on the different layouts. I am about to study the docs but I wanted to know if there was anything else out there I could reference.

Edit:
http://flare.prefuse.org/api/flare/vis/operator/layout/Layout.html I have found the general layouts here. However I only am able to show 1 or two circles unless I do AxisLayout.

For reference, my data pulled from firebase is something like this.

An array of objects.
Each object has properties name, sales, date, active and such.

I want it to act like the example above and show the item name in each circle. Then when the user clicks the circle he is able to show the properties of the item.

Edit: I was able to find an article on it, but after hours of constructing my data around his set format, I am not able to mock it entirely.
http://simon.oconnorlamb.com/ria/2012/03/visualising-data-with-flare/

Edit: To go into detail:

When I pull from my json list from Google Firebase I parse it so that it puts the items in referencable categories. All of which go into an array to mock the tutorial I linked above. I am trying to mock the structure as close as possible.

```<code>private function handleDataRead(e:DatabaseEvent):void
    {
        var trueDataArray:Array = new Array();

        //Extract manufacturers.
        var manufacturers:Vector.<String> = new Vector.<String>();
        for each (var item:Object in e.data)
        {
            if (manufacturers.indexOf(item.Manufacturer) == -1)
            {
                manufacturers.push(item.Manufacturer);
                //Example:  {type:'Manufacturer',id:'0',name:'Company A'}
                trueDataArray.push( {type:'manufacturer',
                id:manufacturers.indexOf(item.Manufacturer).toString(),
                name:item.Manufacturer});
            }
        }

        //Extract Item Name
        var itemNames:Vector.<String> = new Vector.<String>();
        for each (var item:Object in e.data)
        {
            if (itemNames.indexOf(item.ItemName) == -1)
            {
                itemNames.push(item.ItemName);
                var idValue:String = new String(itemNames.indexOf(item.ItemName) + (manufacturers.length - 1) +1);
                trueDataArray.push( {type:'item',
                id:idValue,
                name:item.ItemName,
                manufacturer:manufacturers.indexOf(item.Manufacturer).toString()} );
            }
        }

        //Extract property 1
        var mlCount:Vector.<int> = new Vector.<int>();
        for each (var item:Object in e.data)
        {
            if (item.hasOwnProperty("ML"))
            {
                if (mlCount.indexOf(item.ML) == -1)
                {
                    mlCount.push(item.ML);
                    var idValue:String = new String(mlCount.indexOf(item.ML) + (itemNames.length - 1) + (manufacturers.length - 1) +1);
                    trueDataArray.push({type:'mL',
                    id:idValue,
                    name:(item.ML as int).toString(),
                    item:itemNames.indexOf(item.ItemName).toString()});
                }
            }
        }

        //Extract another property
        var mgCount:Vector.<int> = new Vector.<int>();
        for each (var item:Object in e.data)
        {
            if (item.hasOwnProperty("MG"))
            {
                if (mgCount.indexOf(item.MG) == -1)
                {
                    mgCount.push(item.MG);
                    var idValue:String = new String(mgCount.indexOf(item.MG) + mlCount.indexOf(item.ML) + (itemNames.length - 1) + (manufacturers.length - 1) +1);
                    trueDataArray.push({type:'mG',
                    id:idValue,
                    name:(item.MG as int).toString(),
                    mL:mlCount.indexOf(item.ML).toString()});
                }
            }

        }
</code>```

The result looks like this.

```<code>[
   {
      "name":"Company A",
      "type":"manufacturer",
      "id":"0"
   },
   {
      "name":"Company B",
      "type":"manufacturer",
      "id":"1"
   },
   {
      "name":"Company C",
      "type":"manufacturer",
      "id":"2"
   },
   {
      "name":"Company D",
      "type":"manufacturer",
      "id":"3"
   },
   {
      "name":"Company E",
      "type":"manufacturer",
      "id":"4"
   },
   {
      "type":"manufacturer",
      "id":"5"
   },
... //So on
   {
      "manufacturer":"0",
      "name":"Item Name 1",
      "type":"item",
      "id":"18"
   },
   {
      "manufacturer":"0",
      "name":"Item Name 2",
      "type":"item",
      "id":"19"
   },
   {
      "manufacturer":"0",
      "name":"Item Name 3",
      "type":"item",
      "id":"20"
   },
   {
      "manufacturer":"0",
      "name":"Item Name 4",
      "type":"item",
      "id":"21"
 ...//So on
   {
      "name":"60",
      "item":"0",
      "type":"mL",
      "id":"195"
   },
   {
      "name":"100",
      "item":"5",
      "type":"mL",
      "id":"196"
   },
   {
      "name":"120",
      "item":"36",
      "type":"mL",
      "id":"197"
   },
   {
      "name":"30",
      "item":"100",
      "type":"mL",
      "id":"198"
   }
   ...//and so forth
]
</code>```

When I pass this to my function to create the nodes and edges (that I again based off the blog in the link above)

```<code>    public function buildTree(arr:Array):Data
    {
        var d:Data = new Data(true);
        //Keyed lookup for easy edge addition in step 2
        var nodeLookup:Object = {};
        var row:Object;
        var ns:NodeSprite;
        //Step 1: Add all rows of data;
        for each(row in arr){
            ns = d.addNode(row);
            nodeLookup[row.id] = ns;
        }
        //Step 2: Add edges
        for each(ns in d.nodes){
            if(ns.data.hasOwnProperty('manufacturer')){
                d.addEdgeFor(nodeLookup[ns.data.manufacturer],ns);
            }
            else if(ns.data.hasOwnProperty('item')){
                d.addEdgeFor(nodeLookup[ns.data.item],ns);
            }
            else if(ns.data.hasOwnProperty('mL')){
                d.addEdgeFor(nodeLookup[ns.data.mL],ns);
            }
        }
        return d;
    }
</code>```

and construct it

```<code>        data = buildTree(trueDataArray);
        sourceTree = new ItemVisualisation(data);

        sourceTree.bounds = new Rectangle(10, 10, 550, 550);
        sourceTree.x = 20;
        sourceTree.y = 20;
        addChild(sourceTree);

        sourceTree.operators.add(new IndentedTreeLayout());
        sourceTree.operators.add(new ShapeEncoder("data.type"));
        sourceTree.operators.add(new ColorEncoder("data.type", Data.NODES, "lineColor", ScaleType.CATEGORIES));
        sourceTree.data.nodes.setProperties({fillColor:0, lineWidth:2});
        sourceTree.update();
</code>```

I get the following..

I almost have this down but I don't know what I am doing wrong. Everything seems to be as it should in relation.

Edit: It seems that the nodes may be linking properly with each other however this is not the layout I desire. I cannot get any other layouts to work either.

答:
```<code>trueDataArray.push({type:'root', id:0, name:'rootname'});
</code>```

I was able to solve this problem by binding everything to 1 node. I was having some trouble listing anything beyond two steps but that is beyond the requirement of my project.

Title: Flare ItemVisualisation

Body:
Using the latest Flare build originally built by prefuse, I am trying to get an indent field like the one in Layouts seen here. I am working with a list of objects that I pull from Google Firebase. While I can put them on a graph just fine and compare one and other values I can't find instructions on the different layouts. I am about to study the docs but I wanted to know if there was anything else out there I could reference.

Edit:
http://flare.prefuse.org/api/flare/vis/operator/layout/Layout.html I have found the general layouts here. However I only am able to show 1 or two circles unless I do AxisLayout.

For reference, my data pulled from firebase is something like this.

An array of objects.
Each object has properties name, sales, date, active and such.

I want it to act like the example above and show the item name in each circle. Then when the user clicks the circle he is able to show the properties of the item.

Edit: I was able to find an article on it, but after hours of constructing my data around his set format, I am not able to mock it entirely.
http://simon.oconnorlamb.com/ria/2012/03/visualising-data-with-flare/

Edit: To go into detail:

When I pull from my json list from Google Firebase I parse it so that it puts the items in referencable categories. All of which go into an array to mock the tutorial I linked above. I am trying to mock the structure as close as possible.

private function handleDataRead(e:DatabaseEvent):void
    {
        var trueDataArray:Array = new Array();

        //Extract manufacturers.
        var manufacturers:Vector.<String> = new Vector.<String>();
        for each (var item:Object in e.data)
        {
            if (manufacturers.indexOf(item.Manufacturer) == -1)
            {
                manufacturers.push(item.Manufacturer);
                //Example:  {type:'Manufacturer',id:'0',name:'Company A'}
                trueDataArray.push( {type:'manufacturer',
                id:manufacturers.indexOf(item.Manufacturer).toString(),
                name:item.Manufacturer});
            }
        }

        //Extract Item Name
        var itemNames:Vector.<String> = new Vector.<String>();
        for each (var item:Object in e.data)
        {
            if (itemNames.indexOf(item.ItemName) == -1)
            {
                itemNames.push(item.ItemName);
                var idValue:String = new String(itemNames.indexOf(item.ItemName) + (manufacturers.length - 1) +1);
                trueDataArray.push( {type:'item',
                id:idValue,
                name:item.ItemName,
                manufacturer:manufacturers.indexOf(item.Manufacturer).toString()} );
            }
        }

        //Extract property 1
        var mlCount:Vector.<int> = new Vector.<int>();
        for each (var item:Object in e.data)
        {
            if (item.hasOwnProperty("ML"))
            {
                if (mlCount.indexOf(item.ML) == -1)
                {
                    mlCount.push(item.ML);
                    var idValue:String = new String(mlCount.indexOf(item.ML) + (itemNames.length - 1) + (manufacturers.length - 1) +1);
                    trueDataArray.push({type:'mL',
                    id:idValue,
                    name:(item.ML as int).toString(),
                    item:itemNames.indexOf(item.ItemName).toString()});
                }
            }
        }

        //Extract another property
        var mgCount:Vector.<int> = new Vector.<int>();
        for each (var item:Object in e.data)
        {
            if (item.hasOwnProperty("MG"))
            {
                if (mgCount.indexOf(item.MG) == -1)
                {
                    mgCount.push(item.MG);
                    var idValue:String = new String(mgCount.indexOf(item.MG) + mlCount.indexOf(item.ML) + (itemNames.length - 1) + (manufacturers.length - 1) +1);
                    trueDataArray.push({type:'mG',
                    id:idValue,
                    name:(item.MG as int).toString(),
                    mL:mlCount.indexOf(item.ML).toString()});
                }
            }

        }

The result looks like this.

[
   {
      "name":"Company A",
      "type":"manufacturer",
      "id":"0"
   },
   {
      "name":"Company B",
      "type":"manufacturer",
      "id":"1"
   },
   {
      "name":"Company C",
      "type":"manufacturer",
      "id":"2"
   },
   {
      "name":"Company D",
      "type":"manufacturer",
      "id":"3"
   },
   {
      "name":"Company E",
      "type":"manufacturer",
      "id":"4"
   },
   {
      "type":"manufacturer",
      "id":"5"
   },
... //So on
   {
      "manufacturer":"0",
      "name":"Item Name 1",
      "type":"item",
      "id":"18"
   },
   {
      "manufacturer":"0",
      "name":"Item Name 2",
      "type":"item",
      "id":"19"
   },
   {
      "manufacturer":"0",
      "name":"Item Name 3",
      "type":"item",
      "id":"20"
   },
   {
      "manufacturer":"0",
      "name":"Item Name 4",
      "type":"item",
      "id":"21"
 ...//So on
   {
      "name":"60",
      "item":"0",
      "type":"mL",
      "id":"195"
   },
   {
      "name":"100",
      "item":"5",
      "type":"mL",
      "id":"196"
   },
   {
      "name":"120",
      "item":"36",
      "type":"mL",
      "id":"197"
   },
   {
      "name":"30",
      "item":"100",
      "type":"mL",
      "id":"198"
   }
   ...//and so forth
]

When I pass this to my function to create the nodes and edges (that I again based off the blog in the link above)

    public function buildTree(arr:Array):Data
    {
        var d:Data = new Data(true);
        //Keyed lookup for easy edge addition in step 2
        var nodeLookup:Object = {};
        var row:Object;
        var ns:NodeSprite;
        //Step 1: Add all rows of data;
        for each(row in arr){
            ns = d.addNode(row);
            nodeLookup[row.id] = ns;
        }
        //Step 2: Add edges
        for each(ns in d.nodes){
            if(ns.data.hasOwnProperty('manufacturer')){
                d.addEdgeFor(nodeLookup[ns.data.manufacturer],ns);
            }
            else if(ns.data.hasOwnProperty('item')){
                d.addEdgeFor(nodeLookup[ns.data.item],ns);
            }
            else if(ns.data.hasOwnProperty('mL')){
                d.addEdgeFor(nodeLookup[ns.data.mL],ns);
            }
        }
        return d;
    }

and construct it

        data = buildTree(trueDataArray);
        sourceTree = new ItemVisualisation(data);

        sourceTree.bounds = new Rectangle(10, 10, 550, 550);
        sourceTree.x = 20;
        sourceTree.y = 20;
        addChild(sourceTree);

        sourceTree.operators.add(new IndentedTreeLayout());
        sourceTree.operators.add(new ShapeEncoder("data.type"));
        sourceTree.operators.add(new ColorEncoder("data.type", Data.NODES, "lineColor", ScaleType.CATEGORIES));
        sourceTree.data.nodes.setProperties({fillColor:0, lineWidth:2});
        sourceTree.update();

I get the following..

I almost have this down but I don't know what I am doing wrong. Everything seems to be as it should in relation.

Edit: It seems that the nodes may be linking properly with each other however this is not the layout I desire. I cannot get any other layouts to work either.

Body:
trueDataArray.push({type:'root', id:0, name:'rootname'});

I was able to solve this problem by binding everything to 1 node. I was having some trouble listing anything beyond two steps but that is beyond the requirement of my project.


来源: stackexchange

问:
How to perform binary "or" operations on column of Data Frame in Spark
Let me explain you the scenario:

I am creating one mask value. i.e.

```<code>val Date = 20170501
val day = Date.toString.substring(6, 8)
val mask = pow(2, day.toInt -1)
</code>```

Then next I am creating dataframe which create additional column using withColumn i.e.

```<code>val t1 = df.withColumn("C1", when($"a1" > 0 , $"C1" | mask.toInt).otherwise($"C1"))
</code>```

but when I am performing | operation with Dataframe column it is giving me error as "value | is not a member of org.apache.spark.sql.ColumnName".

early help will be appreciated.

Thanks in advance.

答:
You can use bitwiseOR which is implemented by Column :

```<code>val t1 = df.withColumn("C1", when($"a1" > 0 , $"C1".bitwiseOR(mask.toInt)).otherwise($"C1"))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let me explain you the scenario:

I am creating one mask value. i.e.

val Date = 20170501
val day = Date.toString.substring(6, 8)
val mask = pow(2, day.toInt -1)

Then next I am creating dataframe which create additional column using withColumn i.e.

val t1 = df.withColumn("C1", when($"a1" > 0 , $"C1" | mask.toInt).otherwise($"C1"))

but when I am performing | operation with Dataframe column it is giving me error as "value | is not a member of org.apache.spark.sql.ColumnName".

early help will be appreciated.

Thanks in advance.

Body:
You can use bitwiseOR which is implemented by Column :

val t1 = df.withColumn("C1", when($"a1" > 0 , $"C1".bitwiseOR(mask.toInt)).otherwise($"C1"))

ContentLicense: CC BY-SA 4.0


问:
How can I get Symfony request context to use the REQUEST_URI from a IIS rewrite rule?
I setup a Reverse Proxy Rewrite Rule in IIS7 for requests to Symfony.
It matches the pattern and passes the correct request details so from a technical perspective it is working, but Symfony doesn't seem to use the correct info or rather the info I want it to use.

Breakpointing in app.php to see what symfony receives from the other server in the $_SERVER details the relevant parameters for this are:

HTTP_X_ORIGINAL_URL="/foo/bar/foo/someCall/123456789"

REQUEST_URI="/bar/foo/someCall/123456789" (what was matched by the
pattern in the rewrite rule)

A route has been setup for /bar/foo/someCall/{id}, but the request context only sets the pathInfo as /foo/bar/foo/someCall/{id}, which results in a "No route exists ..." error.

I need the request context (possibly route listener etc) to use what is in REQUEST_URI. How would one be able to do so, if at all possible?

答:
IIS generates the header HTTP_X_ORIGINAL_URL as part of the rewrite and unfortunately Symfony will overwrite the REQUEST_URI due to the condition for if ($this->headers->has('X_ORIGINAL_URL')) in the prepareRequestUri() funtion.

Leading off from what Pierre spoke of in his answer he assisted in figuring out how to get around the problem.

We had to adapt our nginx conf file to 'overwrite' the HTTP_X_ORIGINAL_URL to be empty so the condition was not met and the REQUEST_URI is not incorrectly overwritten.

```<code>location ~^\/{url}\/? {
    ...
    proxy_set_header X-ORIGINAL-URL "";
    ...
}
</code>```

Body:
IIS generates the header HTTP_X_ORIGINAL_URL as part of the rewrite and unfortunately Symfony will overwrite the REQUEST_URI due to the condition for if ($this->headers->has('X_ORIGINAL_URL')) in the prepareRequestUri() funtion.

Leading off from what Pierre spoke of in his answer he assisted in figuring out how to get around the problem.

We had to adapt our nginx conf file to 'overwrite' the HTTP_X_ORIGINAL_URL to be empty so the condition was not met and the REQUEST_URI is not incorrectly overwritten.

location ~^\/{url}\/? {
    ...
    proxy_set_header X-ORIGINAL-URL "";
    ...
}


问:
Finding Duplicate record on phpmyadmin Server type: MariaDB
I have a table of students and I wish to display a list of all occurances where:

A student's name is shared with at least one other student

The frequency of each duplication

My query is as follows:

```<code>SELECT
    name
    , COUNT(*) AS frequency
FROM
    student
GROUP BY
    name
HAVING
    COUNT(*) > 1
</code>```

My results are as follows:

```<code>1054 - Unknown column 'gt' in 'having clause'
</code>```

Has anyone else experienced this error?

I don't understand it.

答:
I'm not a big fan of HAVING.
I always do something like</p>

```<code>SELECT x.* FROM
{
SELECT name, COUNT(*) AS n
GROUP BY name
} x
WHERE x.n > 1
</code>```

Body:
I have a table of students and I wish to display a list of all occurances where:

A student's name is shared with at least one other student

The frequency of each duplication

My query is as follows:

SELECT
    name
    , COUNT(*) AS frequency
FROM
    student
GROUP BY
    name
HAVING
    COUNT(*) > 1

My results are as follows:

1054 - Unknown column 'gt' in 'having clause'

Has anyone else experienced this error?

I don't understand it.

Body:
I'm not a big fan of HAVING.
I always do something like

SELECT x.* FROM
{
SELECT name, COUNT(*) AS n
GROUP BY name
} x
WHERE x.n > 1


问:
“this” keyword doesn’t seem to work
I am trying to understand how the this keyword works in JavaScript and I made this script:

```<code>function click(){
    this.innerHTML="changed";
}
</code>```

Used in this HTML:

```<code><button id="clicker" onclick="click()" >Click me</button>
</code>```

But it doesn't work, can anyone explain why?

答:
this exists only in the scope of the onclick event itself. It is not bound automatically to other functions.

Pass it on like this:

```<code>function click(element){
element.innerHTML="changed";
}
</code>```

and the html:

```<code><button id="clicker" onclick="click(this)" >Click me</button>
</code>```

Title: “this” keyword doesn’t seem to work

Body:
I am trying to understand how the this keyword works in JavaScript and I made this script:

function click(){
    this.innerHTML="changed";
}

Used in this HTML:

<button id="clicker" onclick="click()" >Click me</button>

But it doesn't work, can anyone explain why?

Body:
this exists only in the scope of the onclick event itself. It is not bound automatically to other functions.

Pass it on like this:

function click(element){
element.innerHTML="changed";
}

and the html:

<button id="clicker" onclick="click(this)" >Click me</button>

ContentLicense: CC BY-SA 2.5


问:
How to convert a JSONArray to a JsArray?
My JsonArray looks like this  :

```<code>  JSONArray itemsJsonArray = new JSONArray();
  JSONObject jsobj = new JSONObject();

 jsobj.put("a", new JSONString("hi"));
 jsobj.put("b", new JSONString("hgjjh"));
 jsobj.put("c", new JSONNumber(149077));

 itemsJsonArray.set(0, jsobj);
</code>```

I need the equivalent data as a JsArray (package :com.google.gwt.core.client)  since the api that I need to use only accepts the JsArray.

I need to convert to specific JsArray and not any JsonObject and can't take the overhead of serializing my data.

What will be the structure of the equivalent JsArray to the above data structured as key : value ?

答:
This code worked for me .

```<code>        JSONArray itemsJsonArray = new JSONArray();
        JSONObject jsobj = new JSONObject();

        jsobj.put("author", new JSONString("hin"));
        jsobj.put("text", new JSONString("hgg"));
        jsobj.put("created", new JSONString("123"));

        itemsJsonArray.set(0, jsobj);

        JavaScriptObject msg =itemsJsonArray.getJavaScriptObject();
        JsArray<?> ob=(JsArray<?>) msg ;
</code>```

Thanks for the help.

Body:
My JsonArray looks like this  :

  JSONArray itemsJsonArray = new JSONArray();
  JSONObject jsobj = new JSONObject();

 jsobj.put("a", new JSONString("hi"));
 jsobj.put("b", new JSONString("hgjjh"));
 jsobj.put("c", new JSONNumber(149077));

 itemsJsonArray.set(0, jsobj);

I need the equivalent data as a JsArray (package :com.google.gwt.core.client)  since the api that I need to use only accepts the JsArray.

I need to convert to specific JsArray and not any JsonObject and can't take the overhead of serializing my data.

What will be the structure of the equivalent JsArray to the above data structured as key : value ?

Body:
This code worked for me .

        JSONArray itemsJsonArray = new JSONArray();
        JSONObject jsobj = new JSONObject();

        jsobj.put("author", new JSONString("hin"));
        jsobj.put("text", new JSONString("hgg"));
        jsobj.put("created", new JSONString("123"));

        itemsJsonArray.set(0, jsobj);

        JavaScriptObject msg =itemsJsonArray.getJavaScriptObject();
        JsArray<?> ob=(JsArray<?>) msg ;

Thanks for the help.


问:
How to send integers in query parameters in nodejs Express service
I have a nodejs express web server running on my box. I want to send a get request along with query parameters. Is there any way to find type of each query parameter like int,bool,string. The query parameters key value is not know to me. I interpret as a json object of key value pairs at server side.</p>

答:
Maybe this will be of any help to those who read this, but I like to use arrow functions to keep my code clean. Since all I do is change one variable it should only take one line of code:</p>
```<code>module.exports = function(repo){

  router.route('/:id',
  (req, res, next) => { req.params.id = parseInt(req.params.id); next(); })
    .get(repo.getById)
    .delete(repo.deleteById)
    .put(repo.updateById);
}
</code>```

Body:
Maybe this will be of any help to those who read this, but I like to use arrow functions to keep my code clean. Since all I do is change one variable it should only take one line of code:

module.exports = function(repo){

  router.route('/:id',
  (req, res, next) => { req.params.id = parseInt(req.params.id); next(); })
    .get(repo.getById)
    .delete(repo.deleteById)
    .put(repo.updateById);
}


问:
How to tell a setup file to install to the Documents folder with Inno Setup compiler?
I'm trying to create a setup file using Inno Setup Compiler, and I want it to install to the Documents folder as it needs to create and then delete a file, something that it can't do if it installs to Program Files. I've tried using %userprofile%\Documents as that works in File Explorer, but that simply creates a folder called %userprofile% wherever the Setup.exe is, and  C:\Users\%username%\Documents simply creates the %username% folder in the Users folder. How do I get it to install into the Documents folder no matter where it is?

答:
While @GTAVLover is right, you will most probably want to use the {userdocs} or {commondocs} constant in standard Inno Setup sections, likes [Files].

The syntax is like:

[Files]
Source: "readme.txt"; DestDir: "{userdocs}"
```

<hr>

<p>Had you wanted to refer to environment variables (what is not the right way in this case), use <code>{%NAME}</code> syntax:</p>

```[Files]
Source: "readme.txt"; DestDir: "{%USERPROFILE}\Documents"
```

Body:
While @GTAVLover is right, you will most probably want to use the {userdocs} or {commondocs} constant in standard Inno Setup sections, likes [Files].

The syntax is like:

[Files]
Source: "readme.txt"; DestDir: "{userdocs}"

Had you wanted to refer to environment variables (what is not the right way in this case), use {%NAME} syntax:

[Files]
Source: "readme.txt"; DestDir: "{%USERPROFILE}\Documents"


问:
How to round money in Twig to save zero in the end?
For example I have 19.796 and I need to round it up  so I use it like this {% set final_sum = sum + (sum / 100 * 21) | number_format(2, 'ceil') %} and it returns me 19.8 but I need 19.80 with zero on the end.

Body:
{{ '%.2f'|format(19.796) }}

it will round it to 19.80


问:
Issue passing the data from one form to another
Overview:

Passing the data from one form to another.

This is a WinForm application which has two forms, named form1 and PostCodeForm.  I need to pass data from the short-lived form PostcodeForm back to Form1 through a clickEvent, then close the form. The values are stored into dataTable in PostcodeSearch class, and to access them I:

Loop through dataTable in PostCodeForm

```<code>for (var item = 0; item < retreiveResults.Count; item++)
{
    var num = dataGridView2.Rows.Add();
    dataGridView2.Rows[num].Cells[0].Value = retreiveResults[item].City;
    dataGridView2.Rows[num].Cells[1].Value = retreiveResults[item].District;
    dataGridView2.Rows[num].Cells[2].Value = retreiveResults[item].HouseName;
</code>```

Created an instance of Form1 in PostCodeForm:

```<code>Form1 formIndi = new Form1();
</code>```

Then created some local variables which are initialized just before the end of the loop in PostCodeForm

```<code>var _City_Cell = dataGridView2.Rows[num].Cells[0].Value;
var _District_Cell = dataGridView2.Rows[num].Cells[1].Value;
var _HouseName_Cell = dataGridView2.Rows[num].Cells[2].Value;
</code>```

Then to pass them to Form1 (in PostCodeForm):

```<code>formIndi.txt_City.Text = _StreetName_Cell.ToString();
formIndi.txt_HouseName.Text = _HouseName_Cell.ToString();
formIndi.txt_ District.Text = _District_Cell.ToString();
</code>```

I need to pass the data back to the main form and store it in the relevant textBoxes.

Issue

My issue is that none of my textBoxes are updating with given values but when I debug the Vars inside the postCodeForm I can see the values, so I have no idea why then the TextBoxes are not displaying the values, as I have always passed data from form to form this way.

答:
Render the new instance form </p>

```<code>Form1 PostCodeForm= new Form1();
PostCodeForm.Show();
Application.Run();
</code>```

Body:
Overview:

Passing the data from one form to another.

This is a WinForm application which has two forms, named form1 and PostCodeForm.  I need to pass data from the short-lived form PostcodeForm back to Form1 through a clickEvent, then close the form. The values are stored into dataTable in PostcodeSearch class, and to access them I:

Loop through dataTable in PostCodeForm

for (var item = 0; item < retreiveResults.Count; item++)
{
    var num = dataGridView2.Rows.Add();
    dataGridView2.Rows[num].Cells[0].Value = retreiveResults[item].City;
    dataGridView2.Rows[num].Cells[1].Value = retreiveResults[item].District;
    dataGridView2.Rows[num].Cells[2].Value = retreiveResults[item].HouseName;

Created an instance of Form1 in PostCodeForm:

Form1 formIndi = new Form1();

Then created some local variables which are initialized just before the end of the loop in PostCodeForm

var _City_Cell = dataGridView2.Rows[num].Cells[0].Value;
var _District_Cell = dataGridView2.Rows[num].Cells[1].Value;
var _HouseName_Cell = dataGridView2.Rows[num].Cells[2].Value;

Then to pass them to Form1 (in PostCodeForm):

formIndi.txt_City.Text = _StreetName_Cell.ToString();
formIndi.txt_HouseName.Text = _HouseName_Cell.ToString();
formIndi.txt_ District.Text = _District_Cell.ToString();

I need to pass the data back to the main form and store it in the relevant textBoxes.

Issue

My issue is that none of my textBoxes are updating with given values but when I debug the Vars inside the postCodeForm I can see the values, so I have no idea why then the TextBoxes are not displaying the values, as I have always passed data from form to form this way.

Body:
Render the new instance form

Form1 PostCodeForm= new Form1();
PostCodeForm.Show();
Application.Run();


问:
JSP Set attribute does not work
I'm trying to pass an attribute (result) to the url using this piece of code. Unfortunately the parameter is null and does not contain the result data. </p>

```<code>request.setAttribute("result", result);
request.getRequestDispatcher("index.jsp").forward(request, response);
</code>```

答:
request.getAttribute("result") gives you the value stored in result . Also make sure that you type cast the result to corresponding data type, if it's an integer type cast it to a wrapper class Integer.  You can achieve that by doing the following; Integer temp = new Integer(result), and then further getting the attribute.

```<code>Integer recVal= (Integer) request.getAttribute("result");
</code>```

Title: JSP Set attribute does not work

Body:
I'm trying to pass an attribute (result) to the url using this piece of code. Unfortunately the parameter is null and does not contain the result data.

request.setAttribute("result", result);
request.getRequestDispatcher("index.jsp").forward(request, response);

Body:
request.getAttribute("result") gives you the value stored in result . Also make sure that you type cast the result to corresponding data type, if it's an integer type cast it to a wrapper class Integer.  You can achieve that by doing the following; Integer temp = new Integer(result), and then further getting the attribute.

Integer recVal= (Integer) request.getAttribute("result");


问:
Firebase debug mode is not uploading log event
Below logs are showing in console when I enable the debug mode for Firebase. Could not able to find the issue why it is not uploading.

```<code><FIRAnalytics/DEBUG> Uploading data. Host: https://app-measurement.com/a
<FIRAnalytics/DEBUG> Received SSL challenge for host. Host: https://app-measurement.com/a
<FIRAnalytics/DEBUG> Successful upload. Got network response. Code, size: 204, -1
<FIRAnalytics/DEBUG> Do not schedule an upload task. Task already exists
<FIRAnalytics/DEBUG> No data to upload. Upload task will not be scheduled
<FIRAnalytics/DEBUG> Canceling active timer
<FIRAnalytics/DEBUG> Cancelling background upload task.
</code>```

test log code below

```<code>[FIRAnalytics logEventWithName:@"Test"
                        parameters:@{
                                     @"name": @"Test",
                                     @"full_text": @"Test"
                                     }];
</code>```

答:
I am previously using firebase pod version "3.2.1". I just updated my pod file to '~>3.17.0' and after that followed the debug guild mentioned in firebase documentation. Debug logs started show up on firebase portal.

documentation link :
https://firebase.google.com/docs/analytics/debugview

Hope it help :)

Body:
Below logs are showing in console when I enable the debug mode for Firebase. Could not able to find the issue why it is not uploading.

<FIRAnalytics/DEBUG> Uploading data. Host: https://app-measurement.com/a
<FIRAnalytics/DEBUG> Received SSL challenge for host. Host: https://app-measurement.com/a
<FIRAnalytics/DEBUG> Successful upload. Got network response. Code, size: 204, -1
<FIRAnalytics/DEBUG> Do not schedule an upload task. Task already exists
<FIRAnalytics/DEBUG> No data to upload. Upload task will not be scheduled
<FIRAnalytics/DEBUG> Canceling active timer
<FIRAnalytics/DEBUG> Cancelling background upload task.

test log code below

[FIRAnalytics logEventWithName:@"Test"
                        parameters:@{
                                     @"name": @"Test",
                                     @"full_text": @"Test"
                                     }];


问:
Correct relational operator/function for comparison of vec3 values?
I'm trying to check if vec3 values have the same components.

```<code>int same = 0;

vec3 v1 = vec3(1.0f, 0.0f, 0.0f);
vec3 v2 = vec3(0.0f, 0.0f, 0.0f);

if (v1 == v2) // <- this part
{
    same = 1;
}
</code>```

Is == the correct relational operator for vec3 type?

If not, what can I use (operators and functions are also welcome) to compare vec3 values?

答:
The GLSL 4.5 Specification, Section 5.9 states:

The equality operators equal (==), and not equal (!=) operate on all types [...]. They result in a scalar Boolean. [...] For vectors, matrices, structures, and arrays,
  all components, members, or elements of one operand must equal the corresponding components,
  members, or elements in the other operand for the operands to be considered equal.

To answer your question: Yes, the == operator compares weather two vectors have the same value in all components.

Body:
I'm trying to check if vec3 values have the same components.

int same = 0;

vec3 v1 = vec3(1.0f, 0.0f, 0.0f);
vec3 v2 = vec3(0.0f, 0.0f, 0.0f);

if (v1 == v2) // <- this part
{
    same = 1;
}

Is == the correct relational operator for vec3 type?

If not, what can I use (operators and functions are also welcome) to compare vec3 values?


问:
MS-SQL 2000: Turn off logging during stored procedure
Here's my scenario:

I have a simple stored procedure that removes a specific set of rows from a table (we'll say about 30k rows), and then inserts about the same amount of rows.  This generally should only take a few seconds; however, the table has a trigger on it that watches for inserts/deletes, and tries to mimic what happened to a linked table on another server.

This process in turn is unbareably slow due to the trigger, and the table is also locked during this process.  So here are my two questions:

I'm guessing a decent part of the slowdown is due to the transaction log.  Is there a way for me to specify in my stored procedure that I do not want what's in the procedure to be logged?

Is there a way for me to do my 'DELETE FROM' and 'INSERT INTO' commands without me locking the table during the entire process?

Thanks!

edit - Thanks for the answers; I figured it was the case (not being able to do either of the above), but wanted to make sure.  The trigger was created a long time ago, and doesn't look very effecient, so it looks like my next step will be to go in to that and find out what's needed and how it can be improved.  Thanks!

答:
1) no, also you are not doing a minimally logged operation like TRUNCATE or BULK INSERT

2) No, how would you prevent corruption otherwise?

OwnerDisplayName: John

LastEditorDisplayName: CodeSlave

OwnerDisplayName: SQLMenace


问:
show button when text is entered in pure HTML/LESS
I want a text field where i can insert text into and when i enter the text there should appear a button on the end of the textfield to clear the text. But I want this with only HTML/Less so without any JS.

As you can see in the code below I used the display: none attribute and i want to change the display: none to display: block after there is text entered in the input field.

code below:

```<code>                    <div class="input-field">
                    <input name="{{field.name}}" ng-model="field.value" type="text"/>

                    <button class="icon-assistant8 ci-cancel" type="reset">
                    </button>

                </div>
</code>```

And this is the relevant Less file:

```<code> .icon-assistant8 {
    position: absolute;
    right: 3px;
    top: 5px;
    width: 20px;
    height: 20px;
    display: none;
}

.icon-assistant8:after {
    display: block;
}
</code>```

Edit: After this example https://codepen.io/shidhincr/pen/ICLBD I know it is possible to do it with only HTML and CSS. I want to do that too but I can't get it to work and I do not know why.

Also I know I can do this with JS, I am just courious what i'm doing wrong.

答:
They key parts of the example you've linked to that you haven't implemented in your own solution are

```<code>.search-box:not(:valid) ~ .close-icon {
    display: none;
}
</code>```

```<code><input type="text" name="focus" required class="search-box" placeholder="Enter search term" />
</code>```

In order for :not(:valid) to match, you need the required attribute on the input. When the input is empty, it's considered not valid.

Here's a basic example

input:not(:valid) ~ button { display: none; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" required>
<button type="button">Foo</button></code>```

Body:
I want a text field where i can insert text into and when i enter the text there should appear a button on the end of the textfield to clear the text. But I want this with only HTML/Less so without any JS.

As you can see in the code below I used the display: none attribute and i want to change the display: none to display: block after there is text entered in the input field.

code below:

                    <input name="{{field.name}}" ng-model="field.value" type="text"/>

                    <button class="icon-assistant8 ci-cancel" type="reset">
                    </button>

And this is the relevant Less file:

 .icon-assistant8 {
    position: absolute;
    right: 3px;
    top: 5px;
    width: 20px;
    height: 20px;
    display: none;
}

.icon-assistant8:after {
    display: block;
}

Edit: After this example https://codepen.io/shidhincr/pen/ICLBD I know it is possible to do it with only HTML and CSS. I want to do that too but I can't get it to work and I do not know why.

Also I know I can do this with JS, I am just courious what i'm doing wrong.

Body:
They key parts of the example you've linked to that you haven't implemented in your own solution are

.search-box:not(:valid) ~ .close-icon {
    display: none;
}

<input type="text" name="focus" required class="search-box" placeholder="Enter search term" />

In order for :not(:valid) to match, you need the required attribute on the input. When the input is empty, it's considered not valid.

Here's a basic example

input:not(:valid) ~ button { display: none; }

<input type="text" required>
<button type="button">Foo</button>


问:
Convert & sort javascript array numerically using non-numeric key
I have a JS array in following structure:

```<code>Array(
    [0] => Array(
        reference : "8926"
        name : "xyz1"
        id_product : "78"
    )
    [1] => Array(
        reference : "11588"
        name : "xyz2"
        id_product : "21"
    )
    [2] => Array(
        reference : "119"
        name : "xyz3"
        id_product : "135"
    )
)
</code>```

I needed to sort this array using the reference key, I have done it using multisort function;

But the problem is : even though reference is numeric but in the array structure it is defined as string and hence instead of sorting like:
119, 8926, 11588 it is sorting it like 11588 119 8926, i.e., like string.

I cannot re-structure the array because I receive it through an API, is there anyway to sort it numerically without having to recreate it in numeric data type separately (because I have to pass the array forward in same format & hence double-conversion will make the script hectic)?

PS - Current sorting (non-numeric) is done using this function.

答:
You can try this.</p>

```<code>myArray.sort(function(a, b){
   return parseInt(a["reference"]) - parseInt(b["reference"]);
});
</code>```

Body:
I have a JS array in following structure:

Array(
    [0] => Array(
        reference : "8926"
        name : "xyz1"
        id_product : "78"
    )
    [1] => Array(
        reference : "11588"
        name : "xyz2"
        id_product : "21"
    )
    [2] => Array(
        reference : "119"
        name : "xyz3"
        id_product : "135"
    )
)

I needed to sort this array using the reference key, I have done it using multisort function;

But the problem is : even though reference is numeric but in the array structure it is defined as string and hence instead of sorting like:
119, 8926, 11588 it is sorting it like 11588 119 8926, i.e., like string.

I cannot re-structure the array because I receive it through an API, is there anyway to sort it numerically without having to recreate it in numeric data type separately (because I have to pass the array forward in same format & hence double-conversion will make the script hectic)?

PS - Current sorting (non-numeric) is done using this function.

Body:
You can try this.

myArray.sort(function(a, b){
   return parseInt(a["reference"]) - parseInt(b["reference"]);
});


问:
F#: Disposing of resources that are inside a closure?
Suppose I create a closure over a resource such as a StreamWriter:

```<code>let currentdir = Directory.GetCurrentDirectory()
let testfile = sprintf "%s\\%s" currentdir "closuretest.txt"

let getwriter() =
    let writer = new StreamWriter(testfile, false)
    (fun() -> writer.Write "test")
</code>```

Is there a way to close the StreamWriter when I'm done with the closure? Or do I need to replace the closure with a wrapper object that has a Write() method and a Dispose() method? (This is of course a trivialized example.) Thanks all.

答:
IDisposable is about deterministically, i.e. explicitly releasing resources. Thus if the closure doesn't somehow provide a disposing functionality by itself, the resource cannot be release deterministically any more.

As Brian pointed out, this can be more or less explicit, though implementing IDisposable is preferrable as use + IDisposable automatically takes care of releasing resources in case of exceptions.

However, sometimes it's sufficient to completely hide the disposable resource and get a closure of what's to be done instead.

```<code>let getWriter body =
    use writer = new StreamWriter(testfile, false)
    body(writer)

// ...

getWriter (fun writer -> writer.Write "test")
</code>```

Body:
Suppose I create a closure over a resource such as a StreamWriter:

let currentdir = Directory.GetCurrentDirectory()
let testfile = sprintf "%s\\%s" currentdir "closuretest.txt"

let getwriter() =
    let writer = new StreamWriter(testfile, false)
    (fun() -> writer.Write "test")

Is there a way to close the StreamWriter when I'm done with the closure? Or do I need to replace the closure with a wrapper object that has a Write() method and a Dispose() method? (This is of course a trivialized example.) Thanks all.

Body:
IDisposable is about deterministically, i.e. explicitly releasing resources. Thus if the closure doesn't somehow provide a disposing functionality by itself, the resource cannot be release deterministically any more.

As Brian pointed out, this can be more or less explicit, though implementing IDisposable is preferrable as use + IDisposable automatically takes care of releasing resources in case of exceptions.

However, sometimes it's sufficient to completely hide the disposable resource and get a closure of what's to be done instead.

let getWriter body =
    use writer = new StreamWriter(testfile, false)
    body(writer)

// ...

getWriter (fun writer -> writer.Write "test")


问:
407 response from proxy using python requests
Below is the code that i used. I am using latest python requests. I am getting 407 response from the below request using python 2.7.
And strange thing is i am getting 503 response while using https instead of http in the requests.

```<code>response = requests.get(query, proxies={'https': "https://username:password@104.247.XX.XX:80"}, headers=headers, timeout=30, allow_redirects=True)
print response
</code>```

Output: Response [503]

```<code>response = requests.get(query, proxies={'http': "http://username:password@104.247.XX.XX:80"}, headers=headers, timeout=30, allow_redirects=True)
print response
</code>```

Output: Response [407]

But the same code is working on my amazon ec2 instance. Though i am trying to run in local machine.

```<code>import urllib2
import urllib
import portalocker
import cookielib
import requests

query = 'http://google.com/search?q=wtf&num=100&tbs=cdr:1,cd_min:2000,cd_max:2015&start=0&filter=0'
headers = {'user-agent': 'Mozilla/5.0 (X11; Linux; rv:2.0.1) Gecko/20100101 Firefox/4.0.1 Midori/0.4'}
response = requests.get(query, proxies={'http': "http://username:password@104.247.XX.XX:80"}, headers=headers, timeout=30, allow_redirects=True)
print response
</code>```

答:
```<code>from requests.auth import HTTPProxyAuth

proxyDict = {
          'http'  : '77.75.105.165',
          'https' : '77.75.105.165'
        }
auth = HTTPProxyAuth('username', 'mypassword')

r = requests.get("http://www.google.com", proxies=proxyDict, auth=auth)
</code>```

Body:
Below is the code that i used. I am using latest python requests. I am getting 407 response from the below request using python 2.7.
And strange thing is i am getting 503 response while using https instead of http in the requests.

response = requests.get(query, proxies={'https': "https://username:password@104.247.XX.XX:80"}, headers=headers, timeout=30, allow_redirects=True)
print response

Output: Response [503]

response = requests.get(query, proxies={'http': "http://username:password@104.247.XX.XX:80"}, headers=headers, timeout=30, allow_redirects=True)
print response

Output: Response [407]

But the same code is working on my amazon ec2 instance. Though i am trying to run in local machine.

import urllib2
import urllib
import portalocker
import cookielib
import requests

query = 'http://google.com/search?q=wtf&num=100&tbs=cdr:1,cd_min:2000,cd_max:2015&start=0&filter=0'
headers = {'user-agent': 'Mozilla/5.0 (X11; Linux; rv:2.0.1) Gecko/20100101 Firefox/4.0.1 Midori/0.4'}
response = requests.get(query, proxies={'http': "http://username:password@104.247.XX.XX:80"}, headers=headers, timeout=30, allow_redirects=True)
print response


问:
SQL partial date comparison
Which method is most efficient when comparing PARTS of date/datetime values? Example for comparing month of datetimes:

```<code>where insdate =DATEADD(month, DATEDIFF(month, 0, @insdate), 0)
</code>```

or

```<code>where year(insdate)=year(@insdate) and month(insdate)=month(@insdate)
</code>```

I'm using sql server

答:
In my opinion, the best way to implement Year or YearMonth check is to cast date in this format YYYYMMDD and then work with that.

This is an example:

Filter by YearMonthDay

```<code>SELECT * FROM myTable
WHERE CONVERT(VARCHAR,MyField,112) = 20170607
</code>```

Filter by YearMonth

```<code>SELECT * FROM myTable
WHERE CONVERT(VARCHAR,MyField,112) / 100 = 201706
</code>```

Filter by Year

```<code>SELECT * FROM myTable
WHERE CONVERT(VARCHAR,MyField,112) / 10000 = 2017
</code>```

For sure this perfomrs better than using Year() ,Month() , DateAdd(), DateDiff() functions.

Title: SQL partial date comparison

Body:
Which method is most efficient when comparing PARTS of date/datetime values? Example for comparing month of datetimes:

where insdate =DATEADD(month, DATEDIFF(month, 0, @insdate), 0)

or

where year(insdate)=year(@insdate) and month(insdate)=month(@insdate)

I'm using sql server

Body:
In my opinion, the best way to implement Year or YearMonth check is to cast date in this format YYYYMMDD and then work with that.

This is an example:

Filter by YearMonthDay

SELECT * FROM myTable
WHERE CONVERT(VARCHAR,MyField,112) = 20170607

Filter by YearMonth

SELECT * FROM myTable
WHERE CONVERT(VARCHAR,MyField,112) / 100 = 201706

Filter by Year

SELECT * FROM myTable
WHERE CONVERT(VARCHAR,MyField,112) / 10000 = 2017

For sure this perfomrs better than using Year() ,Month() , DateAdd(), DateDiff() functions.


问:
custom log grok pattern
I am trying to parse a custom log line using grok pattern but I'm not able to completely parse the line.

Custom log line:

```<code>site 'TRT' : alias 'TRT,FAK,FAS,ATI,ONE,DVZ,TWO' : serveur 'Test10011' RAS : TRT / TRT serveur 'Test10011' OK
</code>```

Grok pattern:

```<code>%{DATA:site}\:%{DATA:alias}\:%{DATA:server}\:%{DATA:msg}
</code>```

Result:

```<code>{
  "site": [
    [
      "site 'TRT' "
    ]
  ],
  "alias": [
    [
      " alias 'TRT,FAK,FAS,ATI,ONE,DVZ,TWO' "
    ]
  ],
  "server": [
    [
      " serveur 'Test10011' RAS "
    ]
  ],
  "msg": [
    [
      ""
    ]
  ]
}
</code>```

I am not able to parse the last few items in the 'msg', . Could you please help ,where I'm going wrong? msg should contain "TRT / TRT serveur 'Test10011' OK"

答:
It seems you just need to use GREEDYDATA instead of DATA pattern:

```<code>%{DATA:site}\s*:\s*%{DATA:alias}\s*:\s*%{DATA:server}\s*:\s*%{GREEDYDATA:msg}
</code>```

I also suggest adding \s* around : to get rid of leading/trailing whitespaces.

Title: custom log grok pattern

Body:
I am trying to parse a custom log line using grok pattern but I'm not able to completely parse the line.

Custom log line:

site 'TRT' : alias 'TRT,FAK,FAS,ATI,ONE,DVZ,TWO' : serveur 'Test10011' RAS : TRT / TRT serveur 'Test10011' OK

Grok pattern:

%{DATA:site}\:%{DATA:alias}\:%{DATA:server}\:%{DATA:msg}

Result:

{
  "site": [
    [
      "site 'TRT' "
    ]
  ],
  "alias": [
    [
      " alias 'TRT,FAK,FAS,ATI,ONE,DVZ,TWO' "
    ]
  ],
  "server": [
    [
      " serveur 'Test10011' RAS "
    ]
  ],
  "msg": [
    [
      ""
    ]
  ]
}

I am not able to parse the last few items in the 'msg', . Could you please help ,where I'm going wrong? msg should contain "TRT / TRT serveur 'Test10011' OK"

Body:
It seems you just need to use GREEDYDATA instead of DATA pattern:

%{DATA:site}\s*:\s*%{DATA:alias}\s*:\s*%{DATA:server}\s*:\s*%{GREEDYDATA:msg}

I also suggest adding \s* around : to get rid of leading/trailing whitespaces.


问:
JQuery Datepicker date format - How to change from dd/mm/yyyy to dd/mm/yy?
I have used JQuery Datepicker where the date format is dd/mm/yyyy. I would like the date to be displayed as dd/mm/yy.

Eg. Instead of 15/07/2017, I would like the date to be shown as 15/07/17 in the datepicker.

This is how I am calling the JQuery datepicker, but it is not formating the date as per my need.

```<code>$( ".startdate" ).datepicker({
    dateFormat: 'dd-mm-yy',
    changeMonth: true,
    changeYear: true
});
</code>```

Is there any inbuilt option for this date format? Or is there a way to create a custom date format according to our own needs.

答:
You need to do like below:-

```<code>$( ".startdate" ).datepicker({
    dateFormat: 'dd/mm/y',//check change
    changeMonth: true,
    changeYear: true
});
</code>```

Example:-

$(".startdate").datepicker({
  dateFormat: 'dd/mm/y', //check change
  changeMonth: true,
  changeYear: true
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.js" data-modules="effect effect-bounce effect-blind effect-bounce effect-clip effect-drop effect-fold effect-slide"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />

<h4>Datepicker with Date Format (dd/mm/y) using JQuery</h4>
<p>Date picker: <input type="text" class="startdate" size="30" /></p>
<p> Date Format : dd/mm/y</p></code>```

Body:
I have used JQuery Datepicker where the date format is dd/mm/yyyy. I would like the date to be displayed as dd/mm/yy.

Eg. Instead of 15/07/2017, I would like the date to be shown as 15/07/17 in the datepicker.

This is how I am calling the JQuery datepicker, but it is not formating the date as per my need.

$( ".startdate" ).datepicker({
    dateFormat: 'dd-mm-yy',
    changeMonth: true,
    changeYear: true
});

Is there any inbuilt option for this date format? Or is there a way to create a custom date format according to our own needs.

Body:
You need to do like below:-

$( ".startdate" ).datepicker({
    dateFormat: 'dd/mm/y',//check change
    changeMonth: true,
    changeYear: true
});

Example:-

$(".startdate").datepicker({
  dateFormat: 'dd/mm/y', //check change
  changeMonth: true,
  changeYear: true
});

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.js" data-modules="effect effect-bounce effect-blind effect-bounce effect-clip effect-drop effect-fold effect-slide"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />

<h4>Datepicker with Date Format (dd/mm/y) using JQuery</h4>
<p>Date picker: <input type="text" class="startdate" size="30" /></p>
<p> Date Format : dd/mm/y</p>


问:
iTextPdf how to break page
I generate pdf file from html page using iTextPdf like:

```<code>iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
            TextReader reader = new StringReader(HTML);
            hw.Parse(reader);
            document.Close();
</code>```

but my html page is large and I need to add page brakes in specific places.

How can I add these page breaks in pdf?

Thanks

答:
Use this code when you want to insert page break:

document.NewPage();

Title: iTextPdf how to break page

Body:
I generate pdf file from html page using iTextPdf like:

iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
            TextReader reader = new StringReader(HTML);
            hw.Parse(reader);
            document.Close();

but my html page is large and I need to add page brakes in specific places.

How can I add these page breaks in pdf?

Thanks


问:
“this” keyword doesn’t seem to work
I am trying to understand how the this keyword works in JavaScript and I made this script:

```<code>function click(){
    this.innerHTML="changed";
}
</code>```

Used in this HTML:

```<code><button id="clicker" onclick="click()" >Click me</button>
</code>```

But it doesn't work, can anyone explain why?

答: Have a look at http://www.quirksmode.org/js/this.html</p>

Title: “this” keyword doesn’t seem to work

Body:
I am trying to understand how the this keyword works in JavaScript and I made this script:

function click(){
    this.innerHTML="changed";
}

Used in this HTML:

<button id="clicker" onclick="click()" >Click me</button>

But it doesn't work, can anyone explain why?


问:
is there a way of handling this Attribute value must be constant error?
I'm trying to invoke this method:

```<code>public Response getWithPathParam(@ApiParam(
        value = "Service group to check",
        allowableValues = ApiConstants.components,
        required = true )
</code>```

but want that allowableValues attribute will get a value that can be varying.

what I mean that I assuming allowableValues is a String.

I wondering if there is a way of reading a string from configuration and pass it into the attributes.

my attempt so far just led into the error of:

"Attribute value must be constant"

can you help please?

答:
Generally, compiler errors cannot be handled in any way other than fixing them.
It is only runtime errors that can somehow be handled.

According to the java language specification, a parameter to an annotation must be a compile-time constant.

This means that you cannot do anything even remotely close to what you are trying to do.

Body:
I'm trying to invoke this method:

public Response getWithPathParam(@ApiParam(
        value = "Service group to check",
        allowableValues = ApiConstants.components,
        required = true )

but want that allowableValues attribute will get a value that can be varying.

what I mean that I assuming allowableValues is a String.

I wondering if there is a way of reading a string from configuration and pass it into the attributes.

my attempt so far just led into the error of:

"Attribute value must be constant"

can you help please?


问:
Is pre-compiled Qt 5.9 VS version independent?
On the Qt website, in the download section, there is a pre-compiled Qt5.9 available.

Before Qt5.9 there were different pre-compiled packages for each Visual Studio version.

Is new pre-compiled Qt5.9 VS version independent?
If not, for which version is it?

答:
No, it's not. It can't be since visual c++ versions are usually* not binary compatible (*just now Visual Studio 2017 is binary compatible with 2015).

That package just has different versions you can install, to target Windows: VS2013 (x64), VS2015(x64 and x86), VS2017(x64), MinGW and to target Android (arm and x86).


Title: Postgresql round timestamp to nearest 30 seconds

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

source -> result

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

Body:
quite ugly to round upwords and downwords:

t=# with a(ts) as (
  values ('2017-06-07 14:11:20'::timestamp),('2017-06-07 14:11:40'),('2017-06-07 14:12:10'),('2017-06-07 14:11:50')
)
, c as (
  select *,date_trunc('minute',ts) t0, date_trunc('minute',ts) + '15 seconds'::interval t1,date_trunc('minute',ts)+ '30 seconds'::interval t2,date_trunc('minute',ts)+ '45 seconds'::interval t3, date_trunc('minute',ts) + '1 minute'::interval t5
  from a
)
select case when ts between t0 and t1 then t0 when ts between t1 and t3 then t2 when ts between t3 and t5 then t5 end rnd,ts from c;
         rnd         |         ts
---------------------+---------------------
 2017-06-07 14:11:30 | 2017-06-07 14:11:20
 2017-06-07 14:11:30 | 2017-06-07 14:11:40
 2017-06-07 14:12:00 | 2017-06-07 14:12:10
 2017-06-07 14:12:00 | 2017-06-07 14:11:50
(4 rows)

Time: 0.434 ms


问:
How to convert all arguments to dictionary in python
I would like to my function func(*args, **kwargs) return one dictionary which contains all arguments I gave to it. For example:

```<code>func(arg1, arg2, arg3=value3, arg4=value4)
</code>```

should return one dictionary like this:

```<code>{'arg1': value1, 'arg2': value2, 'arg3': value3, 'arg4': value4 }
</code>```

答:
If you can't use locals like the other answers suggest:

```<code>def func(*args, **kwargs):
    all_args = {("arg" + str(idx + 1)): arg for idx,arg in enumerate(args)}
    all_args.update(kwargs)
</code>```

This will create a dictionary with all arguments in it, with names.

Body:
I would like to my function func(*args, **kwargs) return one dictionary which contains all arguments I gave to it. For example:

func(arg1, arg2, arg3=value3, arg4=value4)

should return one dictionary like this:

{'arg1': value1, 'arg2': value2, 'arg3': value3, 'arg4': value4 }

Body:
If you can't use locals like the other answers suggest:

def func(*args, **kwargs):
    all_args = {("arg" + str(idx + 1)): arg for idx,arg in enumerate(args)}
    all_args.update(kwargs)

This will create a dictionary with all arguments in it, with names.


问:
How to round money in Twig to save zero in the end?
For example I have 19.796 and I need to round it up  so I use it like this {% set final_sum = sum + (sum / 100 * 21) | number_format(2, 'ceil') %} and it returns me 19.8 but I need 19.80 with zero on the end.

答:
use this.

{{ "%.2f"|format(19.796|round(2, 'ceil')) }} //19.80

19.8 is same as 19.80 so if you want with trailing 0 then convert it into a string.


问:
RxJava from list with async wait for callback
```<code>List<String> listExample = Arrays.asList("one", "two", "three");
</code>```

Think of i have list of string, and using RxJava (Observable.fromArray)

```<code>Observable.fromArray(ids.toArray(new String[ids.size()])).subscribe(new Consumer<String>() {
    @Override
    public void accept(@NonNull String s) throws Exception {

    }
});
</code>```

Here think each string has a Async callback here once i receive that callback it should move to next string. Is it possible using rxjava?

This is the code which i'am having currently, it doesn't wait for till the callback right!.

```<code>for (String id : ids) {
    getMessage(id, new urlGenCallback() {
        @Override
        public void urlAndToken(String url, String token, String idx) {

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

Thank you @Geoffrey Marizy

Answer: Check Below
For More Info About ConcatMap Visit Here

答:
You are looking to the concatMap operator. A complete article on this topic: https://fernandocejas.com/2015/01/11/rxjava-observable-tranformation-concatmap-vs-flatmap/

Wrap your request as an Observable, then pass it as a parameter to concatMap :

```<code>Observable.fromArray(ids.toArray(new String[ids.size()])).concatMap(/* your request returning an Observable */)
</code>```

Body:
List<String> listExample = Arrays.asList("one", "two", "three");

Think of i have list of string, and using RxJava (Observable.fromArray)

Observable.fromArray(ids.toArray(new String[ids.size()])).subscribe(new Consumer<String>() {
    @Override
    public void accept(@NonNull String s) throws Exception {

    }
});

Here think each string has a Async callback here once i receive that callback it should move to next string. Is it possible using rxjava?

This is the code which i'am having currently, it doesn't wait for till the callback right!.

for (String id : ids) {
    getMessage(id, new urlGenCallback() {
        @Override
        public void urlAndToken(String url, String token, String idx) {

        }
    });
}

Thank you @Geoffrey Marizy

Answer: Check Below
For More Info About ConcatMap Visit Here

Body:
You are looking to the concatMap operator. A complete article on this topic: https://fernandocejas.com/2015/01/11/rxjava-observable-tranformation-concatmap-vs-flatmap/

Wrap your request as an Observable, then pass it as a parameter to concatMap :

Observable.fromArray(ids.toArray(new String[ids.size()])).concatMap(/* your request returning an Observable */)


问:
Adding inner shadow to top of UIView
I looked up but I couldn't find how I can add an inner shadow to UIView, only top (from top to bottom) for Swift. What is the best way add inner circle in Swift?

Edit: I've found some questions & answers on SO however they are either in obj-c or looks so complicated. I was just looking for a more Swifty way, if there is any

What I want to achieve:

答:
I rewrote @NRitH solution on Swift 3, also slightly refactor it:</p>

```<code>final class SideShadowLayer: CAGradientLayer {
    enum Side {
        case top,
        bottom,
        left,
        right
    }

    init(frame: CGRect, side: Side, shadowWidth: CGFloat,
         fromColor: UIColor = .black,
         toColor: UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0),
         opacity: Float = 0.5) {
        super.init()

        colors = [fromColor.cgColor, toColor.cgColor]
        self.opacity = opacity

        switch side {
        case .bottom:
            startPoint = CGPoint(x: 0.5, y: 1.0)
            endPoint = CGPoint(x: 0.5, y: 0.0)
            self.frame = CGRect(x: 0, y: frame.height - shadowWidth, width: frame.width, height: shadowWidth)

        case .top:
            startPoint = CGPoint(x: 0.5, y: 0.0)
            endPoint = CGPoint(x: 0.5, y: 1.0)
            self.frame = CGRect(x: 0, y: 0, width: frame.width, height: shadowWidth)

        case .left:
            startPoint = CGPoint(x: 0.0, y: 0.5)
            endPoint = CGPoint(x: 1.0, y: 0.5)
            self.frame = CGRect(x: 0, y: 0, width: shadowWidth, height: frame.height)

        case .right:
            startPoint = CGPoint(x: 1.0, y: 0.5)
            endPoint = CGPoint(x: 0.0, y: 0.5)
            self.frame = CGRect(x: frame.width - shadowWidth, y: 0, width: shadowWidth, height: frame.height)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}
</code>```

Title: Adding inner shadow to top of UIView

Body:
I rewrote @NRitH solution on Swift 3, also slightly refactor it:

final class SideShadowLayer: CAGradientLayer {
    enum Side {
        case top,
        bottom,
        left,
        right
    }

    init(frame: CGRect, side: Side, shadowWidth: CGFloat,
         fromColor: UIColor = .black,
         toColor: UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0),
         opacity: Float = 0.5) {
        super.init()

        colors = [fromColor.cgColor, toColor.cgColor]
        self.opacity = opacity

        switch side {
        case .bottom:
            startPoint = CGPoint(x: 0.5, y: 1.0)
            endPoint = CGPoint(x: 0.5, y: 0.0)
            self.frame = CGRect(x: 0, y: frame.height - shadowWidth, width: frame.width, height: shadowWidth)

        case .top:
            startPoint = CGPoint(x: 0.5, y: 0.0)
            endPoint = CGPoint(x: 0.5, y: 1.0)
            self.frame = CGRect(x: 0, y: 0, width: frame.width, height: shadowWidth)

        case .left:
            startPoint = CGPoint(x: 0.0, y: 0.5)
            endPoint = CGPoint(x: 1.0, y: 0.5)
            self.frame = CGRect(x: 0, y: 0, width: shadowWidth, height: frame.height)

        case .right:
            startPoint = CGPoint(x: 1.0, y: 0.5)
            endPoint = CGPoint(x: 0.0, y: 0.5)
            self.frame = CGRect(x: frame.width - shadowWidth, y: 0, width: shadowWidth, height: frame.height)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}


问:
How to check if all subnodes of TreeNode are expanded?
Is there any easy way to check expand the state of TreeNode and its children? </p>

```<code>bool IsAllNodesExpanded(TreeNode nodeToCheck)
{
  // Use nodeToCheck.isExpanded
  // Use something to check all childrens
  // return something
}
</code>```

答:
Instead of using TreeNode you could introduce your own class which derives from TreeNode. This class could have a recursive method IsAllNodesExpanded like this: (untested)

```<code>public class MyTreeNode : TreeNode
{
  public bool IsAllNodesExpanded()
  {
    if (!IsExpanded)
    {
      return false;
    }

    bool allChildsExpanded = true;

    foreach (MyTreeNode child in Nodes.OfType<MyTreeNode>())
    {
      if (!child.IsAllNodesExpanded())
      {
        allChildsExpanded = false;
        break;
      }
    }

    return allChildsExpanded;
  }
}
</code>```

Body:
Is there any easy way to check expand the state of TreeNode and its children?

bool IsAllNodesExpanded(TreeNode nodeToCheck)
{
  // Use nodeToCheck.isExpanded
  // Use something to check all childrens
  // return something
}

Body:
Instead of using TreeNode you could introduce your own class which derives from TreeNode. This class could have a recursive method IsAllNodesExpanded like this: (untested)

public class MyTreeNode : TreeNode
{
  public bool IsAllNodesExpanded()
  {
    if (!IsExpanded)
    {
      return false;
    }

    bool allChildsExpanded = true;

    foreach (MyTreeNode child in Nodes.OfType<MyTreeNode>())
    {
      if (!child.IsAllNodesExpanded())
      {
        allChildsExpanded = false;
        break;
      }
    }

    return allChildsExpanded;
  }
}


问:
Tenant option is missing in "Admin" Dashboard of Camunda Web App, How to enable it?
In Camunda Web app, on opening Admin menu, its noticed that there are options such as Users, Groups,System and Authorization whereas Tenant option is missing.
Any idea what's wrong? or How to enable it?</p>

答:
this feature is only available starting at version 7.5.x of Camunda BPM platform. You can check the release notes here https://blog.camunda.org/post/2016/05/camunda-bpm-750-released/. It would be great if you would upgrade and try again.

Cheers,
Askar


问:
Selenium Webdriver : How to navigate to child div and move foucs over specific div
Currently facing the issue in navigating to many div tags.
In my application, I have a grid which populates or load data in multiple div tags.

On mouseover, I have to click add comment option which gets loaded as lightbox popup.

Please guide me how to select add comment option.

```<code> <div ng-cell="">
<div class="inCell ng-scope">
<div class="cellDarkGray" ng2-class="{cellDarkGray: (row.getProperty('returnedRecordsNumber') != '0'),cellDarkGray: (row.getProperty('activityid') != '0'),cellDarkGray: (row.getProperty('returnedRecordsNumber') != '0')}">
<div class="cellOrange" ng-class="{cellRed: (row.getProperty('Impact') == '0'),cellOrange: (row.getProperty('activityid') != '0'), cellBlue: (row.getProperty('Impact') == '2')}"/>
<div class="cellWhite">
<div style="height:60px">
<div class="ng-hide" ng-show="(row.getProperty('commentFlag')== true) && (userRole =='ROLE_2') ">
<div class="ng-hide" ng-show="(row.getProperty('commentFlag')== true) && (userRole =='ROLE_1') ">
</div>
<div class="inCellData">
<div class="line1" ng-click="openDetails(row,'viewDetail')">
<span class="title1 ng-binding" ng-hide="row.getProperty('planned_typ')== 'NULL'">ORANGE PLANNED MAINTENANCE - </span>
<span class="title2 ng-binding" ng-hide="row.getProperty('deviceid')== 'NULL'">  BLCY810</span>
<!-- <span ng-hide="row.getProperty('myRouterName')== ''"> ||{{row.getProperty('myRouterName')}} ||</span> -->
</div>
<div class="line2">
<span class="title3"/>
<span class="ng-binding" ng-hide="row.getProperty('service_impact')== ''"> 1 - 5 MINS ||</span>
<span class="title3 ng-binding">09/JUN/2017 01:30:00 AM</span>
up to
<span class="title2 ng-binding">09/JUN/2017 03:30:00 AM</span>
||
<span class="ng-binding">EQUANT SHARED NETWORK</span>
</div>
<div class="line3">
</div>
<div>
<nav id="cbp-spmenu-s1" class="cbp-spmenu cbp-spmenu-vertical cbp-spmenu-left cbp-spmenu-open">
<a ng-click="openDetails(row,'viewDetail')">view details</a>
<div class="" ng-show="userRole =='ROLE_1'">
<a class="" ng-show="row.getProperty('internalFlag')=='Y'" ng-click="setUnsetInternal(row)">invisible to customer</a>
<a class="ng-hide" ng-show="row.getProperty('internalFlag')=='Z'" ng-click="row.getProperty('sourcesystem')=='Carrier Changes' && (row.getProperty('urgency')=='EMERGENCY' || row.getProperty('urgency')=='EXPEDITE') ? alertPastDataZEmergency() : alertPastDataZ() ">invisible to customer</a>
<a class="ng-hide" ng-show="row.getProperty('internalFlag')=='N'" ng-click="setUnsetInternal(row)">visible to customer</a>
<a class="ng-hide" ng-show="row.getProperty('internalFlag')=='X' || row.getProperty('internalFlag')=='H'" ng-click="alertPastDataX()">visible to customer</a>
</div>
<!-- Prod Consol Start -->
<a ng-show="userRole =='ROLE_1'" ng-click="openDetails(row, 'comment')">add a comment</a>
<!-- Prod Consol End -->
</nav>
</div>
</div>
</div>
</code>```

答:
Do mouse hover to the parent element to make the comment visible. Below code might give you some idea.

```<code>    Actions action = new Actions(driver);
    action.moveToElement("//nav[@id='cbp-spmenu-s1']").perform();

    //Now the comment button will be visible
    driver.findElement(By.xpath("//a[contains(text(), 'add a comment')]")).click();
</code>```

Hope this helps. Thanks.

Body:
Currently facing the issue in navigating to many div tags.
In my application, I have a grid which populates or load data in multiple div tags.

On mouseover, I have to click add comment option which gets loaded as lightbox popup.

Please guide me how to select add comment option.

ORANGE PLANNED MAINTENANCE -
  BLCY810

 1 - 5 MINS ||
09/JUN/2017 01:30:00 AM
up to
09/JUN/2017 03:30:00 AM
||
EQUANT SHARED NETWORK

view details

invisible to customer
invisible to customer
visible to customer
visible to customer

add a comment

Body:
Do mouse hover to the parent element to make the comment visible. Below code might give you some idea.

    Actions action = new Actions(driver);
    action.moveToElement("//nav[@id='cbp-spmenu-s1']").perform();

    //Now the comment button will be visible
    driver.findElement(By.xpath("//a[contains(text(), 'add a comment')]")).click();

Hope this helps. Thanks.


问:
Call a variadic function using a variable template
Consider the following code:

```<code>template<typename T, typename... Args>
void foo(const Args&... args)
{
    //...
}

template<typename... Args>
auto fooChar = foo<char, Args...>;

template<typename... Args>
auto fooInt = foo<int, Args...>;
</code>```

To be able to make use of these variable templates, I need to explicitely type the template parameters, like so:

```<code>fooChar<int, char, const char*>(5, 'a', "bar");
</code>```

However, in a standard variadic function call, the template parameters are implicitely deduced based on the actual function parameters type. In other words, I would like to be able to use the variable templates like so, but the extra level of indirection seems to restrict this:

```<code>fooChar(5, 'a', "bar");
</code>```

Obviously, I could simply define simple wrapper functions instead of variable templates, like so:

```<code>template<typename... Args>
void fooChar(const Args&... args)
{
    return foo<char>(args...);
}

template<typename... Args>
void fooInt(const Args&... args)
{
    return foo<int>(args...);
}
</code>```

But overall, it just seems bulkier and less convenient. So, is there any way I could achieve the same result while using variable templates? If not, why is it impossible for the compiler to "forward" the parameters to the aliased function and thus deduce the variadic types?

答:
A wrapper is needed:

```<code>#include <utility>

template<typename T, typename... Args>
void foo(const Args &&... args)
{
    //...
}

template<typename ...Args>
inline void fooChar(const Args && ...args)
{
    foo<char>(std::forward<Args>(args)...);
}
</code>```

Hopefully, your compiler will optimize away the function call.

Body:
Consider the following code:

template<typename T, typename... Args>
void foo(const Args&... args)
{
    //...
}

template<typename... Args>
auto fooChar = foo<char, Args...>;

template<typename... Args>
auto fooInt = foo<int, Args...>;

To be able to make use of these variable templates, I need to explicitely type the template parameters, like so:

fooChar<int, char, const char*>(5, 'a', "bar");

However, in a standard variadic function call, the template parameters are implicitely deduced based on the actual function parameters type. In other words, I would like to be able to use the variable templates like so, but the extra level of indirection seems to restrict this:

fooChar(5, 'a', "bar");

Obviously, I could simply define simple wrapper functions instead of variable templates, like so:

template<typename... Args>
void fooChar(const Args&... args)
{
    return foo<char>(args...);
}

template<typename... Args>
void fooInt(const Args&... args)
{
    return foo<int>(args...);
}

But overall, it just seems bulkier and less convenient. So, is there any way I could achieve the same result while using variable templates? If not, why is it impossible for the compiler to "forward" the parameters to the aliased function and thus deduce the variadic types?

Body:
A wrapper is needed:

#include <utility>

template<typename T, typename... Args>
void foo(const Args &&... args)
{
    //...
}

template<typename ...Args>
inline void fooChar(const Args && ...args)
{
    foo<char>(std::forward<Args>(args)...);
}

Hopefully, your compiler will optimize away the function call.


问:
Excel 2013 Decimal Point converts into Comma in another PC
I am having problems recently with Excel 2013.I want decimal point instead of comma.
I have in the cell written 5.75. I send the Excel file via email and the receiver gets 5,75. But if the receiver send it to me like this with comma, I get in my excel shown 5.75. Where can the Problem be?

P.S I have checked in Advanced, Use System separator.

答:
This is "by design" Excel uses the Windows Locale settings asa set in Windows Control panel, Reion and language to decide what decimal and thousands separators to use.

These can be overridden in Excel's options. This however is an Excel-wide setting (not a per-workbook setting) so I would not advise to change it, otherwise you will confuse your users enormously.


问:
Visual Studio Adding Service Reference without internet connection?
How do i add a Service Reference without internet connection or copy it from one project to another?</p>

答:
If you get WSDL of service. You can add service reference from a file using WSDL provided.

Please see:
How to generate service reference with only physical wsdl file


问:
Get vendor name of SCSI
How can I get the vendor name of SCSI device on linux & c? </p>

答:
You could look into reading /sys files if you know the device/bus id, also check lsscsi.</p>

```<code>  -> cat /sys/bus/scsi/devices/target13:0:0/13:0:0:0/vendor
Marvell
</code>```

Title: Get vendor name of SCSI

Body:
You could look into reading /sys files if you know the device/bus id, also check lsscsi.

  -> cat /sys/bus/scsi/devices/target13:0:0/13:0:0:0/vendor
Marvell


问:
AutoIt _IsPressed not woking in loop
I am having trouble with the following code. I am trying to have the loop bail and go to a Setup() Function if the TAB key is pressed. However when I press TAB nothing happens, it just continues the loop, please help!</p>

```<code>While -1
    While -1
        WinActivate($PID)
        Sleep(1000)
        Send("Hello")
        $timer = TimerInit()
        While -1
            PixelSearch($searchL,$searchT,$searchR,$searchB,"0x" & Hex($color,6),10,1)
--->        If _IsPressed("09",$dll) Then ExitLoop 3 ;HERE IS THE CODE THAT IS NOT WORKING
            If @error <> 1 Then ExitLoop
            If TimerDiff($timer) > 1000 Then
                Sleep(1000)
                WinActivate($PID)
                ExitLoop 2
            EndIf
        Wend
        $timer = TimerInit()
        MouseMove($shade[0], $shade[1])
        While -1
            PixelSearch($shade[0]-10,$shade[1]-10,$shade[0]+10,$shade[1]+10,"0x" & Hex($color,6),10,1)
--->        If _IsPressed("09",$dll) Then ExitLoop 3 ;HERE IS THE CODE THAT IS NOT WORKING
            If @error = 1 Then ExitLoop
            If TimerDiff($timer) > 5000 Then
                Sleep(1000)
                WinActivate($PID)
                Exitloop 2
            EndIf
         Wend
    Wend
 Wend
Setup()
EndFunc
</code>```

答:
I assume you are having a problem with the $dll variable. It's probably not initialised. Just get rid of it. This little example works just fine:

```<code>#include <Misc.au3>

MsgBox( 0, "1 loop", "Now testing with 1 loop." )
While -1
    If _IsPressed("09") Then
        MsgBox( 0, "_IsPressed", "You pressed the TAB key." )
        ExitLoop
    EndIf
WEnd

MsgBox( 0, "3 loops", "Now testing with 3 loops." )
While -1
    While -1
        While -1
            If _IsPressed("09") Then
                MsgBox( 0, "_IsPressed", "You pressed the TAB key." )
                ExitLoop 3
            EndIf
        WEnd
    WEnd
WEnd

MsgBox( 0, "_IsPressed", "Test done." )
</code>```

Title: AutoIt _IsPressed not woking in loop

Body:
I am having trouble with the following code. I am trying to have the loop bail and go to a Setup() Function if the TAB key is pressed. However when I press TAB nothing happens, it just continues the loop, please help!

While -1
    While -1
        WinActivate($PID)
        Sleep(1000)
        Send("Hello")
        $timer = TimerInit()
        While -1
            PixelSearch($searchL,$searchT,$searchR,$searchB,"0x" & Hex($color,6),10,1)
--->        If _IsPressed("09",$dll) Then ExitLoop 3 ;HERE IS THE CODE THAT IS NOT WORKING
            If @error <> 1 Then ExitLoop
            If TimerDiff($timer) > 1000 Then
                Sleep(1000)
                WinActivate($PID)
                ExitLoop 2
            EndIf
        Wend
        $timer = TimerInit()
        MouseMove($shade[0], $shade[1])
        While -1
            PixelSearch($shade[0]-10,$shade[1]-10,$shade[0]+10,$shade[1]+10,"0x" & Hex($color,6),10,1)
--->        If _IsPressed("09",$dll) Then ExitLoop 3 ;HERE IS THE CODE THAT IS NOT WORKING
            If @error = 1 Then ExitLoop
            If TimerDiff($timer) > 5000 Then
                Sleep(1000)
                WinActivate($PID)
                Exitloop 2
            EndIf
         Wend
    Wend
 Wend
Setup()
EndFunc

Body:
I assume you are having a problem with the $dll variable. It's probably not initialised. Just get rid of it. This little example works just fine:

#include <Misc.au3>

MsgBox( 0, "1 loop", "Now testing with 1 loop." )
While -1
    If _IsPressed("09") Then
        MsgBox( 0, "_IsPressed", "You pressed the TAB key." )
        ExitLoop
    EndIf
WEnd

MsgBox( 0, "3 loops", "Now testing with 3 loops." )
While -1
    While -1
        While -1
            If _IsPressed("09") Then
                MsgBox( 0, "_IsPressed", "You pressed the TAB key." )
                ExitLoop 3
            EndIf
        WEnd
    WEnd
WEnd

MsgBox( 0, "_IsPressed", "Test done." )


答:
```<code>{{ "%.2f"|format(19.796) }}
</code>```

as a very basic approach... :)
prints out
    19.80

Title: How to round money in Twig to save zero in the end?

Body: For example I have 19.796 and I need to round it up  so I use it like this {% set final_sum = sum + (sum / 100 * 21) | number_format(2, 'ceil') %} and it returns me 19.8 but I need 19.80 with zero on the end.

Body:
{{ "%.2f"|format(19.796) }}

as a very basic approach... :)
prints out
    19.80


问:
war file not deploying in Tomcat
I have a war file which i want to deploy in my system on tomcat .What I've so far is
1.Shutdown my tomcat from cmd.

2.Set environment variables "C:\Program Files\Java\jdk1.7.0_51" and "%CATALINA_HOME%/bin" .

3.Set appBase="webapps" ,autoDeploy="true", name="localhost", unpackWARs="true"
in server.xml .

4.Copy the war file into "C:\apache-tomcat-7.0.77\webapps\MyProject" .

5.Restart tomcat using cmd.

```<code>                        After doing all this steps the log I got from catalina.log is
</code>```

"INFO: Deploying web application directory C:\apache-tomcat-7.0.77\webapps\MyProject
Jun 07, 2017 4:50:19 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\apache-tomcat-7.0.77\webapps\MyProject has finished in 188 ms
Jun 07, 2017 4:50:19 PM org.apache.catalina.startup.HostConfig deployDirectory"

```<code>                       It seems like MyProject is deployed without any error but when I try to access it using the url http://localhost:8084/MyProject/ the browser shows
</code>```

HTTP Status 404 - /MyProject/

type Status report

message /MyProject/

description The requested resource is not available.

Apache Tomcat/7.0.77
                            My tomcat is running fine when i go to the url http://localhost:8084(8080 is the default port of tomcat but i changed it to 8084)

答:
4.Copy the war file into "C:\apache-tomcat-7.0.77\webapps\MyProject" .

You should put your war file to C:\apache-tomcat-7.0.77\webapps\ instead.

Tomcat will then automatically unpack (into a directory named after a war file) and deploy it.

If you create a webapp sub-folder yourself, Tomcat thinks that it is an already unpacked webapp (with a single .war binary file inside it), and deploys it, but as it is virtually empty (aside the .war archive file), you get 404 while trying to access it.

Title: war file not deploying in Tomcat

Body:
I have a war file which i want to deploy in my system on tomcat .What I've so far is
1.Shutdown my tomcat from cmd.

2.Set environment variables "C:\Program Files\Java\jdk1.7.0_51" and "%CATALINA_HOME%/bin" .

3.Set appBase="webapps" ,autoDeploy="true", name="localhost", unpackWARs="true"
in server.xml .

4.Copy the war file into "C:\apache-tomcat-7.0.77\webapps\MyProject" .

5.Restart tomcat using cmd.

                        After doing all this steps the log I got from catalina.log is

"INFO: Deploying web application directory C:\apache-tomcat-7.0.77\webapps\MyProject
Jun 07, 2017 4:50:19 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\apache-tomcat-7.0.77\webapps\MyProject has finished in 188 ms
Jun 07, 2017 4:50:19 PM org.apache.catalina.startup.HostConfig deployDirectory"

                       It seems like MyProject is deployed without any error but when I try to access it using the url http://localhost:8084/MyProject/ the browser shows

HTTP Status 404 - /MyProject/

type Status report

message /MyProject/

description The requested resource is not available.

Apache Tomcat/7.0.77
                            My tomcat is running fine when i go to the url http://localhost:8084(8080 is the default port of tomcat but i changed it to 8084)


问:
Using HTML in Express instead of Jade
How to I get rid of Jade while using Express with Node.JS? I want to just use plain html. In other articles I have seen that people recommended app.register() which is now deprecated in the latest version.</p>

答:
You can also directly include your html file into your jade file

```<code>include ../../public/index.html
</code>```

Original answer: Express Generator Without Jade

Title: Using HTML in Express instead of Jade

Body:
You can also directly include your html file into your jade file

include ../../public/index.html

Original answer: Express Generator Without Jade


问:
Too few parameters: the query defines 1 parameters but you only bound 0
Symfony Version 3.2.8

I am unsure what is causing this error, according to Doctrine Documentation the setParameter function is being used correctly?

Broken Code:

```<code>public function getNewShipChoices($uid, $fid) {
        /*Identify ships all ready added in fleet and do not allow them to be added again*/
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = :uid')->setParameter('uid', $uid)
                    ->andWhere('c2.fleetId = :fid')->setParameter('fid', $fid);

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = :uid')->setParameter('uid', $uid);

        return $query->getQuery()->getResult();
    }
</code>```

Another thing I tried was to hard code the setParameter values, which brings the same error message

```<code> ->where('c.userid = :uid')->setParameter('uid', 1)
                            ->andWhere('c2.fleetId = :fid')->setParameter('fid', 1);
</code>```

Working Code:
Replacing the setParameter with hard coded values instead of passing in 2 integer values of 1 and 1 works fine.

```<code> public function getNewShipChoices($uid, $fid) {
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = 1')
                    ->andWhere('c2.fleetId = 1');

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = 1');

        return $query->getQuery()->getResult();
    }
</code>```

Did I miss something completely obvious?

答:
Try this adding single quotes to '1'.</p>

```<code>->where('c.userid = :uid')->setParameter('uid', '1')
                        ->andWhere('c2.fleetId = :fid')->setParameter('fid', '1');
</code>```

Body:
Symfony Version 3.2.8

I am unsure what is causing this error, according to Doctrine Documentation the setParameter function is being used correctly?

Broken Code:

public function getNewShipChoices($uid, $fid) {
        /*Identify ships all ready added in fleet and do not allow them to be added again*/
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = :uid')->setParameter('uid', $uid)
                    ->andWhere('c2.fleetId = :fid')->setParameter('fid', $fid);

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = :uid')->setParameter('uid', $uid);

        return $query->getQuery()->getResult();
    }

Another thing I tried was to hard code the setParameter values, which brings the same error message

 ->where('c.userid = :uid')->setParameter('uid', 1)
                            ->andWhere('c2.fleetId = :fid')->setParameter('fid', 1);

Working Code:
Replacing the setParameter with hard coded values instead of passing in 2 integer values of 1 and 1 works fine.

 public function getNewShipChoices($uid, $fid) {
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = 1')
                    ->andWhere('c2.fleetId = 1');

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = 1');

        return $query->getQuery()->getResult();
    }

Did I miss something completely obvious?

Body:
Try this adding single quotes to '1'.

->where('c.userid = :uid')->setParameter('uid', '1')
                        ->andWhere('c2.fleetId = :fid')->setParameter('fid', '1');


问:
OjAlgo How to map / update all the values in PrimitiveDenseStore?
Say I have an 2x2 matrix as PrimitiveDenseStore

```<code>pstore = [ 1 2
           3 4 ]
</code>```

Is there anyway to map all these values based on given anonymous function like

```<code>pstore.map(x -> x * x)
</code>```

So the result is

```<code>pstore = [ 1 4
           9 16 ]
</code>```

答:
Okay I was confused with java's UnaryOperator turns out ojAlgo expects its own Functional Interface PrimitiveFunction.Unary

```<code>PrimitiveFunction.Unary square = arg -> arg * arg;
pstore.modifyAll(square);
</code>```

Body:
Say I have an 2x2 matrix as PrimitiveDenseStore

pstore = [ 1 2
           3 4 ]

Is there anyway to map all these values based on given anonymous function like

pstore.map(x -> x * x)

So the result is

pstore = [ 1 4
           9 16 ]

Body:
Okay I was confused with java's UnaryOperator turns out ojAlgo expects its own Functional Interface PrimitiveFunction.Unary

PrimitiveFunction.Unary square = arg -> arg * arg;
pstore.modifyAll(square);


问:
Convert & sort javascript array numerically using non-numeric key
I have a JS array in following structure:

```<code>Array(
    [0] => Array(
        reference : "8926"
        name : "xyz1"
        id_product : "78"
    )
    [1] => Array(
        reference : "11588"
        name : "xyz2"
        id_product : "21"
    )
    [2] => Array(
        reference : "119"
        name : "xyz3"
        id_product : "135"
    )
)
</code>```

I needed to sort this array using the reference key, I have done it using multisort function;

But the problem is : even though reference is numeric but in the array structure it is defined as string and hence instead of sorting like:
119, 8926, 11588 it is sorting it like 11588 119 8926, i.e., like string.

I cannot re-structure the array because I receive it through an API, is there anyway to sort it numerically without having to recreate it in numeric data type separately (because I have to pass the array forward in same format & hence double-conversion will make the script hectic)?

PS - Current sorting (non-numeric) is done using this function.

答:
Try this: </p>

```<code>let a = new Array(
    {
        reference : "8926",
        name : "xyz1",
        id_product : "78"
    },
    {
        reference : "11588",
        name : "xyz2",
        id_product : "21"
    },
    {
        reference : "119",
        name : "xyz3",
        id_product : "135"
    }
);

a.sort((a, b) => {
  return Number(a.reference) - Number(b.reference);
});
</code>```

Body:
I have a JS array in following structure:

Array(
    [0] => Array(
        reference : "8926"
        name : "xyz1"
        id_product : "78"
    )
    [1] => Array(
        reference : "11588"
        name : "xyz2"
        id_product : "21"
    )
    [2] => Array(
        reference : "119"
        name : "xyz3"
        id_product : "135"
    )
)

I needed to sort this array using the reference key, I have done it using multisort function;

But the problem is : even though reference is numeric but in the array structure it is defined as string and hence instead of sorting like:
119, 8926, 11588 it is sorting it like 11588 119 8926, i.e., like string.

I cannot re-structure the array because I receive it through an API, is there anyway to sort it numerically without having to recreate it in numeric data type separately (because I have to pass the array forward in same format & hence double-conversion will make the script hectic)?

PS - Current sorting (non-numeric) is done using this function.

Body:
Try this:

let a = new Array(
    {
        reference : "8926",
        name : "xyz1",
        id_product : "78"
    },
    {
        reference : "11588",
        name : "xyz2",
        id_product : "21"
    },
    {
        reference : "119",
        name : "xyz3",
        id_product : "135"
    }
);

a.sort((a, b) => {
  return Number(a.reference) - Number(b.reference);
});


问:
mailto: unable to add attachments
I have an HTML link. I'm using mailto to open up the mail when a user clicks on the link.
I'm able to set the to email id and subject but I'm not able to add an attachment.

This particular form is now in localhost but it will be moved to live server later. These attachment files are stored in a folder and I get the path to these files from a PHP variable.

I tried passing the path to it but it didn't add the attachment.

How can I make this happen?

Here's the sample code.

```<code>$filePath = 'C:\xampp\htdocs\sampleProject\attachments\pdfs\samplepdf-03.pdf'

<a href="mailto:?subject=Pictures from PhotoAlbum
         &body=This is the body text
         &attachment='<?php echo $filePath; ?>'">
Email This
</a>
</code>```

答:
You can't. The mailto: URI scheme doesn't support attachments (and the client wouldn't usually have access to the web server's hard disk anyway).

Consider sending the email from your PHP instead of from your visitor's email client.

Title: mailto: unable to add attachments

Body:
I have an HTML link. I'm using mailto to open up the mail when a user clicks on the link.
I'm able to set the to email id and subject but I'm not able to add an attachment.

This particular form is now in localhost but it will be moved to live server later. These attachment files are stored in a folder and I get the path to these files from a PHP variable.

I tried passing the path to it but it didn't add the attachment.

How can I make this happen?

Here's the sample code.

$filePath = 'C:\xampp\htdocs\sampleProject\attachments\pdfs\samplepdf-03.pdf'

<a href="mailto:?subject=Pictures from PhotoAlbum
         &body=This is the body text
         &attachment='<?php echo $filePath; ?>'">
Email This