问:
Javascript Loop for same commands
I am trying to figure out how to loop this instead of 6 seperate versions of this. It's obviously redundant code. I would have no issues doing this in PHP.

I would like to keep this purely JS.

```<code>    function p1Name() {
    document.getElementById('p1_name_1').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_2').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_3').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_4').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_5').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_6').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_7').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
}
</code>```

This same function gets repeated 6 times.
p1, p2, p3, p4, p5, p6

答:
Working off the answer by Keiwan... the function would still need to be called several times... you can access object properties such as scorecard.p1 as scorecard["p1"]. So, to call it just once.

```<code>function pName(px) {
  for (var i = 1; i <= 7; i++) {
    document.getElementById(px + '_name_' + i).innerHTML = (scorecard[px][scorecard[px].selectedIndex].text);
  }
}
</code>```

That's provided that px is fed in as a string.

Title: Javascript Loop for same commands

Body:
I am trying to figure out how to loop this instead of 6 seperate versions of this. It's obviously redundant code. I would have no issues doing this in PHP.

I would like to keep this purely JS.

    function p1Name() {
    document.getElementById('p1_name_1').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_2').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_3').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_4').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_5').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_6').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_7').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
}

This same function gets repeated 6 times.
p1, p2, p3, p4, p5, p6

Body:
Working off the answer by Keiwan... the function would still need to be called several times... you can access object properties such as scorecard.p1 as scorecard["p1"]. So, to call it just once.

function pName(px) {
  for (var i = 1; i <= 7; i++) {
    document.getElementById(px + '_name_' + i).innerHTML = (scorecard[px][scorecard[px].selectedIndex].text);
  }
}

That's provided that px is fed in as a string.


来源: stackexchange

问:
Javascript return illegal statement
```<code>if(choice1 === choice2) {
return"The result is a tie!";
</code>```

}

else if (choice1 === "rock") {

```<code>if (choice2 === "scissors") {
    return "rock wins";

}
else {
    return "paper wins";
}
</code>```

}

please help mee

答:
A return statement returns control to the calling context. In the case of global code, there is no calling context to return to, so they are illegal there. They are part of the production for FunctionDeclaration, so you can only use them inside functions.

To get to the relevant parts of ECMA-262, start with §14.1 Function Definitions, one of which is FunctionDeclaration which consists of, among other things, a FunctionBody, which is made up of a FunctionStatementList, which contains a StatementList. Now that is made up (surprisingly) of zero or more StatementListItems which are Statements, and one type of statement is ReturnStatement, which is described in §13.10.

So return statements can only appear in function bodies, and function bodies can only appear in code that is a FunctionDeclaration, FunctionExpression or ArrowFunction. So from that it can be stated more generally that return statements can only appear inside functions.

ContentLicense: CC BY-SA 3.0

Title: Javascript return illegal statement

Body:
if(choice1 === choice2) {
return"The result is a tie!";

}

else if (choice1 === "rock") {

if (choice2 === "scissors") {
    return "rock wins";

}
else {
    return "paper wins";
}

}

please help mee


问:
Java Downcasting of extending class
Why this code is not working? When i casting, I get ClassCastExeption
Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B
    at HelloWorld.main</p>

```<code>public class HelloWorld
{
 public static void main(String[] args)
  {
    B b1 = (B)new A();
    b1.a();
   }
}

public class A
{
  public void a (){
  System.out.println("A.a");
  }
  public void b (){
  System.out.println("A.b");
  }
}

public class B extends A{
}
</code>```

答:
Casting can't always be done in both ways.

If you are creating an Animal, by calling "new Animal()", you are creating an Object that is an Animal, but it cannot be downcasted to Dog. Because it's not a dog.

However when you create a Dog by calling "new Dog()", then you can upcast it to "Animal" and downcast it back to "Dog".

```<code>Dog dog = new Dog();
Animal animal = dog;         //upcasting to Animal
if(animal instanceof Dog){ // testing if the Animal is a Dog
    Dog dog2 = (Dog) animal; //downcast
}
</code>```

Title: Java Downcasting of extending class

Body:
Why this code is not working? When i casting, I get ClassCastExeption
Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B
    at HelloWorld.main

public class HelloWorld
{
 public static void main(String[] args)
  {
    B b1 = (B)new A();
    b1.a();
   }
}

public class A
{
  public void a (){
  System.out.println("A.a");
  }
  public void b (){
  System.out.println("A.b");
  }
}

public class B extends A{
}

Body:
Casting can't always be done in both ways.

If you are creating an Animal, by calling "new Animal()", you are creating an Object that is an Animal, but it cannot be downcasted to Dog. Because it's not a dog.

However when you create a Dog by calling "new Dog()", then you can upcast it to "Animal" and downcast it back to "Dog".

Dog dog = new Dog();
Animal animal = dog;         //upcasting to Animal
if(animal instanceof Dog){ // testing if the Animal is a Dog
    Dog dog2 = (Dog) animal; //downcast
}


问:
CSS: background-color on section tag doesn't cover full width?
Foremost there are a lot of posts relating to background-color. I have read several and have tried various solutions posted there from setting background-size to making overflow hidden. Nothing seems to work....
How can I get background-color to cover the whole section?

I have a very simple M.W.E. below:

html

```<code><body>
<section>
  TEST!
</section>
</body>
</code>```

css

```<code>body {
  background-color: coral;
}

section {
  background-color: blue;
  width: 100%;
}
</code>```

Fiddle

答:
You need to use margin:auto on body tag

snippet below

body {
  background-color: coral;
  margin:auto;
}

