问:
Does promise-chaining guarantee that a callback of the next promise is called only after preceding one is finished?
I met an article about promises in js, where the author shows a piece of code:

```<code>// I want to remove() all docs
db.allDocs({include_docs: true}).then(function (result) {
  result.rows.forEach(function (row) {
    db.remove(row.doc);
  });
}).then(function () {
  // I naively believe all docs have been removed() now!
});
</code>```

and says

What's the problem with this code? The problem is that the first
  function is actually returning undefined, meaning that the second
  function isn't waiting for db.remove() to be called on all the
  documents. In fact, it isn't waiting on anything, and can execute when
  any number of docs have been removed!

So, as I understood, if the second callback function() {} accepts no arguments, it actually doesn't wait for the end of the callback function(result). Am I inferring correctly? Because when I run the following piece of code, it gives me an opposite result:

```<code>var array = [];
for ( let i = 0; i < 1000; i++ )
    array.push(i);

var promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve(), 1000);
});

promise
.then(() => array.forEach(item => console.log(item)))
.then(() => console.log("invoked earlier"));
</code>```

I wait for "invoked earlier" to appear in the middle of printed numbers. But doesn't matter how large the number of items is. "Invoked earlier" appears always at the end. Can someone explain me what I am missing? Maybe the article is outdated and something has changed since then?

答:
In order to guarantee this, you actually have to return promises from the previous promise.

Whatever you return from a promise will be passed into the next promise.

In your case, you're returning undefined.

If, instead, you returned a promise, then the promise would be resolved, and the second promise would run after that happened, and would be passed whatever value the promise resolved with.

So yes, promises are guaranteed to run one after another, but if you choose to do something async inside of their callback, and don't bother chaining it back into the promise by returning it, then they're not going to bother to wait for anything (because they don't know that there's anything to wait for).

I'm assuming db.remove returns a promise...

...so, knowing that we have to return a promise from the callback, in order for it to actually wait for async stuff to happen, I would do something like this.

```<code>.then(result => Promise.all(result.rows.map(row => db.remove(row.doc))))
.then((listOfRemoves) => console.log(`removed`));
</code>```

Whether the second function takes 1 argument or 0 arguments is 100% inconsequential as to when the second function runs.

Edit

examples:

```<code>.then(() => setTimeout(() => console.log('2nd', 20000)))
.then(() => console.log('first'));
</code>```

This happens because the first then has NO idea that there is a setTimeout happening. It's not a mind-reader, it just runs the code and passes the return value along (in this case, undefined).

If the return value happens to be a promise, though, it will wait until that promise is done, get the value from it, and pass that on.

```<code>.then(() => new Promise(resolve => setTimeout(resolve, 20000)))
.then(() => console.log('I waited 20 seconds.'));
</code>```

Because it's returning a promise, it will call the then of that promise, and wait to get the value, to pass on.

The reason your tests are failing is because you're basically doing this.

```<code>.then(() => console.log('first'))
.then(() => console.log('second'));
</code>```

These are guaranteed to fire in this order. Period.
All of the other ones have been firing in that order as well. It's just that they are also scheduling async processes, just like all other callbacks/timeouts that use async I/O in JS.

Body:
I met an article about promises in js, where the author shows a piece of code:

// I want to remove() all docs
db.allDocs({include_docs: true}).then(function (result) {
  result.rows.forEach(function (row) {
    db.remove(row.doc);
  });
}).then(function () {
  // I naively believe all docs have been removed() now!
});

and says

What's the problem with this code? The problem is that the first
  function is actually returning undefined, meaning that the second
  function isn't waiting for db.remove() to be called on all the
  documents. In fact, it isn't waiting on anything, and can execute when
  any number of docs have been removed!

So, as I understood, if the second callback function() {} accepts no arguments, it actually doesn't wait for the end of the callback function(result). Am I inferring correctly? Because when I run the following piece of code, it gives me an opposite result:

var array = [];
for ( let i = 0; i < 1000; i++ )
    array.push(i);

var promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve(), 1000);
});

promise
.then(() => array.forEach(item => console.log(item)))
.then(() => console.log("invoked earlier"));

I wait for "invoked earlier" to appear in the middle of printed numbers. But doesn't matter how large the number of items is. "Invoked earlier" appears always at the end. Can someone explain me what I am missing? Maybe the article is outdated and something has changed since then?

Body:
In order to guarantee this, you actually have to return promises from the previous promise.

Whatever you return from a promise will be passed into the next promise.

In your case, you're returning undefined.

If, instead, you returned a promise, then the promise would be resolved, and the second promise would run after that happened, and would be passed whatever value the promise resolved with.

So yes, promises are guaranteed to run one after another, but if you choose to do something async inside of their callback, and don't bother chaining it back into the promise by returning it, then they're not going to bother to wait for anything (because they don't know that there's anything to wait for).

I'm assuming db.remove returns a promise...

...so, knowing that we have to return a promise from the callback, in order for it to actually wait for async stuff to happen, I would do something like this.

.then(result => Promise.all(result.rows.map(row => db.remove(row.doc))))
.then((listOfRemoves) => console.log(`removed`));

Whether the second function takes 1 argument or 0 arguments is 100% inconsequential as to when the second function runs.

Edit

examples:

.then(() => setTimeout(() => console.log('2nd', 20000)))
.then(() => console.log('first'));

This happens because the first then has NO idea that there is a setTimeout happening. It's not a mind-reader, it just runs the code and passes the return value along (in this case, undefined).

If the return value happens to be a promise, though, it will wait until that promise is done, get the value from it, and pass that on.

.then(() => new Promise(resolve => setTimeout(resolve, 20000)))
.then(() => console.log('I waited 20 seconds.'));

Because it's returning a promise, it will call the then of that promise, and wait to get the value, to pass on.

The reason your tests are failing is because you're basically doing this.

.then(() => console.log('first'))
.then(() => console.log('second'));

These are guaranteed to fire in this order. Period.
All of the other ones have been firing in that order as well. It's just that they are also scheduling async processes, just like all other callbacks/timeouts that use async I/O in JS.


来源: stackexchange

问:
rain plugin in jquery?
I need to breeze rain are petals of flowers as whole through my website. Now i am currently showering show by using snowfall jquery plugin.

Is there is any plugin to shower rain or petals of flowers.

答:
How about this: http://rain-demo.heroku.com/

Library is here: https://github.com/juliocesar/rain.js

ContentLicense: CC BY-SA 2.5

Title: rain plugin in jquery?


问:
pyspark ImportError: cannot import name accumulators
Goal: I am trying to get apache-spark pyspark to be appropriately interpreted within my pycharm IDE.

Problem: I currently receive the following error:

```<code>ImportError: cannot import name accumulators
</code>```

I was following the following blog to help me through the process. http://renien.github.io/blog/accessing-pyspark-pycharm/

Due to the fact my code was taking the except path I personally got rid of the try: except: just to see what the exact error was.

Prior to this I received the following error:

```<code>ImportError: No module named py4j.java_gateway
</code>```

This was fixed simply by typing '$sudo pip install py4j' in bash.

My code currently looks like the following chunk:

```<code>import os
import sys

# Path for spark source folder
os.environ['SPARK_HOME']="[MY_HOME_DIR]/spark-1.2.0"

# Append pyspark to Python Path
sys.path.append("[MY_HOME_DIR]/spark-1.2.0/python/")

try:
    from pyspark import SparkContext
    print ("Successfully imported Spark Modules")

except ImportError as e:
    print ("Can not import Spark Modules", e)
    sys.exit(1)
</code>```

My Questions:

    1. What is the source of this error? What is the cause?
    2. How do I remedy the issue so I can run pyspark in my pycharm editor.

NOTE: The current interpreter I use in pycharm is Python 2.7.8 (~/anaconda/bin/python)

Thanks ahead of time!

Don

答:
Only thing worked out for me is, go to base folder of spark. then go to accumulators.py

In beginning, there was wrong multi line command used. remove everything.

you're good to go!

ContentLicense: CC BY-SA 3.0

Body:
Goal: I am trying to get apache-spark pyspark to be appropriately interpreted within my pycharm IDE.

Problem: I currently receive the following error:

ImportError: cannot import name accumulators

I was following the following blog to help me through the process. http://renien.github.io/blog/accessing-pyspark-pycharm/

Due to the fact my code was taking the except path I personally got rid of the try: except: just to see what the exact error was.

Prior to this I received the following error:

ImportError: No module named py4j.java_gateway

This was fixed simply by typing '$sudo pip install py4j' in bash.

My code currently looks like the following chunk:

import os
import sys

# Path for spark source folder
os.environ['SPARK_HOME']="[MY_HOME_DIR]/spark-1.2.0"

# Append pyspark to Python Path
sys.path.append("[MY_HOME_DIR]/spark-1.2.0/python/")

try:
    from pyspark import SparkContext
    print ("Successfully imported Spark Modules")

except ImportError as e:
    print ("Can not import Spark Modules", e)
    sys.exit(1)

My Questions:

    1. What is the source of this error? What is the cause?
    2. How do I remedy the issue so I can run pyspark in my pycharm editor.

NOTE: The current interpreter I use in pycharm is Python 2.7.8 (~/anaconda/bin/python)

Thanks ahead of time!

Don


问:
Unity 2D - Rotate object and limiting the rotation
I'm trying to do a rotating cannon which rotates back and forward.
I want to limit the rotation from -55 to 55 (i mean transform.position.z), but i can't make it work.

For the moment my code is:

```<code>public class Cannon : MonoBehaviour
{
    bool hit = false;

    void Update ()
    {
        float angle = transform.rotation.z;
        if (angle > -55 & angle < 55 & !hit)
        {
            transform.Rotate(Vector3.back * Time.deltaTime);
        }

        if (angle <= -55)
        {
            transform.Rotate(Vector3.back * Time.deltaTime);
            hit = true;
        }
        if (angle >= 55)
        {
            transform.Rotate(Vector3.forward * Time.deltaTime);
            hit = true;
        }
    }
}
</code>```

The only think that is working is the first rotation which I've done for the object to start rotating, so it just rotates back and don't stop, it seems to be ignoring "angle"

I've also tried to put the last 2 If statements, inside the first one but still not working.

I want to make it rotate until it hit -55, then start rotating until it hits +55 and repeat this.

答:
The first thing you need to do is to use Euler Angles rather than Quarternions to find the rotation in degrees.

Then, since it doesn't report negative angles but rather angles from 0 to 360, you will need to subtract 360 whenever greater than 180 to get the negative angle equivalent.

From there you can apply your test to keep it in bounds:

```<code>public class Cannon : MonoBehaviour {

    public float direction = 1f; // initial direction
    public float speed = 20f; // speed of rotation

    void Update ()
    {
        float angle = transform.eulerAngles.z;
        if (angle > 180f) angle -= 360f;

        if ((angle < -55f) || (angle > 55f)) direction *= -1f; // reverse direction (toggles between 1 & -1)

        transform.Rotate (0, 0, speed * direction * Time.deltaTime);
    }
}
</code>```