section {
  background-color: blue;
  width: 100%;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<section>
  TEST!
</section>
</body></code>```

Body:
Foremost there are a lot of posts relating to background-color. I have read several and have tried various solutions posted there from setting background-size to making overflow hidden. Nothing seems to work....
How can I get background-color to cover the whole section?

I have a very simple M.W.E. below:

html

  TEST!

css

body {
  background-color: coral;
}

section {
  background-color: blue;
  width: 100%;
}

Fiddle

Body:
You need to use margin:auto on body tag

snippet below

body {
  background-color: coral;
  margin:auto;
}

section {
  background-color: blue;
  width: 100%;

}

<body>
<section>
  TEST!
</section>
</body>


问:
Very slow postgresql query with deep hierarchy
I have a query where I want to get all transactions for a specific user(owner table) in my database. The database is pretty normalized, so getting from transaction to owner traverses many tables. My tables with relevant foreign keys are as follows:

```<code>**owners**
-------
id

**store_shops**
-----------
id
owner_id

**service_shops**
-------------
id
owner_id

**products**
-------------
id
store_shop_id

**services**
------------
id
service_shop_id

**order_services**
------------------
id
service_id
order_id

**order_products**
------------------
id
product_id
order_id

**orders**
----------
id
transaction_id

**transactions**
----------------
id
refund_transaction_id
amount
</code>```

I have the following query:

```<code>SELECT DISTINCT ON (sales.id) sales.id, sales.amount FROM transactions sales
LEFT OUTER JOIN transactions refunds ON refunds.id = sales.refund_transaction_id
LEFT OUTER JOIN orders ON orders.transaction_id = trans.id OR orders.transaction_id = refunds.id
LEFT OUTER JOIN order_services ON order_services.order_id = orders.id
LEFT OUTER JOIN order_products ON order_products.order_id = orders.id
LEFT OUTER JOIN products ON  products.id = order_products.product_id
LEFT OUTER JOIN services ON services.id = order_services.service_id
LEFT OUTER JOIN service_shops ON service_shops.id = services.service_shop_id
LEFT OUTER JOIN store_shops ON store_shops.id = products.store_shop_id
LEFT OUTER JOIN owners service_shop_owners ON service_shop_owners.id = service_shops.owner_id
LEFT OUTER JOIN owners store_shop_owners ON store_shop_owners.id = store_shops.owner_id
WHERE (service_shop_owners.id = 26930 OR store_shop_owners.id = 26930)
</code>```

This gives me the desired results. Only trouble is that on a dataset of hundreds of thousands of records, it becomes unusably slow.

I'm not very advanced when it comes to SQL, but I realize all the LEFT OUTER JOINs isn't very efficient.

Is there a better way for me to handle this query? Or am I going to have to denormalize the database a bit and store more info in the transaction table?

UPDATE
Using Wyzard's answer below, I now have this query:

```<code>SELECT trans.id, trans.amount, refunds.id
FROM
  service_shops
  JOIN services ON services.service_shop_id = service_shop.id
  JOIN order_services ON order_services.service_id = services_id
  JOIN orders ON orders.id = order_services.order_id
  JOIN transactions trans ON trans.id = orders.transaction_id
  LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id
WHERE service_shops.owner_id = 26930
UNION
SELECT trans.id, trans.amount, refunds.id
FROM
  store_shops
  JOIN products ON store_shops.id = products.store_shop_id
  JOIN order_products ON order_products.product_id = products.id
  JOIN orders ON orders.id = order_products.order_id
  JOIN transactions trans ON trans.id = orders.transaction_id
  LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id
WHERE store_shops.owner_id = 2693
</code>```

This is very fast and a big improvement. Only problem now is that the two LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id do not seem to be grabbing associated refund transactions. I'm assuming this is because they do not have an order associated directly with them, so the WHERE clause filters them out.

答:
Change this:

```<code>WHERE (service_shop_owners.id = 26930 OR store_shop_owners.id = 26930)
</code>```

To this:

```<code>WHERE 26930 IN (service_shop_owners.id, store_shop_owners.id)
</code>```

Using OR usually means the index won't be used, but it should be used with the IN.

The above change should be enough to make a big difference. To further improve thecquery, reverse the order of the tables, especially list service_shop_owners as the first table in the FROM clause. The optimiser should do this for you, but often it doesn't.

Body:
I have a query where I want to get all transactions for a specific user(owner table) in my database. The database is pretty normalized, so getting from transaction to owner traverses many tables. My tables with relevant foreign keys are as follows:

**owners**
-------
id

**store_shops**
-----------
id
owner_id

**service_shops**
-------------
id
owner_id

**products**
-------------
id
store_shop_id

**services**
------------
id
service_shop_id

**order_services**
------------------
id
service_id
order_id

**order_products**
------------------
id
product_id
order_id

**orders**
----------
id
transaction_id

**transactions**
----------------
id
refund_transaction_id
amount

I have the following query:

SELECT DISTINCT ON (sales.id) sales.id, sales.amount FROM transactions sales
LEFT OUTER JOIN transactions refunds ON refunds.id = sales.refund_transaction_id
LEFT OUTER JOIN orders ON orders.transaction_id = trans.id OR orders.transaction_id = refunds.id
LEFT OUTER JOIN order_services ON order_services.order_id = orders.id
LEFT OUTER JOIN order_products ON order_products.order_id = orders.id
LEFT OUTER JOIN products ON  products.id = order_products.product_id
LEFT OUTER JOIN services ON services.id = order_services.service_id
LEFT OUTER JOIN service_shops ON service_shops.id = services.service_shop_id
LEFT OUTER JOIN store_shops ON store_shops.id = products.store_shop_id
LEFT OUTER JOIN owners service_shop_owners ON service_shop_owners.id = service_shops.owner_id
LEFT OUTER JOIN owners store_shop_owners ON store_shop_owners.id = store_shops.owner_id
WHERE (service_shop_owners.id = 26930 OR store_shop_owners.id = 26930)

This gives me the desired results. Only trouble is that on a dataset of hundreds of thousands of records, it becomes unusably slow.

I'm not very advanced when it comes to SQL, but I realize all the LEFT OUTER JOINs isn't very efficient.

Is there a better way for me to handle this query? Or am I going to have to denormalize the database a bit and store more info in the transaction table?

UPDATE
Using Wyzard's answer below, I now have this query:

SELECT trans.id, trans.amount, refunds.id
FROM
  service_shops
  JOIN services ON services.service_shop_id = service_shop.id
  JOIN order_services ON order_services.service_id = services_id
  JOIN orders ON orders.id = order_services.order_id
  JOIN transactions trans ON trans.id = orders.transaction_id
  LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id
WHERE service_shops.owner_id = 26930
UNION
SELECT trans.id, trans.amount, refunds.id
FROM
  store_shops
  JOIN products ON store_shops.id = products.store_shop_id
  JOIN order_products ON order_products.product_id = products.id
  JOIN orders ON orders.id = order_products.order_id
  JOIN transactions trans ON trans.id = orders.transaction_id
  LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id
WHERE store_shops.owner_id = 2693

This is very fast and a big improvement. Only problem now is that the two LEFT JOIN transactions refunds ON refunds.id = trans.refund_transaction_id do not seem to be grabbing associated refund transactions. I'm assuming this is because they do not have an order associated directly with them, so the WHERE clause filters them out.

Body:
Change this:

WHERE (service_shop_owners.id = 26930 OR store_shop_owners.id = 26930)

To this:

WHERE 26930 IN (service_shop_owners.id, store_shop_owners.id)

Using OR usually means the index won't be used, but it should be used with the IN.

The above change should be enough to make a big difference. To further improve thecquery, reverse the order of the tables, especially list service_shop_owners as the first table in the FROM clause. The optimiser should do this for you, but often it doesn't.


问:
How to find out if a cookie is already there?
So I do simple JS function like

```<code>function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

}
</code>```

how tm make sure that users_resolution is set?

答:
If you just do

```<code>var cookies = document.cookie;
</code>```

then the string cookies will contain a semicolon-separated list of cookie name-value pairs.  You can split the string on ";" and loop through the results, checking for the presence of your cookie name.

ContentLicense: CC BY-SA 2.5

Body:
So I do simple JS function like

function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

}

how tm make sure that users_resolution is set?

Body:
If you just do

var cookies = document.cookie;

then the string cookies will contain a semicolon-separated list of cookie name-value pairs.  You can split the string on ";" and loop through the results, checking for the presence of your cookie name.


问:
Comparing 2 arrays for equal elements and deleting the entries from both arrays
Suppose i have 2 numpy arrays which have elements like these:

```<code>arr1 = [[1, 2], [3, 5], [3, 4]]
arr2 = [[2, 3], [3, 4], [6, 6]]
</code>```

I want the resultant array to have arr2 appended or horizontally stacked to
 arr1 containing the elements which are NOT present in both the arrays:

```<code>arr3 = [[1, 2], [3, 5], [2, 3], [6, 6]]
</code>```

As you can see, [3, 4] is not there in the expected resultant array. What is the best numpy and pythonic implementation for this?

答:
```<code>arr_3 = list(set(arr_1).symmetric_difference(set(arr_2)))
</code>```

or:

```<code>arr_3 = list(set(map(tuple, arr_1))
    .symmetric_difference(set(map(tuple, arr_2))))
</code>```

A little research:

```<code>from random import randint
from timeit import timeit

import itertools

arr1 = [[randint(0, 5), randint(0, 5)] for _ in range(1000)]
arr2 = [[randint(0, 5), randint(0, 5)] for _ in range(1000)]

def symmetric_difference(a, b):
    now_exists = set()
    results = []
    for e in itertools.chain(a, b):
        rerp_of_e = repr(e)
        if rerp_of_e not in now_exists:
            now_exists.add(rerp_of_e)
            results.append(e)

    return results

def method2(a, b):
    c = a + b
    return [l for l in c if c.count(l) == 1]

print(timeit('[l for l in arr1 + arr2 if (arr1 + arr2).count(l) == 1]', 'from __main__ import arr1, arr2',
             number=10) / 10)

print(timeit('method2(arr1, arr2)', 'from __main__ import arr1, arr2, method2',
             number=10) / 10)

print(timeit('list(set(map(tuple, arr1)).symmetric_difference(set(map(tuple, arr2))))',
             'from __main__ import arr1, arr2', number=10) / 10)

print(timeit('symmetric_difference(arr1, arr2)', 'from __main__ import arr1, arr2, symmetric_difference',
             number=10) / 10)
</code>```

Output:

```<code>0.16653713929933542
0.14676828165012284
0.00030277483018301685
0.0008909022958581315
</code>```

Body:
Suppose i have 2 numpy arrays which have elements like these:

arr1 = [[1, 2], [3, 5], [3, 4]]
arr2 = [[2, 3], [3, 4], [6, 6]]

I want the resultant array to have arr2 appended or horizontally stacked to
 arr1 containing the elements which are NOT present in both the arrays:

arr3 = [[1, 2], [3, 5], [2, 3], [6, 6]]

As you can see, [3, 4] is not there in the expected resultant array. What is the best numpy and pythonic implementation for this?

Body:
arr_3 = list(set(arr_1).symmetric_difference(set(arr_2)))

or:

arr_3 = list(set(map(tuple, arr_1))
    .symmetric_difference(set(map(tuple, arr_2))))

A little research:

from random import randint
from timeit import timeit

import itertools

arr1 = [[randint(0, 5), randint(0, 5)] for _ in range(1000)]
arr2 = [[randint(0, 5), randint(0, 5)] for _ in range(1000)]

def symmetric_difference(a, b):
    now_exists = set()
    results = []
    for e in itertools.chain(a, b):
        rerp_of_e = repr(e)
        if rerp_of_e not in now_exists:
            now_exists.add(rerp_of_e)
            results.append(e)

    return results

def method2(a, b):
    c = a + b
    return [l for l in c if c.count(l) == 1]

print(timeit('[l for l in arr1 + arr2 if (arr1 + arr2).count(l) == 1]', 'from __main__ import arr1, arr2',
             number=10) / 10)

print(timeit('method2(arr1, arr2)', 'from __main__ import arr1, arr2, method2',
             number=10) / 10)

print(timeit('list(set(map(tuple, arr1)).symmetric_difference(set(map(tuple, arr2))))',
             'from __main__ import arr1, arr2', number=10) / 10)

print(timeit('symmetric_difference(arr1, arr2)', 'from __main__ import arr1, arr2, symmetric_difference',
             number=10) / 10)

Output:

0.16653713929933542
0.14676828165012284
0.00030277483018301685
0.0008909022958581315


问:
How to properly override mouse events in other apps (Windows)?
I'm trying to implement system-wide drag operation with middle mouse button. It should override middle mouse drag behavior in other programs. Currently, I am handling global mouse events with system-wide hooks.

Problem is - many programs still receive and handle same events like I did not intercept them.

Here's what I tried:

not call the next hook for mouse down event: I never receive mouse up, so I don't know where and when to stop dragging

not call the next hook for mouse move: cursor slows down tremendously

not call the next hook for mouse up: most windows in the system stop reacting to mouse events completely after my drag is finished

always call the next hook in the chain: if the control under mouse has scroll in it, most of the time it will be scrolling while my drag is in progress. Also UWP apps continue receiving mouse events during my drag, so if a link in MS Edge happens to be under cursor when it started, and mouse does not leave Edge boundary, Edge receives click event, and new tab is opened

What I need is: when user holds middle mouse and starts dragging, my drag handler should be called, and no other handlers, like file drag, scroll, etc should happen.

答:
I ended up with somewhat hacky solution:

do not call the next hook for mouse down for middle button

record where it was pressed

when handling mouse up, if user did not drag - replay the whole mouse up + mouse down using SendInput from a separate thread (to avoid deadlock due to reentrancy)


问:
Matplotlib interactive widget from python script
I am adapting this example to interact with a plot using matplotlib's widgets.
The way I normally work is interactive, from within spyder I just call a function that does the plotting.
My goal is to make an executable available to users who do not have Python installed, so as an intermediate step I am wrapping the functions into a script.
I have minimal experience with standalone scripts, so in a nutshell mine looks like this:

```<code>import various_modules
def plotting()
    ...
    plot_some_initial_stuff
    sl = Slider()
    plt.show()                <-------
    def update()
       ...
       ax.set_ydata()
       fig.canvas.draw_idle()
    sl.on_change(update)
    return()
plotting()
</code>```

So I just define the plotting function and then call it.
I had to add the plt.show() command, which I do not need to have when I'm working from the IPython shell, otherwise doing:

```<code>python my_plot.py
</code>```

would not produce anything. By adding plt.show(), the window shows up with the graphs I define in the initialization part. However, no interaction happens.

What is the correct way of achieving interaction when running a script like I'm doing?

答:
Although I do not know all the details, I learnt that:

the default mode for script is non-interactive

this means that

no plot is generated until show() is called

the execution of the script does not proceed after the statement

Therefore, my call to show() was too early and actually blocked the definition of the update function and its connection to the slider.on_change() event.

It has been enough to move show() to the last line of the function definition to obtain the desired behaviour.

Body:
I am adapting this example to interact with a plot using matplotlib's widgets.
The way I normally work is interactive, from within spyder I just call a function that does the plotting.
My goal is to make an executable available to users who do not have Python installed, so as an intermediate step I am wrapping the functions into a script.
I have minimal experience with standalone scripts, so in a nutshell mine looks like this:

import various_modules
def plotting()
    ...
    plot_some_initial_stuff
    sl = Slider()
    plt.show()                <-------
    def update()
       ...
       ax.set_ydata()
       fig.canvas.draw_idle()
    sl.on_change(update)
    return()
plotting()

So I just define the plotting function and then call it.
I had to add the plt.show() command, which I do not need to have when I'm working from the IPython shell, otherwise doing:

python my_plot.py

would not produce anything. By adding plt.show(), the window shows up with the graphs I define in the initialization part. However, no interaction happens.

What is the correct way of achieving interaction when running a script like I'm doing?


答:
There is a default margin on the body element, so you should always add this rule:

```<code>body, html {
  margin: 0;
}
</code>```

Here it is applied to your example: https://jsfiddle.net/93669xwh/

Title: CSS: background-color on section tag doesn't cover full width?

Body:
There is a default margin on the body element, so you should always add this rule:

body, html {
  margin: 0;
}

Here it is applied to your example: https://jsfiddle.net/93669xwh/


问:
How can I protect a logging object from the garbage collector in a multiprocessing process?
I create a couple of worker processes using Python's Multiprocessing module 2.6.
In each worker I use the standard logging module (with log rotation and file per worker)
to keep an eye on the worker. I've noticed that after a couple of hours that no more
events are written to the log. The process doesn't appear to crash and still responds
to commands via my queue. Using lsof I can see that the log file is no longer open.
I suspect the log object may be killed by the garbage collector, if so is there a way
that I can mark it to protect it?</p>

答:
I agree with @THC4k. This doesn't seem like a GC issue. I'll give you my reasons why, and I'm sure somebody will vote me down if I'm wrong (if so, please leave a comment pointing out my error!).

If you're using CPython, it primarily uses reference counting, and objects are destroyed immediately when the ref count goes to zero (since 2.0, supplemental garbage collection is also provided to handle the case of circular references). Keep a reference to your log object and it won't be destroyed.

If you're using Jython or IronPython, the underlying VM does the garbage collection. Again, keep a reference and the GC shouldn't touch it.

Either way, it seems that either you're not keeping a reference to an object you need to keep alive, or you have some other error.


问:
Javascript Deep Clone Object with Circular References
I have copied the function below from an existing answer by Dmitriy Pichugin. This function can deep clone an object without any circular references- it works.

```<code>function deepClone( obj ) {
    if( !obj || true == obj ) //this also handles boolean as true and false
        return obj;
    var objType = typeof( obj );
    if( "number" == objType || "string" == objType ) // add your immutables here
        return obj;
    var result = Array.isArray( obj ) ? [] : !obj.constructor ? {} : new obj.constructor();
    if( obj instanceof Map )
        for( var key of obj.keys() )
            result.set( key, deepClone( obj.get( key ) ) );
    for( var key in obj )
    if( obj.hasOwnProperty( key ) )
            result[key] = deepClone( obj[ key ] );
    return result;
}
</code>```

However, my program loops indefinitely and I have realised that this is due to a circular reference.

An example of a circular reference:

```<code>function A() {}
function B() {}

var a = new A();
var b = new B();

a.b = b;
b.a = a;
</code>```

答:
Since object cloning has a lot of pitfalls (circular references, proto chains, Set/Map, etc)

I suggest you to use one of well-tested popular solutions.

Like,  lodash's _.cloneDeep or 'clone' npm module.

Body:
I have copied the function below from an existing answer by Dmitriy Pichugin. This function can deep clone an object without any circular references- it works.

function deepClone( obj ) {
    if( !obj || true == obj ) //this also handles boolean as true and false
        return obj;
    var objType = typeof( obj );
    if( "number" == objType || "string" == objType ) // add your immutables here
        return obj;
    var result = Array.isArray( obj ) ? [] : !obj.constructor ? {} : new obj.constructor();
    if( obj instanceof Map )
        for( var key of obj.keys() )
            result.set( key, deepClone( obj.get( key ) ) );
    for( var key in obj )
    if( obj.hasOwnProperty( key ) )
            result[key] = deepClone( obj[ key ] );
    return result;
}

However, my program loops indefinitely and I have realised that this is due to a circular reference.

An example of a circular reference:

function A() {}
function B() {}

var a = new A();
var b = new B();

a.b = b;
b.a = a;


问:
Runtime Error Error in :0:0 caused by: No provider for StatusBar
I am building my ionic 2 app, and i get this error:

```<code>Runtime Error
Error in :0:0 caused by: No provider for StatusBar!
</code>```

in app.component.ts, I have :

```<code>import { StatusBar } from '@ionic-native/status-bar';
...
@Component({
    templateUrl: 'app.html'
})
export class MyApp {

    pageComponent: any;
    private admobid: any;