Body:
I'm trying to do a rotating cannon which rotates back and forward.
I want to limit the rotation from -55 to 55 (i mean transform.position.z), but i can't make it work.

For the moment my code is:

public class Cannon : MonoBehaviour
{
    bool hit = false;

    void Update ()
    {
        float angle = transform.rotation.z;
        if (angle > -55 & angle < 55 & !hit)
        {
            transform.Rotate(Vector3.back * Time.deltaTime);
        }

        if (angle <= -55)
        {
            transform.Rotate(Vector3.back * Time.deltaTime);
            hit = true;
        }
        if (angle >= 55)
        {
            transform.Rotate(Vector3.forward * Time.deltaTime);
            hit = true;
        }
    }
}

The only think that is working is the first rotation which I've done for the object to start rotating, so it just rotates back and don't stop, it seems to be ignoring "angle"

I've also tried to put the last 2 If statements, inside the first one but still not working.

I want to make it rotate until it hit -55, then start rotating until it hits +55 and repeat this.

Body:
The first thing you need to do is to use Euler Angles rather than Quarternions to find the rotation in degrees.

Then, since it doesn't report negative angles but rather angles from 0 to 360, you will need to subtract 360 whenever greater than 180 to get the negative angle equivalent.

From there you can apply your test to keep it in bounds:

public class Cannon : MonoBehaviour {

    public float direction = 1f; // initial direction
    public float speed = 20f; // speed of rotation

    void Update ()
    {
        float angle = transform.eulerAngles.z;
        if (angle > 180f) angle -= 360f;

        if ((angle < -55f) || (angle > 55f)) direction *= -1f; // reverse direction (toggles between 1 & -1)

        transform.Rotate (0, 0, speed * direction * Time.deltaTime);
    }
}


问:
is it possible to detect idle use on php like detecting in JavaScript even for mouse focus
However there are lots of ways in PHP to logout the application when user is idle using session i am using

while login

```<code>$_SESSION['last_activity']=time()+10;
</code>```

in header

```<code>$expire_time = 10; //10 secs
if($_SESSION['last_activity'] < time()-$expire_time) {
    echo 'session destroyed';
}
else {
    $_SESSION['last_activity'] = time();
}
</code>```

this function logs out the user based on user clicks or refreshing the page even on tabs, but not mouse events which is possible in javascript

```<code>var IDLE_TIMEOUT = 900; //seconds
var _idleSecondsCounter = 0;

document.onclick = function () {
    _idleSecondsCounter = 0;
};

document.onmousemove = function () {
    _idleSecondsCounter = 0;
};

document.onkeypress = function () {
    _idleSecondsCounter = 0;
};

window.setInterval(CheckIdleTime, 1000);

function CheckIdleTime() {
    _idleSecondsCounter++;
    var oPanel = document.getElementById("SecondsUntilExpire");
    if (oPanel)
        oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
    if (_idleSecondsCounter >= IDLE_TIMEOUT) {
       alert('Times up!, You are idle for about 15 minutes, Please login to continue');
        document.location.href = "logout.php";
    }
}
</code>```

but this wont work across the project or tabs, if user keeps a tab idle and works on another tab the whole project would get logged out, is there any way to make this script works globally or make php to detect all events.

答:
You may use JavaScript local storage API

With local storage, web applications can store data locally within the user's browser.

Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

```<code>var IDLE_TIMEOUT = 900; //seconds
    sessionStorage.idleSecondCounter =  0;

document.onclick = function () {
    sessionStorage.idleSecondCounter = 0;
};

document.onmousemove = function () {
    sessionStorage.idleSecondCounter = 0;
};

document.onkeypress = function () {
    sessionStorage.idleSecondCounter = 0;
};

window.setInterval(CheckIdleTime, 1000);

function CheckIdleTime() {
    sessionStorage.idleSecondCounter = parseInt(sessionStorage.idleSecondCounter)+1;
    var oPanel = document.getElementById("SecondsUntilExpire");
    if (oPanel)
        oPanel.innerHTML = (IDLE_TIMEOUT - sessionStorage.idleSecondCounter) + "";
    if (sessionStorage.idleSecondCounter >= IDLE_TIMEOUT) {
       alert('Times up!, You are idle for about 15 minutes, Please login to continue');
        document.location.href = "logout.php";
    }
}
</code>```

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.

Body:
However there are lots of ways in PHP to logout the application when user is idle using session i am using

while login

$_SESSION['last_activity']=time()+10;

in header

$expire_time = 10; //10 secs
if($_SESSION['last_activity'] < time()-$expire_time) {
    echo 'session destroyed';
}
else {
    $_SESSION['last_activity'] = time();
}

this function logs out the user based on user clicks or refreshing the page even on tabs, but not mouse events which is possible in javascript

var IDLE_TIMEOUT = 900; //seconds
var _idleSecondsCounter = 0;

document.onclick = function () {
    _idleSecondsCounter = 0;
};

document.onmousemove = function () {
    _idleSecondsCounter = 0;
};

document.onkeypress = function () {
    _idleSecondsCounter = 0;
};

window.setInterval(CheckIdleTime, 1000);

function CheckIdleTime() {
    _idleSecondsCounter++;
    var oPanel = document.getElementById("SecondsUntilExpire");
    if (oPanel)
        oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
    if (_idleSecondsCounter >= IDLE_TIMEOUT) {
       alert('Times up!, You are idle for about 15 minutes, Please login to continue');
        document.location.href = "logout.php";
    }
}

but this wont work across the project or tabs, if user keeps a tab idle and works on another tab the whole project would get logged out, is there any way to make this script works globally or make php to detect all events.

Body:
You may use JavaScript local storage API

With local storage, web applications can store data locally within the user's browser.

Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

var IDLE_TIMEOUT = 900; //seconds
    sessionStorage.idleSecondCounter =  0;

document.onclick = function () {
    sessionStorage.idleSecondCounter = 0;
};

document.onmousemove = function () {
    sessionStorage.idleSecondCounter = 0;
};

document.onkeypress = function () {
    sessionStorage.idleSecondCounter = 0;
};

window.setInterval(CheckIdleTime, 1000);

function CheckIdleTime() {
    sessionStorage.idleSecondCounter = parseInt(sessionStorage.idleSecondCounter)+1;
    var oPanel = document.getElementById("SecondsUntilExpire");
    if (oPanel)
        oPanel.innerHTML = (IDLE_TIMEOUT - sessionStorage.idleSecondCounter) + "";
    if (sessionStorage.idleSecondCounter >= IDLE_TIMEOUT) {
       alert('Times up!, You are idle for about 15 minutes, Please login to continue');
        document.location.href = "logout.php";
    }
}

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.


问:
Strip day from elasticsearch date using painless scripting
I have date with this format November 17th 2016, 12:54:29.000" and I need to get that 17 only using painless script. Also if anyone can provide me link to painless script tutorial regarding date formats.

答:
If the field is mapped as date you can just

doc['<field_name>'].date.dayOfMonth.

Otherwise, you'll need to use a regular expression, something like

/ (\d{2})/.matcher(doc['<field_name>'].value).group(1).

The date-based solution uses org.joda.time.MutableDateTime. The regex one uses java.util.regex.Matcher and you have to enable regular expressions in your Elasticsearch configuration file as script.painless.regex.enabled=on.


问:
Why is my ruby case statement not working?
What's wrong with that?
Yes, I could make an if else statement, but I wanna do that with case statements.

In my Controller

```<code>query_limit = case current_user
                when nil
                  return 5
                when is_admin?
                  return 200
                when has_role?('registered')
                  return 20
                else
                  return 5
              end

NoMethodError (undefined method `is_admin?' for #<V1::MyController:123123123>):
</code>```

puts query_limit # is always ELSE when I do this:

```<code> query_limit = case current_user
                    when nil
                      return 5
                    when current_user.is_admin?
                      return 200
                    when current_user.has_role?('registered')
                      return 20
                    else
                      return 5
                  end
</code>```

Model User

```<code>class User
  def is_admin?
    self.has_role?('administrator')
  end

  def has_role?(the_role)
    self.roles.any? {|role| role.slug == the_role}
  end
end
</code>```

答:
A case statement works by comparing the given value against the values of the when statements (using ===). So case current_user; when current_user.is_admin? checks whether current_user is equal to current_user.is_admin?, which it's obviously not going to be.

Basically

```<code>case x
  when y
    case1
  when z
    case2
  ...
end
</code>```

is equivalent to

```<code>if y === x
  case1
elsif z === x
  case2
...
end
</code>```

If that structure does not fit your use case, you should use case.

PS: return returns from the current method, so it's not what you want here.

PPS: You can also use case without an expression as a different way to write an arbitrary if-elsif chain. So you could do what you want like this:

```<code>query_limit = case
  when current_user == nil
    5
  when current_user.is_admin?
    200
  ...
end
</code>```

But of course you can also just use a plain if-elsif for this. It's really just a matter of preference.

Body:
What's wrong with that?
Yes, I could make an if else statement, but I wanna do that with case statements.

In my Controller

query_limit = case current_user
                when nil
                  return 5
                when is_admin?
                  return 200
                when has_role?('registered')
                  return 20
                else
                  return 5
              end

NoMethodError (undefined method `is_admin?' for #<V1::MyController:123123123>):

puts query_limit # is always ELSE when I do this:

 query_limit = case current_user
                    when nil
                      return 5
                    when current_user.is_admin?
                      return 200
                    when current_user.has_role?('registered')
                      return 20
                    else
                      return 5
                  end

Model User

class User
  def is_admin?
    self.has_role?('administrator')
  end

  def has_role?(the_role)
    self.roles.any? {|role| role.slug == the_role}
  end
end

Body:
A case statement works by comparing the given value against the values of the when statements (using ===). So case current_user; when current_user.is_admin? checks whether current_user is equal to current_user.is_admin?, which it's obviously not going to be.

Basically

case x
  when y
    case1
  when z
    case2
  ...
end

is equivalent to

if y === x
  case1
elsif z === x
  case2
...
end

If that structure does not fit your use case, you should use case.

PS: return returns from the current method, so it's not what you want here.

PPS: You can also use case without an expression as a different way to write an arbitrary if-elsif chain. So you could do what you want like this:

query_limit = case
  when current_user == nil
    5
  when current_user.is_admin?
    200
  ...
end

But of course you can also just use a plain if-elsif for this. It's really just a matter of preference.


问:
how to save dynamically changed ( byjquery ) html DOM?
I got some nice layout generator using jquery dynamic forms, and jquery ui features to change number of used elements, their css properties etc. Everything looks great but there is one problem with presentation of current result. I would like to save generated html DOM and parse it somehow ( delete hidden elements from DOM tree etc ). Any ideas how to save current (modified) html + css?</p>

答:
As a first step you can use

```<code>var $alteredHtml = $('html').clone();
// use jQuery here to make alterations to the cloned html (parse it)
</code>```