    constructor(
          public platform: Platform
        , public statusBar: StatusBar
        ...
</code>```

I don't understand if I have to list all the native plugins in the app.module.ts ?

答:
As the error suggests, you don't have a provider for StatusBar.

Add a provider either in your component,

```<code>@Component({
   .....
   providers: [StatusBar]
})
</code>```

or preferably, in your NgModule

```<code>@NgModule({
   imports: ...
    .......,
   providers: [StatusBar]
})
</code>```

In the latter case, you'll have to add another es6 'import' statement to allow the StatusBar type to be available to be added as a provider in the NgModule

Body:
I am building my ionic 2 app, and i get this error:

Runtime Error
Error in :0:0 caused by: No provider for StatusBar!

in app.component.ts, I have :

import { StatusBar } from '@ionic-native/status-bar';
...
@Component({
    templateUrl: 'app.html'
})
export class MyApp {

    pageComponent: any;
    private admobid: any;

    constructor(
          public platform: Platform
        , public statusBar: StatusBar
        ...

I don't understand if I have to list all the native plugins in the app.module.ts ?

Body:
As the error suggests, you don't have a provider for StatusBar.

Add a provider either in your component,

@Component({
   .....
   providers: [StatusBar]
})

or preferably, in your NgModule

@NgModule({
   imports: ...
    .......,
   providers: [StatusBar]
})

In the latter case, you'll have to add another es6 'import' statement to allow the StatusBar type to be available to be added as a provider in the NgModule


问:
VideoView: how to always show MediaController while playing video
I have a very simple task - just to show playback controls while playing video on VideoView. But I can't solve it.

Here is the piece of code that I use for initializing VideoView and setting MediaController:

```<code>videoView.setVideoURI(Uri.parse(videoUrl));
MediaController mediaController = new MediaController(this);
videoView.setMediaController(mediaController);
videoView.setKeepScreenOn(true);
videoView.setOnPreparedListener(mp -> {
    progress.setVisibility(View.GONE);
    videoView.start();
    mediaController.show(0);
});
</code>```

The thing is that mediaController.show(0) doesn't give any effect. Controls just show up for 3 seconds and then disappear.

Also I have tried to override MediaController's hide() method:

```<code>@Override public void hide() {}
</code>```

Well, it works - controls never hide, but unfortunately hardware 'back' button stops working. Without override hardware 'back' button on first tap close media controls, on second tap - brings user to previous screen, as expected.

Are there any working solutions?

答:
In addition to u2gilles's answer, I encountered that the delay was too short resulting "play" symbol being displayed instead of the "pause" symbol.

Modify the handler's delay to ~250ms to fix it.

Body:
I have a very simple task - just to show playback controls while playing video on VideoView. But I can't solve it.

Here is the piece of code that I use for initializing VideoView and setting MediaController:

videoView.setVideoURI(Uri.parse(videoUrl));
MediaController mediaController = new MediaController(this);
videoView.setMediaController(mediaController);
videoView.setKeepScreenOn(true);
videoView.setOnPreparedListener(mp -> {
    progress.setVisibility(View.GONE);
    videoView.start();
    mediaController.show(0);
});

The thing is that mediaController.show(0) doesn't give any effect. Controls just show up for 3 seconds and then disappear.

Also I have tried to override MediaController's hide() method:

@Override public void hide() {}

Well, it works - controls never hide, but unfortunately hardware 'back' button stops working. Without override hardware 'back' button on first tap close media controls, on second tap - brings user to previous screen, as expected.

Are there any working solutions?


问:
Why it is common to use anchor inside list item for navbar?
I could not find any information, why it is common to use anchor in list item in navbar?

```<code><ul>
    <li><a href="/one">One</a></li>
    <li><a href="/two">Two</a></li>
</ul>
</code>```

Even navbar in Bootstrap 3 is implemented in such way

```<code><ul class="nav navbar-nav">
  <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
  <li><a href="#">Link</a></li>
  <li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
    <ul class="dropdown-menu">
      <li><a href="#">Action</a></li>
      <li><a href="#">Another action</a></li>
      <li><a href="#">Something else here</a></li>
      <li role="separator" class="divider"></li>
      <li><a href="#">Separated link</a></li>
      <li role="separator" class="divider"></li>
      <li><a href="#">One more separated link</a></li>
    </ul>
  </li>
</ul>
</code>```

Even now some HTML-coders use it and teach to do it.
Why should I use this awkward markup? Then I have to "clean" all browser-default styles for list-items list-style-type: none; and put inside each list item an anchor for navigation link?

What is wrong with this, below?

```<code><div class="nav">
  <span><a href="/one">One</a></span>
  <span><a href="/two">Two</a></span>
</div>
</code>```

 or
 does not matter.
It is already 3 years of HTML5, what is wrong with this, below?

```<code><nav>
  <a href="/one">One</a>
  <a href="/two">Two</a>
</nav>
</code>```

Is it connected some-how with old browsers? If yes, give me a link to read what was wrong, please.

答:
 and  is valid but not semantic since a navbar is essentially a list.

I usually use this approach:

```<code><nav>
 <ul>
  <li class="navbar-item"><a href=#>placeholder</li>
 </ul>
</nav>
</code>```

This is both semantic and can be cleanly styled using css child selectors.

Body:
I could not find any information, why it is common to use anchor in list item in navbar?

One

Two

Even navbar in Bootstrap 3 is implemented in such way

Link (current)

Link

    Dropdown

Action

Another action

Something else here

Separated link

One more separated link

Even now some HTML-coders use it and teach to do it.
Why should I use this awkward markup? Then I have to "clean" all browser-default styles for list-items list-style-type: none; and put inside each list item an anchor for navigation link?

What is wrong with this, below?

  One
  Two

 or
 does not matter.
It is already 3 years of HTML5, what is wrong with this, below?

  One
  Two

Is it connected some-how with old browsers? If yes, give me a link to read what was wrong, please.

Body:
<div> and <span> is valid but not semantic since a navbar is essentially a list.

I usually use this approach:

<nav>
 <ul>
  <li class="navbar-item"><a href=#>placeholder</li>
 </ul>
</nav>

This is both semantic and can be cleanly styled using css child selectors.


问:
Copy invocation-list from one delegate to another
I'm using the expression-builder pattern to build an object. One of the things the expression-builder configures on the object is event-handlers. Here is some demonstrative pseudo-code:

```<code>public class TargetObject
    {
        public event Action SomeEvent;
    }

    public class ObjectBuilder
    {
        private Action handler;

        public TargetObject GetObject()
        {
            TargetObject target = new TargetObject();
            target.SomeEvent += handler;

            return target;
        }

        public ObjectBuilder AddHandler(Action handler)
        {
            this.handler += handler;
            return this;
        }
    }
</code>```

What I would like is, rather than write:

```<code>this.handler += handler;
</code>```

To transfer the invocation-list encapsulated by the "handler" member in ObjectBuilder, to "SomeEvent" in target. Otherwise, ObjectBuilder will not get garbage-collected because my TargetObject's "SomeEvent" will hold a reference to the ObjectBuilder's "handler".

Is this possible?

EDIT:
As requested, here is some sample code that consumes these classes:

```<code>class Program
    {
        static void Main(string[] args)
        {
            TargetObject target = new ObjectBuilder()
                .AddHandler(DoSomething)
                .GetObject();
        }

        private static void DoSomething()
        {
        }
    }
</code>```

答: Are you sure ObjectBuilder is not GC-ed because TargetObject instance is holding its "handler" field? delegate is immutable, this.handler += handler will create a new Action instance.</p>

Body:
I'm using the expression-builder pattern to build an object. One of the things the expression-builder configures on the object is event-handlers. Here is some demonstrative pseudo-code:

public class TargetObject
    {
        public event Action SomeEvent;
    }

    public class ObjectBuilder
    {
        private Action handler;

        public TargetObject GetObject()
        {
            TargetObject target = new TargetObject();
            target.SomeEvent += handler;

            return target;
        }

        public ObjectBuilder AddHandler(Action handler)
        {
            this.handler += handler;
            return this;
        }
    }

What I would like is, rather than write:

this.handler += handler;

To transfer the invocation-list encapsulated by the "handler" member in ObjectBuilder, to "SomeEvent" in target. Otherwise, ObjectBuilder will not get garbage-collected because my TargetObject's "SomeEvent" will hold a reference to the ObjectBuilder's "handler".

Is this possible?

EDIT:
As requested, here is some sample code that consumes these classes:

class Program
    {
        static void Main(string[] args)
        {
            TargetObject target = new ObjectBuilder()
                .AddHandler(DoSomething)
                .GetObject();
        }

        private static void DoSomething()
        {
        }
    }


问:
Swift: extract float from byte data
I'm looking for a robust and elegant way to extract four big-endian bytes from an array as a Float.

I can get a UInt32 with the bits via something like this:

```<code>let data: [Byte] = [0x00, 0x00, 0x00, 0x40, 0x86, 0x66, 0x66, 0x00]
let dataPtr = UnsafePointer<Byte>(data)
let byteOffset = 3
let bits = UnsafePointer<UInt32>(dataPtr + byteOffset)[0].bigEndian
</code>```

But I can't figure out a good way to convert this into a Float in Swift.

For example, in Java:

```<code>float f = Float.intBitsToFloat(bits)
</code>```

or in C:

```<code>float f = *(float *)&bits;
</code>```

I tried casting the dataPtr to a float UnsafePointer, but then the endianness is a problem.

Any suggestions?

答:
Here's the solution for Swift 3:</p>

```<code>Float(bitPattern: bits)
</code>```

Title: Swift: extract float from byte data

Body:
I'm looking for a robust and elegant way to extract four big-endian bytes from an array as a Float.

I can get a UInt32 with the bits via something like this:

let data: [Byte] = [0x00, 0x00, 0x00, 0x40, 0x86, 0x66, 0x66, 0x00]
let dataPtr = UnsafePointer<Byte>(data)
let byteOffset = 3
let bits = UnsafePointer<UInt32>(dataPtr + byteOffset)[0].bigEndian

But I can't figure out a good way to convert this into a Float in Swift.

For example, in Java:

float f = Float.intBitsToFloat(bits)

or in C:

float f = *(float *)&bits;

I tried casting the dataPtr to a float UnsafePointer, but then the endianness is a problem.

Any suggestions?

Body:
Here's the solution for Swift 3:

Float(bitPattern: bits)


问:
Cannot handle POST request with this servlet
this is my servlet

```<code>import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.json.JSONObject;
import org.json.simple.JSONObject;

import com.mysql.jdbc.Statement;
/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Connection connection;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init(ServletConfig config) throws ServletException {
        ServletContext context = config.getServletContext();
        String url = context.getInitParameter("dbUrl");
        String dbUser = context.getInitParameter("dbUser");
        String dbPassword = context.getInitParameter("dbPassword");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url, dbUser, dbPassword);
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void destroy() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
    }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("plain/text");

        JSONObject json = new JSONObject();
        PrintWriter out = response.getWriter();
        String usernameV = request.getParameter("usernameV");
        String passwordV = request.getParameter("passwordV");

        json.put("ris", 0);
        try {
            String sql = "SELECT * FROM user WHERE username = ? AND password = ? ";
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1, usernameV);
            stmt.setString(2, passwordV);
            json.put("password", usernameV);
            json.put("username", usernameV);

            out.print(json.toJSONString());
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                json.replace("ris", 1);
                out.print(json.toJSONString());
                stmt.close();
                rs.close();
                return;
            }
            stmt.close();
            rs.close();
        } catch (SQLException e) {
            json.replace("err", e.getMessage());
            out.print(json.toJSONString());

        }

        out.print(json.toJSONString());``
    }

    }
</code>```

and here's my javascript

$(document).ready(function() {
 $(window).keydown(function(event){//impedisco l'invio del form premendo invio
  if(event.keyCode == 13) {
   event.preventDefault();
   return false;
  }
 });

 $("#bottone").click(function(){
  $("#risultato").attr("style", "color: black;");
  $("#risultato").html("Caricamento...");
  var username = $("#username").val();
  var password = $("#password").val();
  $.ajax({
   type: "POST",
   url: "Register",
   //data: {"username" : username, "password": password},
   data: "username=" + username + "&password=" + password,
   dataType: "text",
   success: function(msg)
   {
    var result = $.parseJSON(msg);
    if(result.error){
     switch (result.error) {
     case 1:
      Step();

      break;
     default:
      $("#risultato").html(msg);
     break;
     }
    }else{
     $("#bottone").prop('disabled', true);
     $("#risultato").attr("style", "color: black;");
     $("#risultato").html("Benvenuto " + username + "!");
    }
   },
   error: function()
   {
    $("#risultato").attr("style", "color: red;");
    $("#risultato").html("Errore di connessione!");
   }
  });
 });
});

function Step() {
 $("#risultato").attr("style", "color: red;");
 $("#risultato").html("Username già esistente!
");
 $("#risultato").append("
Inserisci la tua password : <input type='password' name='passwordV' id='passwordV'> <input type='button' id='bottone1' value='Login'>
");

 $("#bottone1").click(function(){
  $("#res").attr("style", "color: black;");
  $("#res").html("Caricamento...");
  var username = $("#username").val();
  var password = $("#passwordV").val();
 $.ajax({
  type: "POST",
  url: "Login",
  data: "usernameV=" + username + "&passwordV=" + password,
  dataType: "text",
  success: function(msg)
  {
   var resulto = $.parseJSON(msg);
   if(resulto.ris){
    switch (resulto.ris) {
    case 1:
     $("#res").attr("style", "color: red;");
     $("#res").html("Benvenuto " + username + "!");

     break;
    default:
     $("#res").html(msg);
    break;
    }
   }else{
    $("#bottone1").prop('disabled', true);
    $("#res").attr("style", "color: black;");
    $("#res").html("password errata:"+ password);
    $("#stack").attr("style", "color: black;");
    $("#stack").html(msg);
   }
  },
  error: function()
  {
   $("#res").attr("style", "color: red;");
   $("#res").html("Errore di connessione!");
  }
 });
 });
}

 ```
</div>
</div>

 if it helps, i post also the default.jsp page:</p>

```<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chat Room</title>

    <form name="modulo" action="">

            Nome utente: <input type="text" name="username" id="username">
            Password:    <input type="password" name="password" id="password">
            <input type="button" id="bottone" value="Registrati!">

    </form>

```

<p>i add also the Register.java servlet.. This one does work, and, as you  can see, it is almost the same as the login one.</p>

```package it.marco.chat.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.json.JSONObject;
import org.json.simple.JSONObject;

import com.mysql.jdbc.Statement;

/**
 * Servlet implementation class Register
 */
@WebServlet("/Register")
public class Register extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Connection connection;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
    }

    /**
     * @see Servlet#init(ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        ServletContext context = config.getServletContext();
        String url = context.getInitParameter("dbUrl");
        String dbUser = context.getInitParameter("dbUser");
        String dbPassword = context.getInitParameter("dbPassword");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url, dbUser, dbPassword);
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @see Servlet#destroy()
     */
    public void destroy() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("plain/text");

        JSONObject json = new JSONObject();
        PrintWriter out = response.getWriter();
        json.put("error", 0);

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try {
            String sql = "SELECT * FROM user WHERE username = ?";
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                json.replace("error", 1);
                out.print(json.toJSONString());
                stmt.close();
                rs.close();
                return;
            }
            stmt.close();
            rs.close();
        } catch (SQLException e) {
        }

        int uid = -1;

        try {
            String sql = "INSERT INTO user(username,password) VALUES(?,?)";
            PreparedStatement stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            stmt.setString(1, username);
            stmt.setString(2, password);
            stmt.execute();
            ResultSet rs = stmt.getGeneratedKeys();
            if (rs.next()) {
                uid = rs.getInt(1);
            }
            stmt.close();
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        json.put("uid", uid);

        out.print(json.toJSONString());
    }

}
```

i cannot understand why the servlet is not able to handle the POST request.. I mean, i have already set up one servlet that hanldles the register part and it works perfectly.
I have tried all the evening to make it work, and i am pretty sure there's a stupid mistake i am not able to see, that's why i have come here.
I hope that someone is able to help me.
Thank you

答:
change this :

```<code>@WebServlet("/Login")
</code>```

to

```<code>@WebServlet(name = "Login", urlPatterns = { "/Login" })
</code>```

it will work believe me

Body:
this is my servlet

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.json.JSONObject;
import org.json.simple.JSONObject;

import com.mysql.jdbc.Statement;
/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Connection connection;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init(ServletConfig config) throws ServletException {
        ServletContext context = config.getServletContext();
        String url = context.getInitParameter("dbUrl");
        String dbUser = context.getInitParameter("dbUser");
        String dbPassword = context.getInitParameter("dbPassword");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url, dbUser, dbPassword);
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void destroy() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
    }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("plain/text");

        JSONObject json = new JSONObject();
        PrintWriter out = response.getWriter();
        String usernameV = request.getParameter("usernameV");
        String passwordV = request.getParameter("passwordV");

        json.put("ris", 0);
        try {
            String sql = "SELECT * FROM user WHERE username = ? AND password = ? ";
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1, usernameV);
            stmt.setString(2, passwordV);
            json.put("password", usernameV);
            json.put("username", usernameV);

            out.print(json.toJSONString());
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                json.replace("ris", 1);
                out.print(json.toJSONString());
                stmt.close();
                rs.close();
                return;
            }
            stmt.close();
            rs.close();
        } catch (SQLException e) {
            json.replace("err", e.getMessage());
            out.print(json.toJSONString());

        }

        out.print(json.toJSONString());``
    }

    }

and here's my javascript

$(document).ready(function() {
 $(window).keydown(function(event){//impedisco l'invio del form premendo invio
  if(event.keyCode == 13) {
   event.preventDefault();
   return false;
  }
 });

 $("#bottone").click(function(){
  $("#risultato").attr("style", "color: black;");
  $("#risultato").html("Caricamento...");
  var username = $("#username").val();
  var password = $("#password").val();
  $.ajax({
   type: "POST",
   url: "Register",
   //data: {"username" : username, "password": password},
   data: "username=" + username + "&password=" + password,
   dataType: "text",
   success: function(msg)
   {
    var result = $.parseJSON(msg);
    if(result.error){
     switch (result.error) {
     case 1:
      Step();

      break;
     default:
      $("#risultato").html(msg);
     break;
     }
    }else{
     $("#bottone").prop('disabled', true);
     $("#risultato").attr("style", "color: black;");
     $("#risultato").html("Benvenuto " + username + "!");
    }
   },
   error: function()
   {
    $("#risultato").attr("style", "color: red;");
    $("#risultato").html("Errore di connessione!");
   }
  });
 });
});

function Step() {
 $("#risultato").attr("style", "color: red;");
 $("#risultato").html("Username già esistente!
");
 $("#risultato").append("
Inserisci la tua password : <input type='password' name='passwordV' id='passwordV'> <input type='button' id='bottone1' value='Login'>
");

 $("#bottone1").click(function(){
  $("#res").attr("style", "color: black;");
  $("#res").html("Caricamento...");
  var username = $("#username").val();
  var password = $("#passwordV").val();
 $.ajax({
  type: "POST",
  url: "Login",
  data: "usernameV=" + username + "&passwordV=" + password,
  dataType: "text",
  success: function(msg)
  {
   var resulto = $.parseJSON(msg);
   if(resulto.ris){
    switch (resulto.ris) {
    case 1:
     $("#res").attr("style", "color: red;");
     $("#res").html("Benvenuto " + username + "!");

     break;
    default:
     $("#res").html(msg);
    break;
    }
   }else{
    $("#bottone1").prop('disabled', true);
    $("#res").attr("style", "color: black;");
    $("#res").html("password errata:"+ password);
    $("#stack").attr("style", "color: black;");
    $("#stack").html(msg);
   }
  },
  error: function()
  {
   $("#res").attr("style", "color: red;");
   $("#res").html("Errore di connessione!");
  }
 });
 });
}

 if it helps, i post also the default.jsp page:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chat Room</title>

    <form name="modulo" action="">

            Nome utente: <input type="text" name="username" id="username">
            Password:    <input type="password" name="password" id="password">
            <input type="button" id="bottone" value="Registrati!">

    </form>

i add also the Register.java servlet.. This one does work, and, as you  can see, it is almost the same as the login one.

package it.marco.chat.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.json.JSONObject;
import org.json.simple.JSONObject;

import com.mysql.jdbc.Statement;

/**
 * Servlet implementation class Register
 */
@WebServlet("/Register")
public class Register extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Connection connection;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
    }

    /**
     * @see Servlet#init(ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        ServletContext context = config.getServletContext();
        String url = context.getInitParameter("dbUrl");
        String dbUser = context.getInitParameter("dbUser");
        String dbPassword = context.getInitParameter("dbPassword");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url, dbUser, dbPassword);
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @see Servlet#destroy()
     */
    public void destroy() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("plain/text");

        JSONObject json = new JSONObject();
        PrintWriter out = response.getWriter();
        json.put("error", 0);

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try {
            String sql = "SELECT * FROM user WHERE username = ?";
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                json.replace("error", 1);
                out.print(json.toJSONString());
                stmt.close();
                rs.close();
                return;
            }
            stmt.close();
            rs.close();
        } catch (SQLException e) {
        }

        int uid = -1;

        try {
            String sql = "INSERT INTO user(username,password) VALUES(?,?)";
            PreparedStatement stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            stmt.setString(1, username);
            stmt.setString(2, password);
            stmt.execute();
            ResultSet rs = stmt.getGeneratedKeys();
            if (rs.next()) {
                uid = rs.getInt(1);
            }
            stmt.close();
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        json.put("uid", uid);

        out.print(json.toJSONString());
    }

}

i cannot understand why the servlet is not able to handle the POST request.. I mean, i have already set up one servlet that hanldles the register part and it works perfectly.
I have tried all the evening to make it work, and i am pretty sure there's a stupid mistake i am not able to see, that's why i have come here.
I hope that someone is able to help me.
Thank you

Body:
change this :

@WebServlet("/Login")

to

@WebServlet(name = "Login", urlPatterns = { "/Login" })

it will work believe me


答:
The full width of the page?

You can reset or eradicate with:

```<code>*, html, body {
  padding: 0px;
  margin: 0px;
}
</code>```

Updated jsfiddle.

Body:
Foremost there are a lot of posts relating to background-color. I have read several and have tried various solutions posted there from setting background-size to making overflow hidden. Nothing seems to work....
How can I get background-color to cover the whole section?

I have a very simple M.W.E. below:

html

  TEST!

css

body {
  background-color: coral;
}

section {
  background-color: blue;
  width: 100%;
}

Fiddle

Body:
The full width of the page?

You can reset or eradicate with:

*, html, body {
  padding: 0px;
  margin: 0px;
}

Updated jsfiddle.


问:
return function within if statement not executing
Hey so i'm writing a function that checks whether a series of braces is a valid sequence. I have the following code, which mostly does what I want it to do, except it it always returns false. If i enter a valid sequence of braces it ends up in the right if-statement, but never returns true. I don't understand why.

function match(s) {
  if (s === '(') {
    return ')'
  }
  else if (s === '[') {
    return ']'
  }
  else if (s === '{') {
    return '}'
  }
}