but to save it you will need some server side technology, to either save it to a file or a database.

Body:
As a first step you can use

var $alteredHtml = $('html').clone();
// use jQuery here to make alterations to the cloned html (parse it)

but to save it you will need some server side technology, to either save it to a file or a database.


问:
XSD Validaton keyref value not found for identity constraint
I've got some troubles with XSD keyref validation which should run easily.
Here is my XML:

```<code><Configuration>
    <Dependencies>
        <Dependency name="python"></Dependency>
    </Dependencies>
    <Plugins>
        <Plugin>
            <Dependencies>
                <Dependency name="python"></Dependency>
            </Dependencies>
        </Plugin>
    </Plugins>
</Configuration>
</code>```

And now my Schema (please not the key.keyref pair in the Configuration element):

```<code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Configuration">
        <xs:complexType>
            <xs:sequence minOccurs="1" maxOccurs="1">
                <xs:element name="Dependencies" type="DependenciesType"></xs:element>
                <xs:element name="Plugins">
                    <xs:complexType>
                        <xs:sequence minOccurs="1" maxOccurs="unbounded">
                            <xs:element name="Plugin" type="PluginType" minOccurs="1" maxOccurs="unbounded"></xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>

        <xs:key name="kDependency">
            <xs:selector xpath="./Dependencies/Dependency"></xs:selector>
            <xs:field xpath="@name"></xs:field>
        </xs:key>
        <xs:keyref name="krPluginDependency" refer="kDependency">
            <xs:selector xpath="./Plugins/Plugin/Dependencies/Dependency"></xs:selector>
            <xs:field xpath="@name"></xs:field>
        </xs:keyref>

    </xs:element>

    <!-- Now the Dependencies types -->

    <xs:complexType name="DependenciesType">
        <xs:sequence>
            <xs:element minOccurs="1" maxOccurs="unbounded" name="Dependency" type="DependencyType"></xs:element>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="DependencyType">
        <xs:attribute name="name" type="xs:string" use="required"/>
    </xs:complexType>

    <!-- And the plugin type -->

    <xs:complexType name="PluginType">
        <xs:sequence>
            <xs:element name="Dependencies" minOccurs="1" maxOccurs="1">
                <xs:complexType>
                    <xs:sequence minOccurs="1" maxOccurs="1">
                        <xs:element name="Dependency" minOccurs="1" maxOccurs="unbounded">
                            <xs:complexType>
                                <xs:attribute name="name"></xs:attribute>
                            </xs:complexType>
                        </xs:element>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>

</xs:schema>
</code>```