function open(b) {
  if ( (b === '(' ) || (b === '[' ) || (b === '{') ) {
    return true;
  }
  return false;
}

function checkValid(string, temp, n) {
  var current = string.charAt(n)
  var currentMatch = temp.charAt(0)

  if (!(current) && (n === string.length) && (temp === "")) {
    console.log('hey')
    return true
  }

  if (open(current)) {
    temp = match(current).concat(temp)
    checkValid(string, temp, n+1)
  }
  else {
    if (current === currentMatch) {
      temp = temp.substr(1)
      checkValid(string, temp, n+1)
    }
    return false;
  }
  return false;
}

function validBraces(braces) {
  var n = 0
  var temp = ''
  return checkValid(braces, temp, n)
}

validBraces('()') // should return true
validBraces('[[)}}{') //should return false```

答:
The last return false is always being returned from your original checkValid function call.

This is because you aren't returning the recursive checkValid calls.

function match(s) {
  if (s === '(') {
    return ')'
  }
  else if (s === '[') {
    return ']'
  }
  else if (s === '{') {
    return '}'
  }
}

function open(b) {
  if ( (b === '(' ) || (b === '[' ) || (b === '{') ) {
    return true;
  }
  return false;
}

function checkValid(string, temp, n) {
  var current = string.charAt(n)
  var currentMatch = temp.charAt(0)

  if (!(current) && (n === string.length) && (temp === "")) {
    console.log('hey')
    return true
  }

  if (open(current)) {
    temp = match(current).concat(temp)
    return checkValid(string, temp, n+1)
  }
  else {
    if (current === currentMatch) {
      temp = temp.substr(1)
      return checkValid(string, temp, n+1)
    }
    return false;
  }
  return false;
}

function validBraces(braces) {
  var n = 0
  var temp = ''
  return checkValid(braces, temp, n)
}

validBraces('()') // should return true
validBraces('[[)}}{') //should return false
```


问:
Unable to find file in VBScript
The VBE encoder section works (from prior experience but this time around it cannot find the required file. The file is in the %temp% folder so there are spaces in the path but I have used the "" as can be seen in the code. The MsgBox shows the correct file and I can confirm its existence but the code fails when fso.GetFile.

This is part of a larger script that is called with the target file (full path) as the argument. The target file is previously created by the calling script.

Main script (gets called with target file):

```<code>Set fso      = CreateObject("Scripting.FileSystemObject")
Set wshShell = WScript.CreateObject("WScript.Shell")
textFile     = WScript.Arguments(0)
GetExtension = fso.GetExtensionName(fso.GetFileName(textFile))

If LCase(GetExtension) = "vbs" Then
    Set oFilesToEncode = WScript.Arguments
    Set oEncoder = CreateObject("Scripting.Encoder")
    For i = 0 To oFilesToEncode.Count - 1
        file = """" & Trim(oFilesToEncode(i)) & """"
        MsgBox file

        If fso.FileExists(Left(file, Len(file) - 3) & "vbe") Then fso.DeleteFile(Left(file, Len(file) - 3) & "vbe")

        Set oFile   = fso.GetFile(file)
        Set oStream = oFile.OpenAsTextStream(1)
        sSourceFile = oStream.ReadAll
        oStream.Close

        sDest        = oEncoder.EncodeScriptFile(".vbs", sSourceFile, 0, "")
        sFileOut     = Left(file, Len(file) - 3) & "vbe"
        Set oEncFile = fso.CreateTextFile(sFileOut)
        oEncFile.Write sDest
        oEncFile.Close
    Next
End If

WScript.Quit
</code>```

Section of calling script:

```<code>Do While fso.FileExists(strTempVBS) = False
Loop

strKey  = "HKEY_CLASSES_ROOT\Engineers-Toolbox\Multi-Tool\Installed\Path\"
value    = wshShell.RegRead( strKey )
arg     = " " & strTempVBS
running = "C:\Custom\Multi-Tool\Multi-Tool.exe " & """" & arg & """"
wshShell.Run running, True
</code>```

I have tried using hard coding the path to the exe to get it going, 'value' contains the path to the main script.

答:
Do not prematurely add quotes around paths. I'm always confused why people keep doing this, because it creates more problems than it solves. Add double quotes when they're actually required, but not before.

FileSystemObject methods can handle paths with spaces without the additional double quotes. In fact, they will interpret double quotes in a path string as part of the path and throw an error, because they can't find a file with a double quote in its name (which would be invalid anyway).

Your check for the existence of a file also doesn't work, because you don't account for the quotes you added to the path string:

```<code>file = """C:\some\folder\file.vbs"""
WScript.Echo file
WScript.Echo Left(file, Len(file) - 3) & "vbe"
</code>```

The output of the above code snippet is

```
"C:\some\folder\file.vbs"
"C:\some\folder\file.vvbe
```

Change this:

```<code>file = """" & Trim(oFilesToEncode(i)) & """"
</code>```

into this:

```<code>file = Trim(oFilesToEncode(i))
</code>```

and the problem will disappear.

Title: Unable to find file in VBScript

Body:
The VBE encoder section works (from prior experience but this time around it cannot find the required file. The file is in the %temp% folder so there are spaces in the path but I have used the "" as can be seen in the code. The MsgBox shows the correct file and I can confirm its existence but the code fails when fso.GetFile.

This is part of a larger script that is called with the target file (full path) as the argument. The target file is previously created by the calling script.

Main script (gets called with target file):

Set fso      = CreateObject("Scripting.FileSystemObject")
Set wshShell = WScript.CreateObject("WScript.Shell")
textFile     = WScript.Arguments(0)
GetExtension = fso.GetExtensionName(fso.GetFileName(textFile))

If LCase(GetExtension) = "vbs" Then
    Set oFilesToEncode = WScript.Arguments
    Set oEncoder = CreateObject("Scripting.Encoder")
    For i = 0 To oFilesToEncode.Count - 1
        file = """" & Trim(oFilesToEncode(i)) & """"
        MsgBox file

        If fso.FileExists(Left(file, Len(file) - 3) & "vbe") Then fso.DeleteFile(Left(file, Len(file) - 3) & "vbe")

        Set oFile   = fso.GetFile(file)
        Set oStream = oFile.OpenAsTextStream(1)
        sSourceFile = oStream.ReadAll
        oStream.Close

        sDest        = oEncoder.EncodeScriptFile(".vbs", sSourceFile, 0, "")
        sFileOut     = Left(file, Len(file) - 3) & "vbe"
        Set oEncFile = fso.CreateTextFile(sFileOut)
        oEncFile.Write sDest
        oEncFile.Close
    Next
End If

WScript.Quit

Section of calling script:

Do While fso.FileExists(strTempVBS) = False
Loop

strKey  = "HKEY_CLASSES_ROOT\Engineers-Toolbox\Multi-Tool\Installed\Path\"
value    = wshShell.RegRead( strKey )
arg     = " " & strTempVBS
running = "C:\Custom\Multi-Tool\Multi-Tool.exe " & """" & arg & """"
wshShell.Run running, True

I have tried using hard coding the path to the exe to get it going, 'value' contains the path to the main script.

Body:
Do not prematurely add quotes around paths. I'm always confused why people keep doing this, because it creates more problems than it solves. Add double quotes when they're actually required, but not before.

FileSystemObject methods can handle paths with spaces without the additional double quotes. In fact, they will interpret double quotes in a path string as part of the path and throw an error, because they can't find a file with a double quote in its name (which would be invalid anyway).

Your check for the existence of a file also doesn't work, because you don't account for the quotes you added to the path string:

file = """C:\some\folder\file.vbs"""
WScript.Echo file
WScript.Echo Left(file, Len(file) - 3) & "vbe"

The output of the above code snippet is

"C:\some\folder\file.vbs"
"C:\some\folder\file.vvbe

Change this:

file = """" & Trim(oFilesToEncode(i)) & """"

into this:

file = Trim(oFilesToEncode(i))

and the problem will disappear.


问:
Django REST Framework: Unique_together validation on Serializers
Having issues with a serializer.is_valid() returning True if the serializer instance fails a unique_together constraint on the model side.

Is there a way for me to specify in the serializer to enforce a unique_together constraint?

答:
Well this is kinda stupid and it's very unlikely that anyone but me would make this mistake, but I had put the same model in two serializers class, as a consequence I had this problem

Hope my mistake help someone!


问:
Shopify API error when add new product
I'm using Shopify API  with PHP CURL POST Method to create a product. Kindly find the following code and the response. I got error "Not Found".

```<code>    <?php

      $products_array = array(
      "product"=>array(
      'title'=>'',
      "title"=> "Burton Custom Freestlye 151",
      "body_html"=> "<strong>Good snowboard!</strong>",
      "vendor"=> "Burton",
      "product_type"=> "Snowboard",
      "published"=> false ,
      "variants"=>array(
                    array(
                    "sku"=>"t_009",
                    "price"=>20.00,
                    "grams"=>200,
                    "taxable"=>false,
                    )
                 )
       )
      );
      echo json_encode($products_array);
      echo "<br />";
      $url = "https://apikey:password@hostname/admin/products.json";

      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:   application/json; charset=utf-8'));
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_VERBOSE, 0);
      curl_setopt($curl, CURLOPT_HEADER, 1);
      curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($products_array));
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
      $response = curl_exec ($curl);
      curl_close ($curl);
      echo "```";
      print_r($response);

       ?>
```

<p>The response of the request :</p>

```      {"product":{"title":"Burton Custom Freestlye 151","body_html":"Good snowboard!<\/strong>","vendor":"Burton","product_type":"Snowboard","published":false,"variants":[{"sku":"t_009","price":20,"grams":200,"taxable":false}]}}

       HTTP/1.1 404 Not Found
       Server: nginx
       Date: Sat, 01 Apr 2017 21:08:04 GMT
       Content-Type: application/json; charset=utf-8
       Transfer-Encoding: chunked
       Connection: keep-alive
       Vary: Accept-Encoding
       Vary: Accept-Encoding
       Vary: Accept-Encoding
       X-Frame-Options: DENY
       X-Content-Type-Options: nosniff
       X-Download-Options: noopen
       X-Permitted-Cross-Domain-Policies: none
       X-XSS-Protection: 1; mode=block; report=/xss-     report?source%5Baction%5D=create&source%5Bapp%5D=Shopify&    source%5Bcontroller%5D=admin%2Fproducts&source%5Bsection%5D=admin&source%5Buuid%5D=5539f94e-776f-4672-ab2a-f340c0cf2ad1
       X-Dc: ash,chi2
       X-Request-ID: 5539f94e-776f-4672-ab2a-f340c0cf2ad1

       {"errors":"Not Found"}
```

How can I fix that error ? and what does that mean ??

答: Double check that you are using the right .myshopify.com hostname for your store. You can see this (along with the API key and password) after creating a private app in the Shopify admin: https://shopify.com/admin/apps/private

Title: Shopify API error when add new product

Body:
I'm using Shopify API  with PHP CURL POST Method to create a product. Kindly find the following code and the response. I got error "Not Found".

    <?php

      $products_array = array(
      "product"=>array(
      'title'=>'',
      "title"=> "Burton Custom Freestlye 151",
      "body_html"=> "Good snowboard!",
      "vendor"=> "Burton",
      "product_type"=> "Snowboard",
      "published"=> false ,
      "variants"=>array(
                    array(
                    "sku"=>"t_009",
                    "price"=>20.00,
                    "grams"=>200,
                    "taxable"=>false,
                    )
                 )
       )
      );
      echo json_encode($products_array);
      echo "
";
      $url = "https://apikey:password@hostname/admin/products.json";

      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:   application/json; charset=utf-8'));
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_VERBOSE, 0);
      curl_setopt($curl, CURLOPT_HEADER, 1);
      curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($products_array));
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
      $response = curl_exec ($curl);
      curl_close ($curl);
      echo "
";
      print_r($response);

       ?>

The response of the request :

      {"product":{"title":"Burton Custom Freestlye 151","body_html":"Good snowboard!<\/strong>","vendor":"Burton","product_type":"Snowboard","published":false,"variants":[{"sku":"t_009","price":20,"grams":200,"taxable":false}]}}

       HTTP/1.1 404 Not Found
       Server: nginx
       Date: Sat, 01 Apr 2017 21:08:04 GMT
       Content-Type: application/json; charset=utf-8
       Transfer-Encoding: chunked
       Connection: keep-alive
       Vary: Accept-Encoding
       Vary: Accept-Encoding
       Vary: Accept-Encoding
       X-Frame-Options: DENY
       X-Content-Type-Options: nosniff
       X-Download-Options: noopen
       X-Permitted-Cross-Domain-Policies: none
       X-XSS-Protection: 1; mode=block; report=/xss-     report?source%5Baction%5D=create&source%5Bapp%5D=Shopify&    source%5Bcontroller%5D=admin%2Fproducts&source%5Bsection%5D=admin&source%5Buuid%5D=5539f94e-776f-4672-ab2a-f340c0cf2ad1
       X-Dc: ash,chi2
       X-Request-ID: 5539f94e-776f-4672-ab2a-f340c0cf2ad1

       {"errors":"Not Found"}

How can I fix that error ? and what does that mean ??


问:
IIS rewrite rule to deny access files and folder starting with "."
I need an IIS rewrite rule to deny access to all files and folder starting with "."

Files like
.git
.composer
.htaccess  (I know is for Apache )

Any folder like
/.test/
A plus if rule can cover any folder starting with “.”  but  not this one “./well-known/acme-challenge”

thanks

答:
Well I think I found it ;)

add this to web.config make sure the <rule> is inside <rules>

```<code><rules>

...

   <rule name="Deny files and folderd starting with ." patternSyntax="ECMAScript" stopProcessing="true">
     <match url="(^\.|\/\.)" ignoreCase="true" negate="false" />
     <conditions logicalGrouping="MatchAll">
     </conditions>
     <action type="AbortRequest" />
  </rule>

<rules>
</code>```

Body:
Well I think I found it ;)

add this to web.config make sure the <rule> is inside <rules>

<rules>

...

   <rule name="Deny files and folderd starting with ." patternSyntax="ECMAScript" stopProcessing="true">
     <match url="(^\.|\/\.)" ignoreCase="true" negate="false" />
     <conditions logicalGrouping="MatchAll">
     </conditions>
     <action type="AbortRequest" />
  </rule>

<rules>


问:
Integrating TextExt in SlickGrid custom editor
i want to implement a custom editor in SlickGrid using TextExt but I'm having trouble doing so.

I have two different lists args.column.names and `args.column.values.
I want the tags to show the selected names but to post the list of the corresponding ids.

Here is a first draft, I don't really see how to manage that.

Can someone help me figure out what to write in these functions to match what I'm trying to do ?

```<code>function AutoCompletedTextField(args) {
    var $input;
    var defaultValue;
    var scope = this;

    this.init = function () {
        $input = $("<textarea class='textarea' rows='1'></textarea>")
            .appendTo(args.container)
            .bind("keydown.nav", function (e) {
                if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
                    e.stopImmediatePropagation();
                }
            })
            .focus()
            .select();

        $('.textarea').textext({
            plugins: 'tags autocomplete arrow'
        }).bind('getSuggestions', function (e, data) {
            var list = args.column.names,
                textext = $(e.target).textext()[0],
                query = (data ? data.query : '') || '';
            $(this).trigger('setSuggestions', { result: textext.itemManager().filter(list, query) });
        });

    };

    this.destroy = function () {
        $input.remove();
    };

    this.focus = function () {
        $input.focus();
    };

    this.getValue = function () {
        return $input.textext()[0].hiddenInput().val();
    };

    this.setValue = function (val) {
        $input.textext()[0].hiddenInput().val(val)
    };

    this.loadValue = function (item) {
        $input[0].defaultValue = item[args.column.field];
        $input.select();
    };

    this.serializeValue = function () {
        return $input[0].defaultValue;
    };

    this.applyValue = function (item, state) {
        item[args.column.field] = state;
    };

    this.isValueChanged = function () {
        return (!($input.textext()[0].hiddenInput().val() == "" && defaultValue == null)) && ($input.textext()[0].hiddenInput().val() != defaultValue);
    };

    this.validate = function () {
        if (args.column.validator) {
            var validationResults = args.column.validator($input.val());
            if (!validationResults.valid) {
                return validationResults;
            }
        }

        return {
            valid: true,
            msg: null
        };
    };

    this.init();
}
</code>```

答:
You may want to try my repo, it's updated for the latest jQuery and has a lot of fixes and enhancements.

One of those enhancements is a Select2 editor, which is very similar to what you're trying to do. I think if you check that out it will be clear what is needed.

There's an example here.

As a bonus, there also a mechanism to allow certain keycodes to bubble through to the grid rather than be captured by the editor. This can be useful for up-arrow, etc. This isn't in the MLeibman branch.

Body:
i want to implement a custom editor in SlickGrid using TextExt but I'm having trouble doing so.

I have two different lists args.column.names and `args.column.values.
I want the tags to show the selected names but to post the list of the corresponding ids.

Here is a first draft, I don't really see how to manage that.

Can someone help me figure out what to write in these functions to match what I'm trying to do ?

function AutoCompletedTextField(args) {
    var $input;
    var defaultValue;
    var scope = this;

    this.init = function () {
        $input = $("<textarea class='textarea' rows='1'></textarea>")
            .appendTo(args.container)
            .bind("keydown.nav", function (e) {
                if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
                    e.stopImmediatePropagation();
                }
            })
            .focus()
            .select();

        $('.textarea').textext({
            plugins: 'tags autocomplete arrow'
        }).bind('getSuggestions', function (e, data) {
            var list = args.column.names,
                textext = $(e.target).textext()[0],
                query = (data ? data.query : '') || '';
            $(this).trigger('setSuggestions', { result: textext.itemManager().filter(list, query) });
        });

    };

    this.destroy = function () {
        $input.remove();
    };

    this.focus = function () {
        $input.focus();
    };

    this.getValue = function () {
        return $input.textext()[0].hiddenInput().val();
    };

    this.setValue = function (val) {
        $input.textext()[0].hiddenInput().val(val)
    };

    this.loadValue = function (item) {
        $input[0].defaultValue = item[args.column.field];
        $input.select();
    };

    this.serializeValue = function () {
        return $input[0].defaultValue;
    };

    this.applyValue = function (item, state) {
        item[args.column.field] = state;
    };

    this.isValueChanged = function () {
        return (!($input.textext()[0].hiddenInput().val() == "" && defaultValue == null)) && ($input.textext()[0].hiddenInput().val() != defaultValue);
    };

    this.validate = function () {
        if (args.column.validator) {
            var validationResults = args.column.validator($input.val());
            if (!validationResults.valid) {
                return validationResults;
            }
        }

        return {
            valid: true,
            msg: null
        };
    };

    this.init();
}


问:
Magento Create Product Attribute That Is An Integer
So apparently the support you get from Varien when you purchase the Enterprise Edition is next to worthless so I am hoping that someone here can maybe lead me in the right direction.

In Magento I am would like to create a product attribute that is the type int. When I create the attribute from the admin panel it creates it as a varchar.

What I am ultimately trying to do is create a total sold attribute so that I can use it for sorting by most sold products in the category display. The problem with it being varchar is that when you sort by this, it sorts it as a string and not a number.

Varien told me that in order to get this to be an integer I would have to do an update to the database. It looks like to me that I would have to change the backend_type column in the eav_attribute table to int and that should hopefully move the values to catalog_product_entity_int table instead of it going to catalog_product_entity_varchar table. Does this make sense? Has anyone else done this before?

Now that I have that question out there, is this what I should expect from the support from Varien? So far their support seem pretty useless. It seems that asking how to do something this simple would not be a big deal (especially since I asked them how to do it, and not to do it for me)

答:
I had exactly the same problem. Additional problem was that i didn't want to loose attribute values.

First of all you need to export products with attribute by magento dataflow system (System/ImportExport/Profiles). You need to create profile to export and mark in Export: 'only mapped fields'. You can use sku and attribute which you want to change for integer in database.

Later you should create sql install file in any module to change database:

mysql4-install-0.1.0.php

```<code>$installer->startSetup();
$installer->updateAttribute('catalog_product', '<<your_attribute_code>>', array(
'backend_type'    => 'int',
));
$this->endSetup();
?>
</code>```

Later it is very important to reindex product_attribute and product_flat_data.

Next step is to mark all product which use this attribute and using action "update attributes" you should set value by 100 for example.

Now reindex again !!!

and import file by another profile in dataflow.

Good luck!

Body:
I had exactly the same problem. Additional problem was that i didn't want to loose attribute values.

First of all you need to export products with attribute by magento dataflow system (System/ImportExport/Profiles). You need to create profile to export and mark in Export: 'only mapped fields'. You can use sku and attribute which you want to change for integer in database.

Later you should create sql install file in any module to change database:

mysql4-install-0.1.0.php

$installer->startSetup();
$installer->updateAttribute('catalog_product', '<<your_attribute_code>>', array(
'backend_type'    => 'int',
));
$this->endSetup();
?>

Later it is very important to reindex product_attribute and product_flat_data.

Next step is to mark all product which use this attribute and using action "update attributes" you should set value by 100 for example.

Now reindex again !!!

and import file by another profile in dataflow.

Good luck!


问:
My nested for loop number pattern doesn't out put the correct pattern
I'm trying to print out this pattern but I'm having trouble arranging the numbers and spacing them out to achieve the expected out put.

```<code>Expected Output:
          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1