The plugin dependencies name has to refer to Configuration dependencies name. I followed the tutorial here in order to check if I am not fool (http://zvon.org/xxl/XMLSchemaTutorial/Output/ser_keys_st5.html). I checked my XPath expression and they are good (https://www.freeformatter.com/xpath-tester.html).

When I try to validate my XML file:

Key 'krPluginDependency' with value 'python' not found for identity constraint of element 'Configuration'.

I do not know where is the problem.

答:
Okay, it was really ridiculous error.
In PluginType Dependency type, the attribute name needs a type. In my case, it is type="xs:string" and it works fine.

Body:
I've got some troubles with XSD keyref validation which should run easily.
Here is my XML:

<Configuration>
    <Dependencies>
        <Dependency name="python"></Dependency>
    </Dependencies>
    <Plugins>
        <Plugin>
            <Dependencies>
                <Dependency name="python"></Dependency>
            </Dependencies>
        </Plugin>
    </Plugins>
</Configuration>

And now my Schema (please not the key.keyref pair in the Configuration element):

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Configuration">
        <xs:complexType>
            <xs:sequence minOccurs="1" maxOccurs="1">
                <xs:element name="Dependencies" type="DependenciesType"></xs:element>
                <xs:element name="Plugins">
                    <xs:complexType>
                        <xs:sequence minOccurs="1" maxOccurs="unbounded">
                            <xs:element name="Plugin" type="PluginType" minOccurs="1" maxOccurs="unbounded"></xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>

        <xs:key name="kDependency">
            <xs:selector xpath="./Dependencies/Dependency"></xs:selector>
            <xs:field xpath="@name"></xs:field>
        </xs:key>
        <xs:keyref name="krPluginDependency" refer="kDependency">
            <xs:selector xpath="./Plugins/Plugin/Dependencies/Dependency"></xs:selector>
            <xs:field xpath="@name"></xs:field>
        </xs:keyref>

    </xs:element>

    <xs:complexType name="DependenciesType">
        <xs:sequence>
            <xs:element minOccurs="1" maxOccurs="unbounded" name="Dependency" type="DependencyType"></xs:element>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="DependencyType">
        <xs:attribute name="name" type="xs:string" use="required"/>
    </xs:complexType>

    <xs:complexType name="PluginType">
        <xs:sequence>
            <xs:element name="Dependencies" minOccurs="1" maxOccurs="1">
                <xs:complexType>
                    <xs:sequence minOccurs="1" maxOccurs="1">
                        <xs:element name="Dependency" minOccurs="1" maxOccurs="unbounded">
                            <xs:complexType>
                                <xs:attribute name="name"></xs:attribute>
                            </xs:complexType>
                        </xs:element>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>

</xs:schema>

The plugin dependencies name has to refer to Configuration dependencies name. I followed the tutorial here in order to check if I am not fool (http://zvon.org/xxl/XMLSchemaTutorial/Output/ser_keys_st5.html). I checked my XPath expression and they are good (https://www.freeformatter.com/xpath-tester.html).

When I try to validate my XML file:

Key 'krPluginDependency' with value 'python' not found for identity constraint of element 'Configuration'.

I do not know where is the problem.


问:
Why to use removeCallbacks() with postDelayed()?
I'm trying to understand the functionality, and in particular, one particular reason why we use removeCallbacks()in conjunction with postDelayed() by going through the Fullscreen Activity template provided in Android Studio. In the fullscreen activity template, when the screen is touched it will show/hide the status bar and navigation/system bar after a certain number of milliseconds, and in this template's case 3000 milliseconds.

```<code>private void hide() {
    // Hide UI first
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.hide();
    }
    mControlsView.setVisibility(View.GONE);
    mVisible = false;

    // Schedule a runnable to remove the status and navigation bar after a delay
    mHideHandler.removeCallbacks(mShowPart2Runnable); // <------ Comment/uncomment
    mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}

@SuppressLint("InlinedApi")
private void show() {
    // Show the system bar
    mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
    mVisible = true;

    // Schedule a runnable to display UI elements after a delay
    mHideHandler.removeCallbacks(mHidePart2Runnable); // <------ Comment/uncomment
    mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}

/**
 * Schedules a call to hide() in [delay] milliseconds, canceling any
 * previously scheduled calls.
 */
private void delayedHide(int delayMillis) {
    mHideHandler.removeCallbacks(mHideRunnable); // <------ Comment/uncomment
    mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
</code>```

I understand that removeCallbacks() is used to remove the pending messages/runnables from the message queue but is there a particular reason why we would use it other than if a condition is met and we no longer want the pending messages/runnables to be executed?

I ask this because in regards to the Fullscreen Activity template I'm a bit confused here as it seems that if i don't call mHideHandler.removeCallbacks(Runnable) when using postDelayed() then it'll allow the user to spam the hide/show methods. With the spamming it looks like the transition animation is interrupted and that the animation may even get stuck during the spam because it was stopped at a certain point during the transition. However, if I do call mHideHandler.removeCallbacks(Runnable) right before postDelayed() then it'll prevent the users from spamming the hide/show methods, which is good.

I guess in short my question is how does mHideHandler.removeCallbacks(Runnable) prevent the spamming of methods being called when used with postDelayed()? Question is similar to this question but am hoping to get an explanation on why this occurs.

Here are the differences in .gif form. Using removeCallbacks() is the intended behaviour while commenting out removeCallbacks() leads to unwanted "abuse" behaviour:

With removeCallbacks()

Without removeCallbacks()

EDIT: Added in .gifs and added comments to the removeCallbacks() in the code to help identify which part of the code i'm talking about.

答:
Each time you perform a click you are posting an event to the MessageQueue, which will be executed after UI_ANIMATION_DELAY milliseconds (let's say it is 300ms).

Now, when you are performing consecutive clicks you are posting events in this way:

```<code>SHOW - HIDE - SHOW - HIDE - ...
</code>```

If you do not perform removeCallbacks(), all of these messages will be executed, meaning that each of those SHOW and HIDE actions would be performed, which results in such a glitchy behavior.

On the other hand, when using removeCallbacks() you are telling that you are no longer interested in the opposite event and do not want that event to be executed entirely. For example, if we have a situation when system bars are shown, then the next click would initiate a HIDE event to happen after 300 ms and you are explicitly telling, that "hey, if there are some events posted that should SHOW the system bar, then cancel them"

```<code>handler.removeCallbacks(showRunnable);
handler.postDelayed(hide, 300);
</code>```

What this gives you, is that each time you perform consecutive click events, the opposite event message that was already posted on the queue would be cancelled. This assures, that each time only 1 message is posted on the queue.

System UI is visible, current message queue:

```<code>EMPTY
</code>```

Click happens:

```<code>HIDE
</code>```

Click happens:

```<code>SHOW (HIDE is being removed from queue)
</code>```

Click happens:

```<code>HIDE (SHOW is being removed from queue)
</code>```

Thus, at the end, when 300ms are passed and this message is not removed from queue, only the last event would be executed.

Body:
I'm trying to understand the functionality, and in particular, one particular reason why we use removeCallbacks()in conjunction with postDelayed() by going through the Fullscreen Activity template provided in Android Studio. In the fullscreen activity template, when the screen is touched it will show/hide the status bar and navigation/system bar after a certain number of milliseconds, and in this template's case 3000 milliseconds.

private void hide() {
    // Hide UI first
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.hide();
    }
    mControlsView.setVisibility(View.GONE);
    mVisible = false;

    // Schedule a runnable to remove the status and navigation bar after a delay
    mHideHandler.removeCallbacks(mShowPart2Runnable); // <------ Comment/uncomment
    mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}

@SuppressLint("InlinedApi")
private void show() {
    // Show the system bar
    mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
    mVisible = true;

    // Schedule a runnable to display UI elements after a delay
    mHideHandler.removeCallbacks(mHidePart2Runnable); // <------ Comment/uncomment
    mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}

/**
 * Schedules a call to hide() in [delay] milliseconds, canceling any
 * previously scheduled calls.
 */
private void delayedHide(int delayMillis) {
    mHideHandler.removeCallbacks(mHideRunnable); // <------ Comment/uncomment
    mHideHandler.postDelayed(mHideRunnable, delayMillis);
}

I understand that removeCallbacks() is used to remove the pending messages/runnables from the message queue but is there a particular reason why we would use it other than if a condition is met and we no longer want the pending messages/runnables to be executed?

I ask this because in regards to the Fullscreen Activity template I'm a bit confused here as it seems that if i don't call mHideHandler.removeCallbacks(Runnable) when using postDelayed() then it'll allow the user to spam the hide/show methods. With the spamming it looks like the transition animation is interrupted and that the animation may even get stuck during the spam because it was stopped at a certain point during the transition. However, if I do call mHideHandler.removeCallbacks(Runnable) right before postDelayed() then it'll prevent the users from spamming the hide/show methods, which is good.

I guess in short my question is how does mHideHandler.removeCallbacks(Runnable) prevent the spamming of methods being called when used with postDelayed()? Question is similar to this question but am hoping to get an explanation on why this occurs.

Here are the differences in .gif form. Using removeCallbacks() is the intended behaviour while commenting out removeCallbacks() leads to unwanted "abuse" behaviour:

With removeCallbacks()

Without removeCallbacks()

EDIT: Added in .gifs and added comments to the removeCallbacks() in the code to help identify which part of the code i'm talking about.

Body:
Each time you perform a click you are posting an event to the MessageQueue, which will be executed after UI_ANIMATION_DELAY milliseconds (let's say it is 300ms).

Now, when you are performing consecutive clicks you are posting events in this way:

SHOW - HIDE - SHOW - HIDE - ...

If you do not perform removeCallbacks(), all of these messages will be executed, meaning that each of those SHOW and HIDE actions would be performed, which results in such a glitchy behavior.

On the other hand, when using removeCallbacks() you are telling that you are no longer interested in the opposite event and do not want that event to be executed entirely. For example, if we have a situation when system bars are shown, then the next click would initiate a HIDE event to happen after 300 ms and you are explicitly telling, that "hey, if there are some events posted that should SHOW the system bar, then cancel them"

handler.removeCallbacks(showRunnable);
handler.postDelayed(hide, 300);

What this gives you, is that each time you perform consecutive click events, the opposite event message that was already posted on the queue would be cancelled. This assures, that each time only 1 message is posted on the queue.

System UI is visible, current message queue:

EMPTY

Click happens:

HIDE

Click happens:

SHOW (HIDE is being removed from queue)

Click happens:

HIDE (SHOW is being removed from queue)

Thus, at the end, when 300ms are passed and this message is not removed from queue, only the last event would be executed.


问:
Exiting an infinite process in python subprocess
i have the following code

```<code>c = open("text.txt", 'a')

output = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE).communicate()[0]

c.write(str(output))
</code>```

But as the ping is infinite , the code stucks at line two till i close the cmd

how can i close the infinite subprocess

i use python 2

答:
You can use -n argument (in linux) for ping to set limited number of ping signals:

```<code>process = subprocess.Popen('ping -n 1 127.0.0.1', shell=True, stdout=subprocess.PIPE)
output = process.communicate()[0]
with open("text.txt", 'a') as f:
    f.write(str(output))
</code>```

Or read a single first line only:

```<code>process = subprocess.Popen('ping 127.0.0.1', shell=True, stdout=subprocess.PIPE, universal_newlines=True)

output = process.stdout.readline()
process.stdout.close()
process.kill()

with open("text.txt", 'a') as f:
    f.write(str(output))
</code>```

Body:
i have the following code

c = open("text.txt", 'a')

output = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE).communicate()[0]

c.write(str(output))

But as the ping is infinite , the code stucks at line two till i close the cmd

how can i close the infinite subprocess

i use python 2

Body:
You can use -n argument (in linux) for ping to set limited number of ping signals:

process = subprocess.Popen('ping -n 1 127.0.0.1', shell=True, stdout=subprocess.PIPE)
output = process.communicate()[0]
with open("text.txt", 'a') as f:
    f.write(str(output))

Or read a single first line only:

process = subprocess.Popen('ping 127.0.0.1', shell=True, stdout=subprocess.PIPE, universal_newlines=True)

output = process.stdout.readline()
process.stdout.close()
process.kill()

with open("text.txt", 'a') as f:
    f.write(str(output))


问:
How to execute a callback only if previous observable returns specific value
Suppose I have 3 functions each returning an observable. Each observable will emit only one value - true or false. I want to call them one after another only if the previous one returns true. Otherwise, I just want to return false and end the observable. How can I do that?

It would be quite easy with promises:

```<code>return fn1().then(fn2).then(fn3).catch((v)=>{return v})
</code>```

As soon as any function in the chain rejects the promise with false no other promise callbacks will be called and the resolved promise value will be false. I'm looking for something similar with observables.

答:
You can use concatMap() to execute async tasks in order and then takeWhile() to complete the stream if necessary:

```<code>fn1()
  .takeWhile(res => res)
  .concatMap(() => fn2())
  .takeWhile(res => res)
  .concatMap(() => fn3())
  .takeWhile(res => res)
  .subscribe(...)
</code>```

Body:
Suppose I have 3 functions each returning an observable. Each observable will emit only one value - true or false. I want to call them one after another only if the previous one returns true. Otherwise, I just want to return false and end the observable. How can I do that?

It would be quite easy with promises:

return fn1().then(fn2).then(fn3).catch((v)=>{return v})

As soon as any function in the chain rejects the promise with false no other promise callbacks will be called and the resolved promise value will be false. I'm looking for something similar with observables.

Body:
You can use concatMap() to execute async tasks in order and then takeWhile() to complete the stream if necessary:

fn1()
  .takeWhile(res => res)
  .concatMap(() => fn2())
  .takeWhile(res => res)
  .concatMap(() => fn3())
  .takeWhile(res => res)
  .subscribe(...)


问:
How to use multiple ajax calendars in a single page
I am trying to use a calendar to insert dates. Unfortunately, I have to use more than one calendar. For extracting the date from the calendar, I am using Ajax toolkit

```<code>`<cc1:ToolkitScriptManager ID="ToolkitScriptManager1"  EnableScriptGlobalization="true" EnableScriptLocalization="true" runat="server">
            </cc1:ToolkitScriptManager>

<asp:TextBox ID="DateOfPurchase" runat="server"  Height="30px" ReadOnly="true" Width="262px"></asp:TextBox>

            <asp:ImageButton ID="imgPopup" ImageUrl="images/index.jpg" ImageAlign="Bottom"
            runat="server" Height="27px" Width="37px" />

            <cc1:CalendarExtender ID="Calendar1" PopupButtonID="imgPopup" runat="server" TargetControlID="DateOfPurchase"
            Format="dd/MM/yyyy">
            </cc1:CalendarExtender>`
</code>```

So whenever I add more than one
 <cc1:ToolkitScriptManager ID="ToolkitScriptManager1"    EnableScriptGlobalization="true" EnableScriptLocalization="true" runat="server">
            </cc1:ToolkitScriptManager>
my program shows error.
And if I use Only one ToolkitScriptManager and multiple  Ajax calendar controls, clicking on only one image button for displaying the calendar, all the calendars,on the page, pops up.

答:
Each CalendarExtender must have its own ID

```<code>        <asp:ImageButton ID="imgPopup1" ImageUrl="images/index.jpg" ImageAlign="Bottom"
        runat="server" Height="27px" Width="37px" />

        <cc1:CalendarExtender ID="Calendar1" PopupButtonID="imgPopup1" runat="server" TargetControlID="DateOfPurchase1"
        Format="dd/MM/yyyy">
        </cc1:CalendarExtender>`
</code>```

```<code>        <asp:ImageButton ID="imgPopup2" ImageUrl="images/index.jpg" ImageAlign="Bottom"
        runat="server" Height="27px" Width="37px" />

        <cc1:CalendarExtender ID="Calendar2" PopupButtonID="imgPopup2" runat="server" TargetControlID="DateOfPurchase2"
        Format="dd/MM/yyyy">
        </cc1:CalendarExtender>`
</code>```

Body:
I am trying to use a calendar to insert dates. Unfortunately, I have to use more than one calendar. For extracting the date from the calendar, I am using Ajax toolkit

`<cc1:ToolkitScriptManager ID="ToolkitScriptManager1"  EnableScriptGlobalization="true" EnableScriptLocalization="true" runat="server">
            </cc1:ToolkitScriptManager>

<asp:TextBox ID="DateOfPurchase" runat="server"  Height="30px" ReadOnly="true" Width="262px"></asp:TextBox>

            <asp:ImageButton ID="imgPopup" ImageUrl="images/index.jpg" ImageAlign="Bottom"
            runat="server" Height="27px" Width="37px" />

            <cc1:CalendarExtender ID="Calendar1" PopupButtonID="imgPopup" runat="server" TargetControlID="DateOfPurchase"
            Format="dd/MM/yyyy">
            </cc1:CalendarExtender>`

So whenever I add more than one
 <cc1:ToolkitScriptManager ID="ToolkitScriptManager1"    EnableScriptGlobalization="true" EnableScriptLocalization="true" runat="server">
            </cc1:ToolkitScriptManager>
my program shows error.
And if I use Only one ToolkitScriptManager and multiple  Ajax calendar controls, clicking on only one image button for displaying the calendar, all the calendars,on the page, pops up.

Body:
Each CalendarExtender must have its own ID

        <asp:ImageButton ID="imgPopup1" ImageUrl="images/index.jpg" ImageAlign="Bottom"
        runat="server" Height="27px" Width="37px" />

        <cc1:CalendarExtender ID="Calendar1" PopupButtonID="imgPopup1" runat="server" TargetControlID="DateOfPurchase1"
        Format="dd/MM/yyyy">
        </cc1:CalendarExtender>`

        <asp:ImageButton ID="imgPopup2" ImageUrl="images/index.jpg" ImageAlign="Bottom"
        runat="server" Height="27px" Width="37px" />

        <cc1:CalendarExtender ID="Calendar2" PopupButtonID="imgPopup2" runat="server" TargetControlID="DateOfPurchase2"
        Format="dd/MM/yyyy">
        </cc1:CalendarExtender>`


问:
Excel consolidate yields incorrect list of unique values
I have two columns that look like this:

```<code>Make/Model      Parc
Abarth*500      15
Abarth*500      19
Abarth*500      2
Abarth*500      14
Abarth*500      15
Abarth*500      25
Abarth*500      20
Abarth*500      17
Abarth*500C     12
Abarth*500C     16
Abarth*500C     23
Abarth*500C     18
Abarth*500C     1
Alfa Romeo*145  405
Alfa Romeo*145  431
Alfa Romeo*146  36
Alfa Romeo*146  80
Alfa Romeo*146  121
Alfa Romeo*146  72
Alfa Romeo*146  39
</code>```

etc...

The sum of the values in the "Parc" column is 10,475,387.

I perform a consolidate on this table to remove the repetitions in "Make/Model" and sum the values in the "Parc" column for each "Make/Model."

Once I perform the consolidation, everything looks as expected:

```<code>Make/Model      Parc
Abarth*500      127
Abarth*500C     70
Alfa Romeo*145  836
Alfa Romeo*146  348
Alfa Romeo*147  3848
Alfa Romeo*155  29
Alfa Romeo*156  3148
Alfa Romeo*159  573
Alfa Romeo*164  111
</code>```

etc...

So what's the problem? The new sum of the "Parc" column is 10,554,076! Verification against an alternate method indicates that the column of unique labels is incorrect in seemingly random places. I also do not understand how the total sum could have gone up. I have over 18,000 rows in this dataset so individually checking all of the data would be very time consuming.

You can find the full dataset here:
Excel File

What have I tried?

I have tried removing all formatting. Also, these numbers are all integers and the option to "Automatically insert a decimal point" is not checked. I have also tried creating a new column of =INT() values to ensure they are all integers. My results are exactly the same in all cases.

I posted this question yesterday and it was put on hold because it could not be reproduced without the full dataset: Excel consolidate sum yields different column total

EDIT:
As Mauricio Noris Freire has shown, you can create a unique item column using advanced filter, and then use SUMIF to solve this problem correctly. I still would like to know why the Excel data tool consolidate does not work as expected.

答:
Your observations are correct.  Both Consolidate and SUMIFS are being affected by the asterisks in your data.  If you remove the asterisks, or, as I did, replace them with a pipe | character, your totals will match.

You could also get a correct report by using a Pivot Table

Examine, for example the output for the Mercedes*190

In the raw data, we show these lines if we filter for that value:

In the Consolidation report, we see that the total for Mercedes*190 will include both that car, and also the Mercedes*A190.  In other words the A190 is being counted twice, because of the wild card issue.

I suspect this is some kind of design flaw.

Body:
I have two columns that look like this:

Make/Model      Parc
Abarth*500      15
Abarth*500      19
Abarth*500      2
Abarth*500      14
Abarth*500      15
Abarth*500      25
Abarth*500      20
Abarth*500      17
Abarth*500C     12
Abarth*500C     16
Abarth*500C     23
Abarth*500C     18
Abarth*500C     1
Alfa Romeo*145  405
Alfa Romeo*145  431
Alfa Romeo*146  36
Alfa Romeo*146  80
Alfa Romeo*146  121
Alfa Romeo*146  72
Alfa Romeo*146  39

etc...

The sum of the values in the "Parc" column is 10,475,387.

I perform a consolidate on this table to remove the repetitions in "Make/Model" and sum the values in the "Parc" column for each "Make/Model."

Once I perform the consolidation, everything looks as expected:

Make/Model      Parc
Abarth*500      127
Abarth*500C     70
Alfa Romeo*145  836
Alfa Romeo*146  348
Alfa Romeo*147  3848
Alfa Romeo*155  29
Alfa Romeo*156  3148
Alfa Romeo*159  573
Alfa Romeo*164  111

etc...

So what's the problem? The new sum of the "Parc" column is 10,554,076! Verification against an alternate method indicates that the column of unique labels is incorrect in seemingly random places. I also do not understand how the total sum could have gone up. I have over 18,000 rows in this dataset so individually checking all of the data would be very time consuming.

You can find the full dataset here:
Excel File

What have I tried?

I have tried removing all formatting. Also, these numbers are all integers and the option to "Automatically insert a decimal point" is not checked. I have also tried creating a new column of =INT() values to ensure they are all integers. My results are exactly the same in all cases.

I posted this question yesterday and it was put on hold because it could not be reproduced without the full dataset: Excel consolidate sum yields different column total

EDIT:
As Mauricio Noris Freire has shown, you can create a unique item column using advanced filter, and then use SUMIF to solve this problem correctly. I still would like to know why the Excel data tool consolidate does not work as expected.


问:
Read media\\:thumbnail RSS feed with Jquery
I'm writing a chrome extension and I'm trying to get the RSS feed "media:thumbnail" but the function el.find('media\:thumbnail').attr('url') outputs 'undefined'.

Here's my code :

```<code>$.get("http://www.reddit.com/.rss", function (data) {
    $(data).find("item").each(function () { // or "item" or whatever suits your feed
        var el = $(this);
        $("tbody").append("<tr><th>" + el.find('media\\:thumbnail').attr('url') + "</th><td>" + el.find("title").text() + "</td></tr>");
    });
});
</code>```

答:
I cannot believe that people do not understand this question and give an answer about something else.

The questioner does not mention CORS or any possible error that could point to it.

The question is simply asking about JQuery selectors on XML nodes rather than HTML, the fact that he is using AJAX to get an RSS feed is irelivant, so one can assume that CORS is not an issue in this case.

I had been struggling with the exact same thing, apparently double backslash is supposed to escape, but doesn't seem to work in this case.

What I did instead is use the JQuery attribute selector with the attribute url, all thumbnails have url attributes in my case.

So your code would be:

```<code>$.get("http://www.reddit.com/.rss", function (data) {
    $(data).find("item").each(function () { // or "item" or whatever suits your feed
        var el = $(this);
        $("tbody").append("<tr><th>" + el.find('[url]').attr('url') + "</th><td>" + el.find("title").text() + "</td></tr>");
    });
});
</code>```

Update

It might be better to use map

```<code>$.get("http://www.reddit.com/.rss", function (data) {
  var tbody = $('tbody');
  tbody.append(
    $(data).find("item").map(function () { // or "item" or whatever suits your feed
      var el = $(this);
      return $("<tr><th>" + el.find('[url]').attr('url') + "</th><td>" + el.find("title").text() + "</td></tr>");
    }).get()
  );
});
</code>```

I have tested it mind

Body:
I'm writing a chrome extension and I'm trying to get the RSS feed "media:thumbnail" but the function el.find('media\:thumbnail').attr('url') outputs 'undefined'.

Here's my code :

$.get("http://www.reddit.com/.rss", function (data) {
    $(data).find("item").each(function () { // or "item" or whatever suits your feed
        var el = $(this);
        $("tbody").append("
" + el.find('media\\:thumbnail').attr('url') + "	" + el.find("title").text() + "
");
    });
});

Body:
I cannot believe that people do not understand this question and give an answer about something else.

The questioner does not mention CORS or any possible error that could point to it.

The question is simply asking about JQuery selectors on XML nodes rather than HTML, the fact that he is using AJAX to get an RSS feed is irelivant, so one can assume that CORS is not an issue in this case.

I had been struggling with the exact same thing, apparently double backslash is supposed to escape, but doesn't seem to work in this case.

What I did instead is use the JQuery attribute selector with the attribute url, all thumbnails have url attributes in my case.

So your code would be:

$.get("http://www.reddit.com/.rss", function (data) {
    $(data).find("item").each(function () { // or "item" or whatever suits your feed
        var el = $(this);
        $("tbody").append("<tr><th>" + el.find('[url]').attr('url') + "</th><td>" + el.find("title").text() + "</td></tr>");
    });
});

Update

It might be better to use map

$.get("http://www.reddit.com/.rss", function (data) {
  var tbody = $('tbody');
  tbody.append(
    $(data).find("item").map(function () { // or "item" or whatever suits your feed
      var el = $(this);
      return $("<tr><th>" + el.find('[url]').attr('url') + "</th><td>" + el.find("title").text() + "</td></tr>");
    }).get()
  );
});

I have tested it mind


问:
sed command to delete a line with contain more than 10 character which not start with 91
I want sed command to delete a line from which which contain more than 10 number and which are not start with 91

My file content is like this

```<code>919876543210
789876543210
9012345678
12345678901
9865746321
</code>```

And need output like this.

```<code>919876543210
9012345678
9865746321
</code>```

I have tried awk 'length>=4' 1.txt | grep -v ^91

this will show me

```<code>789876543210
12345678901
</code>```

答:
What you can do:

ignore all lines starting with "91", /^91/!

otherwise delete anything with at least 11 characters

(assuming you do not care about the difference between digits, letters, whitespace...),

{/.........../d}

Altogether:

```<code>sed  '/^91/!{/.........../d}'
</code>```

With the -E it would be more elegantly possible.

(My sed is GNU sed version 4.2.1)

Body:
I want sed command to delete a line from which which contain more than 10 number and which are not start with 91

My file content is like this

919876543210
789876543210
9012345678
12345678901
9865746321

And need output like this.

919876543210
9012345678
9865746321

I have tried awk 'length>=4' 1.txt | grep -v ^91

this will show me

789876543210
12345678901

Body:
What you can do:

ignore all lines starting with "91", /^91/!

otherwise delete anything with at least 11 characters

(assuming you do not care about the difference between digits, letters, whitespace...),

{/.........../d}

Altogether:

sed  '/^91/!{/.........../d}'

With the -E it would be more elegantly possible.

(My sed is GNU sed version 4.2.1)


问:
Remove Some Character From Records Using SQL
I am having question mark symbol(?) in between first name and last name of Customers in some records, I want to replace all "?" with a space.</p>

```<code>UPDATE Customers
//What to write here?
WHERE Name LIKE '%?%';
</code>```

答:
Try this:

```<code>UPDATE customers set name= replace(name,'?', ' ') WHERE Name LIKE '%?%';
</code>```

(inverted parameters in replace)

Body:
I am having question mark symbol(?) in between first name and last name of Customers in some records, I want to replace all "?" with a space.

UPDATE Customers
//What to write here?
WHERE Name LIKE '%?%';

Body:
Try this:

UPDATE customers set name= replace(name,'?', ' ') WHERE Name LIKE '%?%';

(inverted parameters in replace)


问:
Modal window doesn’t seem to be working
Tried integrating the modal window here on the Lyric button: https://soundwhore.com/trance/tenishia-feat-adina-butar-dont-let-go/

However, nothing happens on click. Any idea, why this would not work?

Code here:

```<code><p class="meta-data">
  <a class="waves-effect waves-light btn-large red" href="#modal-lyric">
    <i class="material-icons left">subject</i>Lyrics
  </a>
  <a class="waves-effect waves-light btn-large amber accent-4" href="https://itunes.apple.com/us/album/dont-let-go-feat.-adina-butar/id1054325261?i=1054325265" target="_blank" title="Go to https://itunes.apple.com/us/album/dont-let-go-feat.-adina-butar/id1054325261?i=1054325265">
    <i class="material-icons left">shopping_cart</i>Buy now
  </a>
</p>
<div class="modal" id="modal-lyric">
  <div class="modal-content">
    <h4>Lyrics</h4>
    <p></p>
  </div>
  <div class="modal-footer">
    <a class="modal-action modal-close waves-effect waves-green btn-flat" href="#!">Done</a>
  </div>
</div>
</code>```

Source: http://materializecss.com/modals.html

答:
I think you just forgot to add the listener:</p>

```<code>  <script>
    $(document).ready(function() {
      $(".modal").modal()
    });
  </script>
</code>```

Title: Modal window doesn’t seem to be working

Body:
Tried integrating the modal window here on the Lyric button: https://soundwhore.com/trance/tenishia-feat-adina-butar-dont-let-go/

However, nothing happens on click. Any idea, why this would not work?

Code here:

    subjectLyrics

    shopping_cartBuy now

Lyrics

    Done

Source: http://materializecss.com/modals.html

Body:
I think you just forgot to add the listener:

  <script>
    $(document).ready(function() {
      $(".modal").modal()
    });
  </script>


问:
<reference> expected, unexpected end of file on PHPStorm
I am using PHPStorm and having some interesting errors/warnings showing up. Not sure if I skipped configuring something.
Here is a query for example,

```<code>$query  = "INSERT INTO tblperson (";
$query .= "  personName, personLname, personNumber, personPhone, personAttr";
$query .= ") VALUES (";
$query .= "  '{$personName}', '{$personLname}', {$personNumber}, {$personPhone}, '{$personAttr}'";
$query .= ")";
</code>```

And I get this warning: " expected, unexpected end of file" on first line of the code. Is there anything I am missing on this insert statement that PHPStorm warns me on?

When I run the code I can insert a record without any problems but still wonder maybe there might be an improvement that I am missing.

答:
Adding this here because the other answer only disables the inspection everywhere and not just for a particular statement.

This issue occurs because the editor loses context when the SQL statement is split over multiple strings.

There is no proper way to actually ignore this error for just a single statement in the editor.

This issue can be reproduced by having your SQL inspections turned on and having a dialect set for the file project.

One potential workaround is to have the beginning of your statement split.

For example, change the below statement from

```<code>$start = "INSERT IGNORE INTO table1(";
$mid = ") VALUES (";
$end = ")";
</code>```

to

```<code>$start = "INSERT " . "IGNORE INTO table1(";
$mid = ") VALUES (";
$end = ")";
</code>```

This'll trick PhpStorm into thinking that your statement is just another string instead of treating it as SQL and performing an inspection on it.

I realise there may be other ways to write statements; however this answer allows for the style of statement in the original question while solving the problem of PhpStorm flagging an error for the particular statement.

Body:
I am using PHPStorm and having some interesting errors/warnings showing up. Not sure if I skipped configuring something.
Here is a query for example,

$query  = "INSERT INTO tblperson (";
$query .= "  personName, personLname, personNumber, personPhone, personAttr";
$query .= ") VALUES (";
$query .= "  '{$personName}', '{$personLname}', {$personNumber}, {$personPhone}, '{$personAttr}'";
$query .= ")";

And I get this warning: " expected, unexpected end of file" on first line of the code. Is there anything I am missing on this insert statement that PHPStorm warns me on?

When I run the code I can insert a record without any problems but still wonder maybe there might be an improvement that I am missing.

Body:
Adding this here because the other answer only disables the inspection everywhere and not just for a particular statement.

This issue occurs because the editor loses context when the SQL statement is split over multiple strings.

There is no proper way to actually ignore this error for just a single statement in the editor.

This issue can be reproduced by having your SQL inspections turned on and having a dialect set for the file project.

One potential workaround is to have the beginning of your statement split.

For example, change the below statement from

$start = "INSERT IGNORE INTO table1(";
$mid = ") VALUES (";
$end = ")";

to

$start = "INSERT " . "IGNORE INTO table1(";
$mid = ") VALUES (";
$end = ")";

This'll trick PhpStorm into thinking that your statement is just another string instead of treating it as SQL and performing an inspection on it.

I realise there may be other ways to write statements; however this answer allows for the style of statement in the original question while solving the problem of PhpStorm flagging an error for the particular statement.


问:
gulp-imagemin task run gives error
I am trying to compress my images for the production server but getting an error in running the gulp-imagemin task.

This is my gulp task:

```<code>gulp.task('images', function(){
    gulp.src('builds/development/images/**/*.*')
    .pipe(gulpif(env === 'production', imageMin({
        progressive:true,
        svgoPlugins:[{removeViewBox:false}],
        use:[pngCrush()]
    })))
    .pipe(gulpif(env === 'production', gulp.dest('builds/production/images')))
    .pipe(connect.reload());
});
</code>```

I am getting the following trace:

```<code>events.js:141
      throw er; // Unhandled 'error' event
      ^
Error: spawn UNKNOWN
  at exports._errnoException (util.js:870:11)
  at ChildProcess.spawn (internal/child_process.js:298:11)
  at Object.exports.spawn (child_process.js:362:9)
  at ret.catch.module.exports.promise (C:\Users\user\desktop\workflows\node_modules\gulp-imagemin\node_modules\imagemin-jpegtran\node_modules\exec-buffer\node_modules\execa\index.js:139:26)
  at C:\Users\user\desktop\workflows\node_modules\gulp-imagemin\node_modules\imagemin-jpegtran\node_modules\exec-buffer\index.js:35:15
</code>```

Can someone please have a look and try to provide some solution.

Thanks in advance.

答:
I had the same problem on a production server and I've tried:

Running imagemin without parameters;

Checking all possible permission issues;

Changing node version to latest;

The solution was to delete the node_modules folder and run npm install again.
Strangely enough, it worked as a charm!

Title: gulp-imagemin task run gives error

Body:
I am trying to compress my images for the production server but getting an error in running the gulp-imagemin task.

This is my gulp task:

gulp.task('images', function(){
    gulp.src('builds/development/images/**/*.*')
    .pipe(gulpif(env === 'production', imageMin({
        progressive:true,
        svgoPlugins:[{removeViewBox:false}],
        use:[pngCrush()]
    })))
    .pipe(gulpif(env === 'production', gulp.dest('builds/production/images')))
    .pipe(connect.reload());
});

I am getting the following trace:

events.js:141
      throw er; // Unhandled 'error' event
      ^
Error: spawn UNKNOWN
  at exports._errnoException (util.js:870:11)
  at ChildProcess.spawn (internal/child_process.js:298:11)
  at Object.exports.spawn (child_process.js:362:9)
  at ret.catch.module.exports.promise (C:\Users\user\desktop\workflows\node_modules\gulp-imagemin\node_modules\imagemin-jpegtran\node_modules\exec-buffer\node_modules\execa\index.js:139:26)
  at C:\Users\user\desktop\workflows\node_modules\gulp-imagemin\node_modules\imagemin-jpegtran\node_modules\exec-buffer\index.js:35:15

Can someone please have a look and try to provide some solution.

Thanks in advance.


问:
Tensorflow Sequence to sequence model using the seq2seq API ( ver 1.1 and above)
I'm using TensorFlow v:1.1, and I would like to implement a sequence to sequence model using tf.contrib.seq2seq api.
However I have hard time understanding how to use all the functions (BasicDecoder, Dynamic_decode, Helper, Training Helper ...) provided to build my model.

Here is my setup: I would like to "translate" a sequence of feature vector: (batch_size, encoder_max_seq_len, feature_dim) into a sequence of a different length (batch_size, decoder_max_len, 1).

I already have the encoder that is an RNN with LSTM cell, and I get its final state that I would like to feed to the decoder as initial input.
I already have the cell for my decoder, MultiRNNCell LSM.
Could you help me building the last part using the functions of tf.contrib.seq2seq2 and dynamic_decode (an example code or explanations would be much appreciated) ?

Here is my code:

```<code>import tensorflow as tf
from tensorflow.contrib import seq2seq
from tensorflow.contrib import rnn
import math

from data import gen_sum_2b2

class Seq2SeqModel:
def __init__(self,
             in_size,
             out_size,
             embed_size,
             n_symbols,
             cell_type,
             n_units,
             n_layers):
    self.in_size = in_size
    self.out_size = out_size
    self.embed_size = embed_size
    self.n_symbols = n_symbols
    self.cell_type = cell_type
    self.n_units = n_units
    self.n_layers = n_layers

    self.build_graph()

def build_graph(self):
    self.init_placeholders()
    self.init_cells()
    self.encoder()
    self.decoder_train()
    self.loss()
    self.training()

def init_placeholders(self):
    with tf.name_scope('Placeholders'):
        self.encoder_inputs = tf.placeholder(shape=(None, None, self.in_size),
                                             dtype=tf.float32, name='encoder_inputs')
        self.decoder_targets = tf.placeholder(shape=(None, None),
                                              dtype=tf.int32, name='decoder_targets')
        self.seqs_len = tf.placeholder(dtype=tf.int32)
        self.batch_size = tf.placeholder(tf.int32, name='dynamic_batch_size')
        self.max_len = tf.placeholder(tf.int32, name='dynamic_seq_len')
        decoder_inputs = tf.reshape(self.decoder_targets, shape=(self.batch_size,
                                    self.max_len, self.out_size))
        self.decoder_inputs = tf.cast(decoder_inputs, tf.float32)
        self.eos_step = tf.ones([self.batch_size, 1], dtype=tf.float32, name='EOS')
        self.pad_step = tf.zeros([self.batch_size, 1], dtype=tf.float32, name='PAD')

def RNNCell(self):
    c = self.cell_type(self.n_units, reuse=None)
    c = rnn.MultiRNNCell([self.cell_type(self.n_units) for i in range(self.n_layers)])
    return c

def init_cells(self):
    with tf.variable_scope('RNN_enc_cell'):
        self.encoder_cell = self.RNNCell()
    with tf.variable_scope('RNN_dec_cell'):
        self.decoder_cell = rnn.OutputProjectionWrapper(self.RNNCell(), self.n_symbols)

def encoder(self):
    with tf.variable_scope('Encoder'):
        self.init_state = self.encoder_cell.zero_state(self.batch_size, tf.float32)
        _, self.encoder_final_state = tf.nn.dynamic_rnn(self.encoder_cell, self.encoder_inputs,
                                                        initial_state=self.init_state)
</code>```

答:
Decoding layer:

The decoding consists of two parts because of their differences during training and inference:

The decoder input at a particular time-step always comes from the output
  of the previous time-step.  But during training, the output is fixed
  to the actual target (the actual target is fed back as input)  and this has shown to improve performance.

Both these are handled using methods from tf.contrib.seq2seq.

The main function for the decoder is: seq2seq.dynamic decoder() which performs dynamic decoding:

tf.contrib.seq2seq.dynamic_decode(decoder,maximum_iterations)

This takes a Decoder instance and maximum_iterations=maximum seq length as inputs.

1.1 The Decoder instance is  from:

seq2seq.BasicDecoder(cell, helper, initial_state,output_layer)

The inputs are:  cell (an RNNCell instance),  helper (helper instance), initial_state (initial state of the decoder which should be the output state of the encoder) and output_layer (an optional dense layer as outputs to makes predictions)

1.2  An RNNCell instance can be a rnn.MultiRNNCell().

1.3  The helper instance is the one that differs in training and inference. During training, we want the inputs to be fed to the decoder, while during inference, we want the output of the decoder in time-step (t) to be passed as the input to the decoder in time step (t+1).

For training: we use the helper function:
                seq2seq.TrainingHelper(inputs, sequence_length), which just read inputs.

For inference: we call the helper function:
                seq2seq.GreedyEmbeddingHelper() or seqseq.SampleEmbeddingHelper(), which differs whether it to use argmax() or sampling(from a distribution) of the outputs and passes the result through an embedding layer to get the next input.

Putting together: the Seq2Seq model

Get the encoder state from the encoder layer and passed it as a initial_state to the decoder.

Get the outputs of decoder train and decoder inference using seq2seq.dynamic_decoder(). When your calling both the methods make sure the weights are shared. (Use variable_scope to reuse the weights)

Then train the network using the loss function seq2seq.sequence_loss.

An example code is given here and here.

Body:
I'm using TensorFlow v:1.1, and I would like to implement a sequence to sequence model using tf.contrib.seq2seq api.
However I have hard time understanding how to use all the functions (BasicDecoder, Dynamic_decode, Helper, Training Helper ...) provided to build my model.

Here is my setup: I would like to "translate" a sequence of feature vector: (batch_size, encoder_max_seq_len, feature_dim) into a sequence of a different length (batch_size, decoder_max_len, 1).

I already have the encoder that is an RNN with LSTM cell, and I get its final state that I would like to feed to the decoder as initial input.
I already have the cell for my decoder, MultiRNNCell LSM.
Could you help me building the last part using the functions of tf.contrib.seq2seq2 and dynamic_decode (an example code or explanations would be much appreciated) ?

Here is my code:

import tensorflow as tf
from tensorflow.contrib import seq2seq
from tensorflow.contrib import rnn
import math

from data import gen_sum_2b2

class Seq2SeqModel:
def __init__(self,
             in_size,
             out_size,
             embed_size,
             n_symbols,
             cell_type,
             n_units,
             n_layers):
    self.in_size = in_size
    self.out_size = out_size
    self.embed_size = embed_size
    self.n_symbols = n_symbols
    self.cell_type = cell_type
    self.n_units = n_units
    self.n_layers = n_layers

    self.build_graph()

def build_graph(self):
    self.init_placeholders()
    self.init_cells()
    self.encoder()
    self.decoder_train()
    self.loss()
    self.training()

def init_placeholders(self):
    with tf.name_scope('Placeholders'):
        self.encoder_inputs = tf.placeholder(shape=(None, None, self.in_size),
                                             dtype=tf.float32, name='encoder_inputs')
        self.decoder_targets = tf.placeholder(shape=(None, None),
                                              dtype=tf.int32, name='decoder_targets')
        self.seqs_len = tf.placeholder(dtype=tf.int32)
        self.batch_size = tf.placeholder(tf.int32, name='dynamic_batch_size')
        self.max_len = tf.placeholder(tf.int32, name='dynamic_seq_len')
        decoder_inputs = tf.reshape(self.decoder_targets, shape=(self.batch_size,
                                    self.max_len, self.out_size))
        self.decoder_inputs = tf.cast(decoder_inputs, tf.float32)
        self.eos_step = tf.ones([self.batch_size, 1], dtype=tf.float32, name='EOS')
        self.pad_step = tf.zeros([self.batch_size, 1], dtype=tf.float32, name='PAD')

def RNNCell(self):
    c = self.cell_type(self.n_units, reuse=None)
    c = rnn.MultiRNNCell([self.cell_type(self.n_units) for i in range(self.n_layers)])
    return c

def init_cells(self):
    with tf.variable_scope('RNN_enc_cell'):
        self.encoder_cell = self.RNNCell()
    with tf.variable_scope('RNN_dec_cell'):
        self.decoder_cell = rnn.OutputProjectionWrapper(self.RNNCell(), self.n_symbols)

def encoder(self):
    with tf.variable_scope('Encoder'):
        self.init_state = self.encoder_cell.zero_state(self.batch_size, tf.float32)
        _, self.encoder_final_state = tf.nn.dynamic_rnn(self.encoder_cell, self.encoder_inputs,
                                                        initial_state=self.init_state)


答:
ndn explained already in his answer why the case statement in your example is not working.

You can switch to an if/elsif block or a slightly longer when current_user.admin? syntax. Or you can define some methods for returning lambdas:

```<code>def is_admin?
  ->(user) { user.is_admin? }
end

def has_role?(role)
  ->(user) { user.has_role?(role) }
end
</code>```

With these methods you can write:

```<code>query_limit = case current_user
              when nil then 5
              when is_admin? then 200
              when has_role?('registered') then 20
              else 5
              end
</code>```

Title: Why is my ruby case statement not working?

Body:
What's wrong with that?
Yes, I could make an if else statement, but I wanna do that with case statements.

In my Controller

query_limit = case current_user
                when nil
                  return 5
                when is_admin?
                  return 200
                when has_role?('registered')
                  return 20
                else
                  return 5
              end

NoMethodError (undefined method `is_admin?' for #<V1::MyController:123123123>):

puts query_limit # is always ELSE when I do this:

 query_limit = case current_user
                    when nil
                      return 5
                    when current_user.is_admin?
                      return 200
                    when current_user.has_role?('registered')
                      return 20
                    else
                      return 5
                  end

Model User

class User
  def is_admin?
    self.has_role?('administrator')
  end

  def has_role?(the_role)
    self.roles.any? {|role| role.slug == the_role}
  end
end

Body:
ndn explained already in his answer why the case statement in your example is not working.

You can switch to an if/elsif block or a slightly longer when current_user.admin? syntax. Or you can define some methods for returning lambdas:

def is_admin?
  ->(user) { user.is_admin? }
end

def has_role?(role)
  ->(user) { user.has_role?(role) }
end

With these methods you can write:

query_limit = case current_user
              when nil then 5
              when is_admin? then 200
              when has_role?('registered') then 20
              else 5
              end

ContentLicense: CC BY-SA 4.0


问:
How to type Redux actions and Redux reducers in TypeScript?
What is the best way to cast the action parameter in a redux reducer with typescript? There will be multiple action interfaces that can occur that all extend a base interface with a property type. The extended action interfaces can have more properties that are all different between the action interfaces. Here is an example below:

```<code>interface IAction {
    type: string
}

interface IActionA extends IAction {
    a: string
}

interface IActionB extends IAction {
    b: string
}

const reducer = (action: IAction) {
    switch (action.type) {
        case 'a':
            return console.info('action a: ', action.a) // property 'a' does not exists on type IAction

        case 'b':
            return console.info('action b: ', action.b) // property 'b' does not exists on type IAction
    }
}
</code>```

The problem is that action needs to be cast as a type that has access to both IActionA and IActionB so the reducer can use both action.a and action.a without throwing an error.

I have several ideas how to work around this issue:

Cast action to any.

Use optional interface members.

example:

```<code>interface IAction {
    type: string
    a?: string
    b?: string
}
</code>```

Use different reducers for every action type.

What is the best way to organize Action/Reducers in typescript? Thank you in advance!

答:
To get implicit typesafety without having to write interfaces for every action, you can use this approach (inspired by the returntypeof function from here: https://github.com/piotrwitek/react-redux-typescript#returntypeof-polyfill)</p>

```<code>import { values } from 'underscore'

/**
 * action creator (declaring the return type is optional,
 * but you can make the props readonly)
 */
export const createAction = <T extends string, P extends {}>(type: T, payload: P) => {
  return {
    type,
    payload
  } as {
    readonly type: T,
    readonly payload: P
  }
}

/**
 * Action types
 */
const ACTION_A = "ACTION_A"
const ACTION_B = "ACTION_B"

/**
 * actions
 */
const actions = {
  actionA: (count: number) => createAction(ACTION_A, { count }),
  actionB: (name: string) => createAction(ACTION_B, { name })
}

/**
 * create action type which you can use with a typeguard in the reducer
 * the actionlist variable is only needed for generation of TAction
 */
const actionList = values(actions).map(returnTypeOf)
type TAction = typeof actionList[number]

/**
 * Reducer
 */
export const reducer = (state: any, action: TAction) => {
  if ( action.type === ACTION_A ) {
    console.log(action.payload.count)
  }
  if ( action.type === ACTION_B ) {
    console.log(action.payload.name)
    console.log(action.payload.count) // compile error, because count does not exist on ACTION_B
  }
  console.log(action.payload.name) // compile error because name does not exist on every action
}
</code>```

Body:
What is the best way to cast the action parameter in a redux reducer with typescript? There will be multiple action interfaces that can occur that all extend a base interface with a property type. The extended action interfaces can have more properties that are all different between the action interfaces. Here is an example below:

interface IAction {
    type: string
}

interface IActionA extends IAction {
    a: string
}

interface IActionB extends IAction {
    b: string
}

const reducer = (action: IAction) {
    switch (action.type) {
        case 'a':
            return console.info('action a: ', action.a) // property 'a' does not exists on type IAction

        case 'b':
            return console.info('action b: ', action.b) // property 'b' does not exists on type IAction
    }
}

The problem is that action needs to be cast as a type that has access to both IActionA and IActionB so the reducer can use both action.a and action.a without throwing an error.

I have several ideas how to work around this issue:

Cast action to any.

Use optional interface members.

example:

interface IAction {
    type: string
    a?: string
    b?: string
}

Use different reducers for every action type.

What is the best way to organize Action/Reducers in typescript? Thank you in advance!

Body:
To get implicit typesafety without having to write interfaces for every action, you can use this approach (inspired by the returntypeof function from here: https://github.com/piotrwitek/react-redux-typescript#returntypeof-polyfill)

import { values } from 'underscore'

/**
 * action creator (declaring the return type is optional,
 * but you can make the props readonly)
 */
export const createAction = <T extends string, P extends {}>(type: T, payload: P) => {
  return {
    type,
    payload
  } as {
    readonly type: T,
    readonly payload: P
  }
}

/**
 * Action types
 */
const ACTION_A = "ACTION_A"
const ACTION_B = "ACTION_B"

/**
 * actions
 */
const actions = {
  actionA: (count: number) => createAction(ACTION_A, { count }),
  actionB: (name: string) => createAction(ACTION_B, { name })
}

/**
 * create action type which you can use with a typeguard in the reducer
 * the actionlist variable is only needed for generation of TAction
 */
const actionList = values(actions).map(returnTypeOf)
type TAction = typeof actionList[number]

/**
 * Reducer
 */
export const reducer = (state: any, action: TAction) => {
  if ( action.type === ACTION_A ) {
    console.log(action.payload.count)
  }
  if ( action.type === ACTION_B ) {
    console.log(action.payload.name)
    console.log(action.payload.count) // compile error, because count does not exist on ACTION_B
  }
  console.log(action.payload.name) // compile error because name does not exist on every action
}


问:
Convertion of tabular data to JSON in Redshift
I am unable to figure out how to convert tabular data to JSON format and store it in another table in Redshift. For example, I have a "DEMO" table with four columns: pid,stid,item_id,trans_id.

For each combination of pid,stid,item_id there exist many trans_ids.

```<code>pid  stid  item_id  trans_id :

1 , AB  , P1 , T1
1 , AB  , P1 , T2
1 , AB  , P1 , T3
1 , AB  , P1 , T4
2 , ABC , P2 , T5
2 , ABC , P2 , T6
2 , ABC , P2 , T7
2 , ABC , P2 , T8
</code>```

I want to store this data in another table called "SAMPLE" as:

```<code>pid  stid  item_id      trans_id

1 , AB  , P1 , {"key1":T1, "key2":"T2" "key2":"T3" "key2":"T4"}
2 , ABC , P2 , {"key1":T5, "key2":"T6" "key2":"T7" "key2":"T8"}
</code>```

I am unable to figure out how to load the data from "DEMO" to "SAMPLE" in JSON format only for column "trans_id" using a SQL query in Redshift. I don't want to use any intermediate files.

答:
There is LISTAGG aggregate function that allows you to concatenate text values within groups. It allows the effective construction of JSON objects:

```<code>SELECT
 pid
,stid
,item_id
,'{'||listagg(
    '"key'||row_number::varchar||'":'||trans_id::varchar
    ,',') within group (order by row_number)
 ||'}'
FROM (
    SELECT *, row_number() over (partition by pid,stid,item_id order by trans_id)
    FROM "DEMO"
)
GROUP BY 1,2,3;
</code>```

As a side note, in this particular case an array of transaction IDs might work better, you'll be able to request the element of a specific order easily without using keyN key:

```<code>WITH tran_arrays as (
    SELECT
     pid
    ,stid
    ,item_id
    ,listagg(trans_id::varchar,',') within group (order by trans_id) as tran_array
    FROM "DEMO"
    GROUP BY 1,2,3
)
SELECT *
,split_part(tran_array,',',1) as first_element
FROM tran_arrays;
</code>```

Body:
I am unable to figure out how to convert tabular data to JSON format and store it in another table in Redshift. For example, I have a "DEMO" table with four columns: pid,stid,item_id,trans_id.

For each combination of pid,stid,item_id there exist many trans_ids.

pid  stid  item_id  trans_id :

1 , AB  , P1 , T1
1 , AB  , P1 , T2
1 , AB  , P1 , T3
1 , AB  , P1 , T4
2 , ABC , P2 , T5
2 , ABC , P2 , T6
2 , ABC , P2 , T7
2 , ABC , P2 , T8

I want to store this data in another table called "SAMPLE" as:

pid  stid  item_id      trans_id

1 , AB  , P1 , {"key1":T1, "key2":"T2" "key2":"T3" "key2":"T4"}
2 , ABC , P2 , {"key1":T5, "key2":"T6" "key2":"T7" "key2":"T8"}

I am unable to figure out how to load the data from "DEMO" to "SAMPLE" in JSON format only for column "trans_id" using a SQL query in Redshift. I don't want to use any intermediate files.

Body:
There is LISTAGG aggregate function that allows you to concatenate text values within groups. It allows the effective construction of JSON objects:

SELECT
 pid
,stid
,item_id
,'{'||listagg(
    '"key'||row_number::varchar||'":'||trans_id::varchar
    ,',') within group (order by row_number)
 ||'}'
FROM (
    SELECT *, row_number() over (partition by pid,stid,item_id order by trans_id)
    FROM "DEMO"
)
GROUP BY 1,2,3;

As a side note, in this particular case an array of transaction IDs might work better, you'll be able to request the element of a specific order easily without using keyN key:

WITH tran_arrays as (
    SELECT
     pid
    ,stid
    ,item_id
    ,listagg(trans_id::varchar,',') within group (order by trans_id) as tran_array
    FROM "DEMO"
    GROUP BY 1,2,3
)
SELECT *
,split_part(tran_array,',',1) as first_element
FROM tran_arrays;


问:
Why my Xcode "Command" + "Left Click" not jump to the target function?
I have updated my Xcode to 8.2.1.
I am using "Command" + "Left mouse Click" to jump to the target function, although it not working randomly, What's the root cause?</p>

答:
I had the same problem today and I follow the answer here to resolve it:

File > Workspace Settings (or Project Setting)

Click over the little grey arrow above Advanced... Button (Derived Data)

Select my project folder and delete it.

After deleted the folder (Derived Data), cmd+left-click starts to jump to the target function again.


问:
How do I check for CSS styling with JavaScript?
Why am I unable to test for CSS styling like this:

```<code>if (document.getElementById("myText").style.outline == "10px solid black")
{
  // Do something
}
</code>```

or

```<code>if (document.getElementById("myText").style.match("outline: 10px solid
black"))
{
  // Do something;
}
</code>```

when I have:

```<code>#myText
{
  outline: 10px solid black;
}
</code>```

答:
I assume getComputedStyle will help in finding the applied style

var elem1 = document.getElementById("myText"),
  style = window.getComputedStyle(elem1, null);
console.log(style.outline)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myText {
  outline: 10px solid black;
}</code>```

Text
```

Body:
Why am I unable to test for CSS styling like this:

if (document.getElementById("myText").style.outline == "10px solid black")
{
  // Do something
}

or

if (document.getElementById("myText").style.match("outline: 10px solid
black"))
{
  // Do something;
}

when I have:

#myText
{
  outline: 10px solid black;
}

Body:
I assume getComputedStyle will help in finding the applied style

var elem1 = document.getElementById("myText"),
  style = window.getComputedStyle(elem1, null);
console.log(style.outline)

#myText {
  outline: 10px solid black;
}

<div id="myText">Text</div>


问:
swift 3 add row to TableViewController using textField from ViewController
I'm making a todolist app in swift. Here is what it looks like :

So far to create a todo I used an alertController but I changed it and now using a new viewcontroller opening when click on the "+" to add. When the ViewController opens itself, I fill the title and then click a button. On the click button I'd like it to add a new row in the tableViewController with the title I put in the textField of the viewController.
I'm having trouble to pass the value of the textField in the new row created in the tableViewController.
Anyone can give some help ?

[EDIT]
Here is my addTodoController :

```<code>var updateTableViewClosure: ((String) -> Void)?

    @IBAction func AddButton(_ sender: Any) {
        var todoValue = titleField.text
        updateTableViewClosure?(todoValue!)
    }

    @IBOutlet weak var titleField: UITextField!
</code>```

Here is my tableviewcontroller :

```<code>if segue.identifier == "CreateAdd" {

    let addItemViewController = segue.destination as! CreateAdd
    addItemViewController.updateTableViewClosure = {
        newItem in myItems(title: todoValue, content:"hello", ontent: "Ceci est le contenu" , startDate: "16/08/1997", author: "Clem")
    }
}
</code>```

I get an error:

" Use of unresolved "todoValue"

答:
You need a way to pass data back to the view controller containing the table view. This can be achieved in many ways, for example using the delegate pattern.

One simpler way to achieve that is using closures, like this:

In the view controller containing the table view:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "identifier" {

        let addItemViewController = segue.destination as! AddItemViewController
        addItemViewController.updateTableViewClosure = {
            newItem in

            // Add the new item to your data source and reload your table view.
        }
    }
}
</code>```

In AddItemViewController add a new variable called updateTableViewClosure which will be your closure:

```<code>var updateTableViewClosure: (String -> Void)?
</code>```

and call it wherever you want like this:

```<code>updateTableViewClosure?("The new item")
</code>```

Hope this helps!

Body:
I'm making a todolist app in swift. Here is what it looks like :

So far to create a todo I used an alertController but I changed it and now using a new viewcontroller opening when click on the "+" to add. When the ViewController opens itself, I fill the title and then click a button. On the click button I'd like it to add a new row in the tableViewController with the title I put in the textField of the viewController.
I'm having trouble to pass the value of the textField in the new row created in the tableViewController.
Anyone can give some help ?

[EDIT]
Here is my addTodoController :

var updateTableViewClosure: ((String) -> Void)?

    @IBAction func AddButton(_ sender: Any) {
        var todoValue = titleField.text
        updateTableViewClosure?(todoValue!)
    }

    @IBOutlet weak var titleField: UITextField!

Here is my tableviewcontroller :

if segue.identifier == "CreateAdd" {

    let addItemViewController = segue.destination as! CreateAdd
    addItemViewController.updateTableViewClosure = {
        newItem in myItems(title: todoValue, content:"hello", ontent: "Ceci est le contenu" , startDate: "16/08/1997", author: "Clem")
    }
}

I get an error:

" Use of unresolved "todoValue"

Body:
You need a way to pass data back to the view controller containing the table view. This can be achieved in many ways, for example using the delegate pattern.

One simpler way to achieve that is using closures, like this:

In the view controller containing the table view:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "identifier" {

        let addItemViewController = segue.destination as! AddItemViewController
        addItemViewController.updateTableViewClosure = {
            newItem in

            // Add the new item to your data source and reload your table view.
        }
    }
}

In AddItemViewController add a new variable called updateTableViewClosure which will be your closure:

var updateTableViewClosure: (String -> Void)?

and call it wherever you want like this:

updateTableViewClosure?("The new item")

Hope this helps!


问:
Appending %22 to post varialbles
I have set of input box like this,

```<code><input type="number" class="form-control" id="gmat1" name="gmat1" placeholder="Eg: 85" >
<input type="number" class="form-control" id="gmpmem1" name=gmpmem1" placeholder="Eg: 5" >
</code>```

then I submit those data to backend using ajax like this,

```<code>var data = new FormData($('#mr_form')[0]);
  $.ajax({
   url: "xxxxxxx",
   dataType: 'JSON',
   data: data,
   processData: false,
   contentType: false,
   cache: false,
   type: 'POST',
   success: function (data) {}
});
</code>```

Then I ctach tose data in the backend like,

```<code> $data = $this->input->post();
</code>```

My problem is when i'm getting the data

```<code>[gmat1] => 45645
[gmpmem1%22] => 454
</code>```

I'm getting

[gmpmem1%22] => 454

%22

%22 has appended to the variable name. I want to remove that part from the variable name. what should i do?

答:
change your input field to

```<code><input type="number" class="form-control" id="gmpmem1" name="gmpmem1" placeholder="Eg: 5" >
</code>```

Use proper quotation

Title: Appending %22 to post varialbles

Body:
I have set of input box like this,

<input type="number" class="form-control" id="gmat1" name="gmat1" placeholder="Eg: 85" >
<input type="number" class="form-control" id="gmpmem1" name=gmpmem1" placeholder="Eg: 5" >

then I submit those data to backend using ajax like this,

var data = new FormData($('#mr_form')[0]);
  $.ajax({
   url: "xxxxxxx",
   dataType: 'JSON',
   data: data,
   processData: false,
   contentType: false,
   cache: false,
   type: 'POST',
   success: function (data) {}
});

Then I ctach tose data in the backend like,

 $data = $this->input->post();

My problem is when i'm getting the data

[gmat1] => 45645
[gmpmem1%22] => 454

I'm getting

[gmpmem1%22] => 454

%22

%22 has appended to the variable name. I want to remove that part from the variable name. what should i do?

Body:
change your input field to

<input type="number" class="form-control" id="gmpmem1" name="gmpmem1" placeholder="Eg: 5" >

Use proper quotation