</code>```

Here is my Code. I don't know how to space the numbers and put the correct numbers in the order that the out put has specified.

```<code>import java.util.Scanner;

public class patterns{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 6; i >= 1; i--)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

                System.out.println();

   for (int i = 1; i <= 6; i++)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

   }
 }
</code>```

This is the Output I'm Getting

```<code>run:
     6
    56
   456
  3456
 23456
123456

123456
 23456
  3456
   456
    56
     6
</code>```

答:
Best way is to use an array -> you loop less times. http://ideone.com/diYtvM  Cheers!

```<code>  import java.util.Scanner;

        public class patterns{
         public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            int[][] arr = new int[6][6];

                for(int i = 0; i<6; i++)
                    arr[i][5] = 1;

    for(int i = 1; i<6; i++)
                for (int j = 4; j>=5-i; j--)
                {
                    arr[i][j] = arr[i-1][j+1] + 1;
                }

            for(int i = 0; i<6; i++)
            {
                for (int j = 0; j<6; j++)
                {
                    if(arr[i][j] > 0)
                    System.out.print(arr[i][j] + " ");
                    else
                    System.out.print("  ");

                }
                    System.out.println("");
            }

            System.out.println("");

            int z = 0;
                for(int i = 5; i>=0; i--)
            {
                for(int k = 0; k<z; k++)
                System.out.print("  ");
                for (int j = 5; j>=0; j--)
                {
                    if(arr[i][j] > 0)
                    System.out.print(arr[i][j] + " ");

                }
                    System.out.println("");
                    z++;
            }

         }

        }
</code>```

OUT:

```<code>          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1
</code>```

Body:
I'm trying to print out this pattern but I'm having trouble arranging the numbers and spacing them out to achieve the expected out put.

Expected Output:
          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1

Here is my Code. I don't know how to space the numbers and put the correct numbers in the order that the out put has specified.

import java.util.Scanner;

public class patterns{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 6; i >= 1; i--)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

                System.out.println();

   for (int i = 1; i <= 6; i++)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

   }
 }

This is the Output I'm Getting

run:
     6
    56
   456
  3456
 23456
123456

123456
 23456
  3456
   456
    56
     6

Body:
Best way is to use an array -> you loop less times. http://ideone.com/diYtvM  Cheers!

  import java.util.Scanner;

        public class patterns{
         public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            int[][] arr = new int[6][6];

                for(int i = 0; i<6; i++)
                    arr[i][5] = 1;

    for(int i = 1; i<6; i++)
                for (int j = 4; j>=5-i; j--)
                {
                    arr[i][j] = arr[i-1][j+1] + 1;
                }

            for(int i = 0; i<6; i++)
            {
                for (int j = 0; j<6; j++)
                {
                    if(arr[i][j] > 0)
                    System.out.print(arr[i][j] + " ");
                    else
                    System.out.print("  ");

                }
                    System.out.println("");
            }

            System.out.println("");

            int z = 0;
                for(int i = 5; i>=0; i--)
            {
                for(int k = 0; k<z; k++)
                System.out.print("  ");
                for (int j = 5; j>=0; j--)
                {
                    if(arr[i][j] > 0)
                    System.out.print(arr[i][j] + " ");

                }
                    System.out.println("");
                    z++;
            }

         }

        }

OUT:

          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1


问:
How does this for loop on consecutive integers work?
This seems like an embarrassingly easy concept but I can't understand why this for loop is working the way it is. The question is simply asking "Given a binary array, find the maximum number of consecutive 1s in this array."

```<code>def main(nums):
 count = 0
 for num in nums:
   if num == 1:
    count+=1
   else:
    count = 0
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
</code>```

My question is, why does this for loop work? I expected the loop to print out the total count of 1's.

答:
It's probably hard to believe, but could it be that the reason you are wondering why this loop works at all is that you are not familiar with Python ability to iterate over all elements of a list, not needing any counter variable increasing its value?

[1,1,0,1,1,1,0,0,1,1,1,1,1]

is in Python a kind of array storing multiple number of values.

Here some "pseudo-code" for explanatory purpose only demonstrating that "for num in nums" means in Python (in terms of programming in other
languages which don't support iteration over elements of a list/array):

```<code>noOfValuesIn_nums = lengthOf/sizeOf(nums)
for i = 0 to noOfValuesIn_nums do:
   # get i=th value from 'nums' and put it to a variable named 'num':
   num = nums[i]
   ...
</code>```

By the way: the loop provided in the question gives the desired result for the provided example:
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
but won't work on another one as demonstrated here:

```<code>def main(nums):
     count = 0
     for num in nums:
         if num == 1:
             count+=1
         else:
             count = 0
     return count

print( main([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# it prints 1 instead of 6
</code>```

The task of finding the longest consecutive sequence of ones
solves following code:

```<code>def main1(nums):
     count = 0
     maxOnes = 0
     for num in nums:
         if num == 1:
             count+=1
         else:
             if count > maxOnes:
                 maxOnes = count
             count = 0
     return maxOnes
print( main1([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# gives 6
</code>```

Body:
This seems like an embarrassingly easy concept but I can't understand why this for loop is working the way it is. The question is simply asking "Given a binary array, find the maximum number of consecutive 1s in this array."

def main(nums):
 count = 0
 for num in nums:
   if num == 1:
    count+=1
   else:
    count = 0
main([1,1,0,1,1,1,0,0,1,1,1,1,1])

My question is, why does this for loop work? I expected the loop to print out the total count of 1's.

Body:
It's probably hard to believe, but could it be that the reason you are wondering why this loop works at all is that you are not familiar with Python ability to iterate over all elements of a list, not needing any counter variable increasing its value?

[1,1,0,1,1,1,0,0,1,1,1,1,1]

is in Python a kind of array storing multiple number of values.

Here some "pseudo-code" for explanatory purpose only demonstrating that "for num in nums" means in Python (in terms of programming in other
languages which don't support iteration over elements of a list/array):

noOfValuesIn_nums = lengthOf/sizeOf(nums)
for i = 0 to noOfValuesIn_nums do:
   # get i=th value from 'nums' and put it to a variable named 'num':
   num = nums[i]
   ...

By the way: the loop provided in the question gives the desired result for the provided example:
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
but won't work on another one as demonstrated here:

def main(nums):
     count = 0
     for num in nums:
         if num == 1:
             count+=1
         else:
             count = 0
     return count

print( main([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# it prints 1 instead of 6

The task of finding the longest consecutive sequence of ones
solves following code:

def main1(nums):
     count = 0
     maxOnes = 0
     for num in nums:
         if num == 1:
             count+=1
         else:
             if count > maxOnes:
                 maxOnes = count
             count = 0
     return maxOnes
print( main1([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# gives 6


问:
How to debug firebase web app locally
I need to build a Cloud Function, so i am trying to set up a developer environment where i can test and debug a firebase function.

From the examples i saw, it all ends up setting up a nodejs node. Because i can't run the node directly, i need to use firebase CLI to start it, so i can't use any local debug.

The best thing i can come with is to put the code in html page and use the browser native debug, which is ok, but database handlers do not work.

Debugging on the server, looks to complicated for short cycles.

Is there a better way to debug it locally?

Update: database handlers work, but only while code is running. Can be triggered if the target object is changed during the same execution.

答:
You seem to be confusing two pieces of your app:

the web app, which is served from Firebase Hosting's servers, but runs in your user's browsers

the functions, which run on Google Cloud's servers

To debug your web app locally, you can use firebase serve (similar to how you use firebase deploy to deploy it). Then open the site in your browser (it defaults to http://localhost:5000) and debug it using your browser's developer tools.

To debug your Cloud Functions for Firebase locally, there is an emulator. See the documentation for more info and the answer here: how to test Cloud Functions for Firebase locally on pc.

Title: How to debug firebase web app locally

ContentLicense: CC BY-SA 4.0