问:
Destroying SecretKey throws DestroyFailedException?
I am writing a function to generate secret key (bytes) based on a password using SecretKeyFactory. I want to destroy SecretKey instance when it is not needed anymore But it throws an exception.

```<code>try {
    byte[] salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

    PBEKeySpec keySpec = new PBEKeySpec("password".toCharArray(), salt, 1000, 256);

    SecretKey secretkey = factory.generateSecret(keySpec);
    byte[] key = secretkey.getEncoded();

    // Using key

    // Destroy key
    Arrays.fill(key, (byte)0);

    // Destroy secretKey
    secretkey.destroy();  // --> Throw DestroyFailedException

} catch (Exception e) {
    e.printStackTrace();
}
</code>```

I am using Oracle JDK1.8.0_66 on Mac.

I take a look at SecretKey source code and I found this default implementation (SecretKey implements Destroyable interface)

```<code>public default void destroy() throws DestroyFailedException {
    throw new DestroyFailedException();
}
</code>```

It means: the implementation of SecretKey does not override the destroy method to destroy internal password chars and internal key bytes.

Is this a bug in JDK 8?

答:
This looks pretty bad to me. I am also looking for ways to destroy a SecretKey. You can use reflection. I know it is super hacky, but it allows us to get the underlying private key array:</p>

```<code>public class DestroyableSecretKeySpec extends SecretKeySpec {
    public DestroyableSecretKeySpec( byte[] key, int offset, int len, String algorithm ) {
        super( key, offset, len, algorithm );
    }

    @Override
    public void destroy() {
        try {
            // Use hacky reflection to clear the underlying private key from memory.
            // This is so ugly :/
            Field f = SecretKeySpec.class.getDeclaredField( "key" );
            f.setAccessible(true);
            byte[] key = (byte[]) f.get( this );
            Arrays.fill( key, (byte)0xCC );
        } catch( NoSuchFieldException | IllegalAccessException e ) {
            throw new EncryptionException( "Can't use reflection to clear a secret key.", e );
        }
    }
}
</code>```

Body:
I am writing a function to generate secret key (bytes) based on a password using SecretKeyFactory. I want to destroy SecretKey instance when it is not needed anymore But it throws an exception.

try {
    byte[] salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

    PBEKeySpec keySpec = new PBEKeySpec("password".toCharArray(), salt, 1000, 256);

    SecretKey secretkey = factory.generateSecret(keySpec);
    byte[] key = secretkey.getEncoded();

    // Using key

    // Destroy key
    Arrays.fill(key, (byte)0);

    // Destroy secretKey
    secretkey.destroy();  // --> Throw DestroyFailedException

} catch (Exception e) {
    e.printStackTrace();
}

I am using Oracle JDK1.8.0_66 on Mac.

I take a look at SecretKey source code and I found this default implementation (SecretKey implements Destroyable interface)

public default void destroy() throws DestroyFailedException {
    throw new DestroyFailedException();
}

It means: the implementation of SecretKey does not override the destroy method to destroy internal password chars and internal key bytes.

Is this a bug in JDK 8?

Body:
This looks pretty bad to me. I am also looking for ways to destroy a SecretKey. You can use reflection. I know it is super hacky, but it allows us to get the underlying private key array:

public class DestroyableSecretKeySpec extends SecretKeySpec {
    public DestroyableSecretKeySpec( byte[] key, int offset, int len, String algorithm ) {
        super( key, offset, len, algorithm );
    }

    @Override
    public void destroy() {
        try {
            // Use hacky reflection to clear the underlying private key from memory.
            // This is so ugly :/
            Field f = SecretKeySpec.class.getDeclaredField( "key" );
            f.setAccessible(true);
            byte[] key = (byte[]) f.get( this );
            Arrays.fill( key, (byte)0xCC );
        } catch( NoSuchFieldException | IllegalAccessException e ) {
            throw new EncryptionException( "Can't use reflection to clear a secret key.", e );
        }
    }
}


来源: stackexchange

问:
Return first word in sentence?
Heres the question I have to answer for school

For the purposes of this question, we will define a word as ending a sentence if that word is immediately followed by a period. For example, in the text “This is a sentence. The last sentence had four words.”, the ending words are ‘sentence’ and ‘words’. In a similar fashion, we will define the starting word of a sentence as any word that is preceded by the end of a sentence. The starting words from the previous example text would be “The”. You do not need to consider the first word of the text as a starting word. Write a program that has:

An endwords function that takes a single string argument. This functioin must return a list of all sentence ending words that appear in the given string. There should be no duplicate entries in the returned list and the periods should not be included in the ending words.

The code I have so far is:

```<code>def startwords(astring):
    mylist = astring.split()
    if mylist.endswith('.') == True:
        return my list
</code>```

but I don't know if I'm using the right approach. I need some help

答:
```<code>def endwords(astring):
    mylist = astring.split('.')
    temp_words = [x.rpartition(" ")[-1] for x in mylist if len(x) > 1]
    return list(set(temp_words))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Return first word in sentence?

Body:
Heres the question I have to answer for school

For the purposes of this question, we will define a word as ending a sentence if that word is immediately followed by a period. For example, in the text “This is a sentence. The last sentence had four words.”, the ending words are ‘sentence’ and ‘words’. In a similar fashion, we will define the starting word of a sentence as any word that is preceded by the end of a sentence. The starting words from the previous example text would be “The”. You do not need to consider the first word of the text as a starting word. Write a program that has:

An endwords function that takes a single string argument. This functioin must return a list of all sentence ending words that appear in the given string. There should be no duplicate entries in the returned list and the periods should not be included in the ending words.

The code I have so far is:

def startwords(astring):
    mylist = astring.split()
    if mylist.endswith('.') == True:
        return my list

but I don't know if I'm using the right approach. I need some help


问:
Dynamically create multiple object instances of same class in c#
I am building a device controller in C# that controls the flow rate of pumps. There is Form1 and a Pump-Class, holding all properties and methods of the pump that are accessible through the Form.  So far, everything works fine. However, there might be the case where there is more than one pump. Of course, I could run individual instances of the executable, but you know..

How can I create multiple instances of the pump-class according to my current demand. Maybe an extra Form upfront with an Add-Button, where it is possible to create as much pumps as needed?

Sure, this is comes down to a very basic question, but I am no professional programmer.. Any comments are highly appreciated.

Thanks in advance.

mulm

```<code>namespace PumpController
{

    public partial class Form1 : Form
    {

        static Pump pump;

        public Form1()
        {

            InitializeComponent();

            cb_availablePorts.DropDownStyle = ComboBoxStyle.DropDownList;
            cb_baudRates.DropDownStyle = ComboBoxStyle.DropDownList;

            string[] availablePorts = SerialPort.GetPortNames();
            foreach (string item in availablePorts)
                {
                    cb_availablePorts.Items.Add(item);
                }

            string[] commonBaudRates = new string[] { "4800", "9600", "19200", "38400", "57600", "115200" };
            foreach (string item in commonBaudRates)
            {
                cb_baudRates.Items.Add(item);
            }
        }

        private void bt_valueUp_Click(object sender, EventArgs e)
        {
            if (!(pump == null))
            {
                pump.increaseValue();
            }
        }

        private void bt_valueDown_Click(object sender, EventArgs e)
        {
            if (!(pump == null))
            {
                pump.decreaseValue();
            }
        }

        private void Form_Closing(object sender, EventArgs e)
        {
            Hide();
            if (!(pump == null))
            {
                pump.Close();
            }
        }

        private void bt_connect_Click(object sender, EventArgs e)
        {
            if (!(cb_availablePorts.SelectedItem == null) && !(cb_baudRates.SelectedItem == null))
            {
                Pump pump = new Pump(Convert.ToString(cb_availablePorts.SelectedItem), Convert.ToInt32(cb_baudRates.SelectedItem));
            }
        }
    }
}
</code>```

答:
The comments lead to part of the answer and are right as far as they go.  However, one important thing has perhaps been overlooked -- the part about finding an(other) COM port.

Each time you instantiate a new Pump object, and add it to the List<Pump> collection, these objects will contend for the same COM port unless you allocate another port.

There is a well-accepted answer for this at enumerating COM ports.  Hate to provide a link as the heart of my answer, but if you have a four-object list of Pump objects contending for a single serial port, you could have troubles.

Body:
I am building a device controller in C# that controls the flow rate of pumps. There is Form1 and a Pump-Class, holding all properties and methods of the pump that are accessible through the Form.  So far, everything works fine. However, there might be the case where there is more than one pump. Of course, I could run individual instances of the executable, but you know..

How can I create multiple instances of the pump-class according to my current demand. Maybe an extra Form upfront with an Add-Button, where it is possible to create as much pumps as needed?

Sure, this is comes down to a very basic question, but I am no professional programmer.. Any comments are highly appreciated.

Thanks in advance.

mulm

namespace PumpController
{

    public partial class Form1 : Form
    {

        static Pump pump;

        public Form1()
        {

            InitializeComponent();

            cb_availablePorts.DropDownStyle = ComboBoxStyle.DropDownList;
            cb_baudRates.DropDownStyle = ComboBoxStyle.DropDownList;

            string[] availablePorts = SerialPort.GetPortNames();
            foreach (string item in availablePorts)
                {
                    cb_availablePorts.Items.Add(item);
                }

            string[] commonBaudRates = new string[] { "4800", "9600", "19200", "38400", "57600", "115200" };
            foreach (string item in commonBaudRates)
            {
                cb_baudRates.Items.Add(item);
            }
        }

        private void bt_valueUp_Click(object sender, EventArgs e)
        {
            if (!(pump == null))
            {
                pump.increaseValue();
            }
        }

        private void bt_valueDown_Click(object sender, EventArgs e)
        {
            if (!(pump == null))
            {
                pump.decreaseValue();
            }
        }

        private void Form_Closing(object sender, EventArgs e)
        {
            Hide();
            if (!(pump == null))
            {
                pump.Close();
            }
        }

        private void bt_connect_Click(object sender, EventArgs e)
        {
            if (!(cb_availablePorts.SelectedItem == null) && !(cb_baudRates.SelectedItem == null))
            {
                Pump pump = new Pump(Convert.ToString(cb_availablePorts.SelectedItem), Convert.ToInt32(cb_baudRates.SelectedItem));
            }
        }
    }
}


问:
How can i handle Stream management duplicate record?

I am implementing XMPPStreamManagement XEP-198 but my last message repeated multiple time

```<code>_xmppStreamManagement = [[XMPPStreamManagement alloc] initWithStorage:[XMPPStreamManagementMemoryStorage new]];
// And then configured however you like.
// This is just an example:
_xmppStreamManagement.autoResume = YES;
_xmppStreamManagement.ackResponseDelay = 0.2;
[_xmppStreamManagement requestAck];
[_xmppStreamManagement automaticallyRequestAcksAfterStanzaCount:3 orTimeout:0.4];
[_xmppStreamManagement automaticallySendAcksAfterStanzaCount:10 orTimeout:5.0];

[_xmppStreamManagement addDelegate:self delegateQueue:dispatch_get_main_queue()];
[_xmppStreamManagement activate:self.xmppStream];
</code>```

After that i enable stream on xmpp Stream Did Authenticate delegate methods

```<code>// Check to see we resumed a previous session
NSArray *stanzaIds = nil;
if ([_xmppStreamManagement didResumeWithAckedStanzaIds:&stanzaIds serverResponse:NULL]){
// Situation A
}else {
// Situation B
//[self goOnline];
[self.xmppStream sendElement:[XMPPPresence presence]]; // send available presence
if ([sender supportsStreamManagement]) {
    [_xmppStreamManagement enableStreamManagementWithResumption:YES maxTimeout:0];
}
}
</code>```

Please suggest me where & how, i resolve duplicate message repetition and also not call XMPPStreamManagement delegate Method's

答:
To avoid message duplication, you should add uniqueness check on your end on message id. As every message packet contains unique id, so you should check that id to avoid duplicate messages.</p>

```<code><message from='userA@yourdomain.io' to='userB@yourdomain.io' id='msg_1'>
    <body>Shall we meet?</body>
</message>
</code>```

Body:
I am implementing XMPPStreamManagement XEP-198 but my last message repeated multiple time

_xmppStreamManagement = [[XMPPStreamManagement alloc] initWithStorage:[XMPPStreamManagementMemoryStorage new]];
// And then configured however you like.
// This is just an example:
_xmppStreamManagement.autoResume = YES;
_xmppStreamManagement.ackResponseDelay = 0.2;
[_xmppStreamManagement requestAck];
[_xmppStreamManagement automaticallyRequestAcksAfterStanzaCount:3 orTimeout:0.4];
[_xmppStreamManagement automaticallySendAcksAfterStanzaCount:10 orTimeout:5.0];

[_xmppStreamManagement addDelegate:self delegateQueue:dispatch_get_main_queue()];
[_xmppStreamManagement activate:self.xmppStream];

After that i enable stream on xmpp Stream Did Authenticate delegate methods

// Check to see we resumed a previous session
NSArray *stanzaIds = nil;
if ([_xmppStreamManagement didResumeWithAckedStanzaIds:&stanzaIds serverResponse:NULL]){
// Situation A
}else {
// Situation B
//[self goOnline];
[self.xmppStream sendElement:[XMPPPresence presence]]; // send available presence
if ([sender supportsStreamManagement]) {
    [_xmppStreamManagement enableStreamManagementWithResumption:YES maxTimeout:0];
}
}

Please suggest me where & how, i resolve duplicate message repetition and also not call XMPPStreamManagement delegate Method's

Body:
To avoid message duplication, you should add uniqueness check on your end on message id. As every message packet contains unique id, so you should check that id to avoid duplicate messages.

<message from='userA@yourdomain.io' to='userB@yourdomain.io' id='msg_1'>
    <body>Shall we meet?</body>
</message>


问:
Computer simulation of the brain
I've been hunting on the net periodically for several months for an answer to this with no joy. Grateful if anyone can shed any light..

I'm interested in work that's been done on simulating the human brain. I could of course mean many things by that. Here's what I do mean, followed by what I don't mean:

I AM interested in simulations of how we think and feel. I'm not talking about down to the level of neurons, but more simulation of the larger modules that are involved. For example one might simulate the 'anger' module as a service that measures the degree one has been disrespected (in some system of representation) and outputs an appropriate measure of anger (again in some system of representation).

I am NOT interested in projects like the Blue Brain etc, where accurate models of neuron clusters are being built. I'm interested in models operating at much higher levels of abstraction, on the level of emotional modules, cognitive reasoning systems etc.

I'm also NOT interested in AI projects that take as their inspiration or paradigm human mechanisms, like Belief-Desire-Intention systems, but which are not actually trying to replicate human behavior. Interesting though these systems are, I'm not interested in making effective systems, but effectively modelling human thought and emotion.

I've been searching far and wide, but all I've found are papers from the 60s like this one:
 Computer Simulation of Human Interaction in Small Groups

It almost appears to me as if psychologists were excited by simulating brains when computers were first available, but now don't do it at all?

Can anyone point me in the direction of more recent research/efforts, if there have been any?

答:
There are a lot of people who've given it some thought, but one of the problems is that as AI research as continued, it seems increasingly that AI leads us to think certain things are actually relatively easy that seemed hard, while the apparently east stuff is what is hard.

Consider, for example, what an expert does in some field of discourse.  We used to think, in the 60's or so, that things like medical diagnosis and chess playing were hard.  We now know that as far as anyone can tell, they are simple search problems; it just happens that the meat computer does search relatively fast and with a lot of parallelism.

There are a number of people, like Jeff Hawkins, who are taking a different approach, and think simulation of the brain is the only way to get something more like what we mean by "thinking"; if they're right, then you're making a category error by saying those don't interest you.

The worst problem with the whole issue is that it appears increasingly difficult to say what we mean when we say we "think and feel" at all.  John Searle, with his "Chinese Room" analogy, would argue that it's actually not possible for a mechanism to "think" or "be conscious".  On the other hand, Alan Turing, with the famous Turing Test, proposed a weaker definition: for Turing, if you can't tell the difference between a "really" thinking and feeling being and a computer simulation of one, then you must assume the simulation is a "thinking and feeling" being.

I tend to come down on Turing's side: after all, I don't know that anyone but me is "
really" a thinking and feeling being.  (To think about that question, look into the idea of a "philosophical zombie", which isn't -- as you might suspect -- a member of the Undead who wonders if there is Meaning in the eating of brains, but instead is a hypothetical entity that isn't conscious, but that perfectly simulates a conscious entity.)

So here's a suggestion: first, think of a way to test, with an effective computation (that is, a halting program or a sequence of tests that is sure to come to a conclusion) if you have really implemented something that can "think and feel"; once you do that, you'll be a long way toward thinking about how to build it.

ContentLicense: CC BY-SA 2.5

Title: Computer simulation of the brain


问:
Unable to type in Visual Studio
I am unable to edit any files in a project in Visual Studio 2013.  It only happens in one project.  If I open a different project I am able to type fine, but once I go back into the problem project I am unable to type in the editor windows.  Not sure if it matters but the project that is giving me issues we are using SVN on.  The other projects are just local ones on the machine.  I have restarted Visual Stuido, restarted the computer and still am unable to edit the files.  Any ideas?</p>

答: Happened to me today, for me the problem was with typescript files. I couldn't write in any .ts file, and this was because I created a tsconfig.json file, but didn't populate it yet (it was empty). Then I was interrupted and forgot I had this empty file, and it took me a while to realize this was the cause of the issue. This issue happened in visual studio 2015.

Title: Unable to type in Visual Studio


问:
Java Swing, how to change the layout after a Next button
I have designed a GUI using Swing components. I have added a Next Button and when someone press it I want to appear another layout of the same GUI. Something like when I pressed proceed in this site in order to write the question.</p>

答:
Sounds like you will want to use a CardLayout. You can define multiple panels to occupy the same space in the frame. You can swap the panel that is displayed based on your requirements.

So based on your question, the "Next" button would just display the next panel added to the CardLayout.

Read the section from the swing tutorial on How to Use CardLayout for more information and working examples.


问:
Creating lists based on two conditions
I am trying to create lists based on data from users.  The data is a 16 question survey, and so I want to split the data into a list of the 16 answers, or a list that is just answers = ['No data available]  My code so far is shown below.

```<code>studentanswers = []
contains_data = False
temp = []
for i in answers:
if i == 'No data available':
    if contains_data:
        studentanswers.append(temp)
        temp = []
        studentanswers.append([i])
        contains_data = False
    else:
        studentanswers.append([i])
else:
    contains_data = True
    if len(temp) < 16:
        temp.append(i)
    else:
        studentanswers.append(temp)
        temp = []
        contains_data = False
</code>```

However, as I iterate, the data gets off the correct count, and some of the data gets assigned to the wrong user.  For example, question 16 for student 1 will become question 1 for student 2.

答:
Your question is unclear, if i got it right, you want a list of the answers of each student.

If this is the case then this should suffice:

```<code>studentanswers = list()
for x in range(len(answers)/16):
    sudentsanswers.append(list(answers[y*16:(y+1)*16])
</code>```

This assumes you have 16 answers for every student.

Edit, i just saw your other comment, this will work:

```<code>studentanswers = list()
studentanswers.append(list())
c = int(0)
for x in range(len(answers)):
    if (c<16 && x  != "No data available"):
        studentanswers[len(studentanswers)-1].append(x)
        c+=1
    else:
        c=0
        studentanswers.append(list())
        studentanswers[len(studentanswers)-1].append(x)
        if x == "No data available":
            studentanswers.append(list())
</code>```

Title: Creating lists based on two conditions

Body:
I am trying to create lists based on data from users.  The data is a 16 question survey, and so I want to split the data into a list of the 16 answers, or a list that is just answers = ['No data available]  My code so far is shown below.

studentanswers = []
contains_data = False
temp = []
for i in answers:
if i == 'No data available':
    if contains_data:
        studentanswers.append(temp)
        temp = []
        studentanswers.append([i])
        contains_data = False
    else:
        studentanswers.append([i])
else:
    contains_data = True
    if len(temp) < 16:
        temp.append(i)
    else:
        studentanswers.append(temp)
        temp = []
        contains_data = False

However, as I iterate, the data gets off the correct count, and some of the data gets assigned to the wrong user.  For example, question 16 for student 1 will become question 1 for student 2.

Body:
Your question is unclear, if i got it right, you want a list of the answers of each student.

If this is the case then this should suffice:

studentanswers = list()
for x in range(len(answers)/16):
    sudentsanswers.append(list(answers[y*16:(y+1)*16])

This assumes you have 16 answers for every student.

Edit, i just saw your other comment, this will work:

studentanswers = list()
studentanswers.append(list())
c = int(0)
for x in range(len(answers)):
    if (c<16 && x  != "No data available"):
        studentanswers[len(studentanswers)-1].append(x)
        c+=1
    else:
        c=0
        studentanswers.append(list())
        studentanswers[len(studentanswers)-1].append(x)
        if x == "No data available":
            studentanswers.append(list())


问:
Apache: Redirect all requests to https://www.domain.tld
I can not find a working solution for me.

Here my settings:

```<code># Redirect non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# Redirect http to https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

The each parts work very well but not together.
The part for https redirection always redirect to https://domain.tld so without www, It is ignored.
Does someone know a solution?

Thanks in advance.

答:
Forcing HTTPS and include WWW:

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST}#%{HTTPS}s !^www\.([^#]+)#(?:off|on(s)) [NC]
RewriteRule ^$ http%2://www.%1%{REQUEST_URI} [R=301,L]
</code>```

Should do both in one shot, otherwise you can separate the rules and probably to it this way:

```<code># Rewrite to WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*) https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

# Rewrite HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
</code>```

If the rewrite doesn't work for non-www to www then there's likely a VirtualHost 301 redirect somewhere else (probably in httpd.conf) that is set on the server... It would look similar to this:

httpd.conf

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
    RewriteRule ^(.*)$ https://example.com$1 [L,R=301]
</IfModule>
</code>```

If that is set in httpd.conf it can override the rewrite in .htaccess for non-www to www.

Body:
I can not find a working solution for me.

Here my settings:

# Redirect non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# Redirect http to https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The each parts work very well but not together.
The part for https redirection always redirect to https://domain.tld so without www, It is ignored.
Does someone know a solution?

Thanks in advance.

Body:
Forcing HTTPS and include WWW:

RewriteEngine On
RewriteCond %{HTTP_HOST}#%{HTTPS}s !^www\.([^#]+)#(?:off|on(s)) [NC]
RewriteRule ^$ http%2://www.%1%{REQUEST_URI} [R=301,L]

Should do both in one shot, otherwise you can separate the rules and probably to it this way:

# Rewrite to WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*) https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

# Rewrite HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

If the rewrite doesn't work for non-www to www then there's likely a VirtualHost 301 redirect somewhere else (probably in httpd.conf) that is set on the server... It would look similar to this:

httpd.conf

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
    RewriteRule ^(.*)$ https://example.com$1 [L,R=301]
</IfModule>

If that is set in httpd.conf it can override the rewrite in .htaccess for non-www to www.


问:
Actionscript 3 remove child at point
hi i'm new to AS3 and i was wondering what is the best way to remove a child at a point.
i tried

```<code>Holder.removeChild(Holder.getObjectsUnderPoint(new Point(exampleX, exampleY))[0]);
</code>```

however that returned ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.

any suggestions?

答:
The getObjectsUnderPoint() method will return an Array of DisplayObjects that may not necessarily be direct children of your Holder object, they may be grand children or grand grand children etc...

You could set a conditional like this:

```<code>var objects:Array =  Holder.getObjectsUnderPoint( yourPoint );
for each( var child:DisplayObject in objects )
{
    if( child.parent == Holder )
       Holder.removeChild( child ) ;
}
</code>```

Holder.contains doesn't filter anything since it will return the grandChildren as well... My mistake!

Title: Actionscript 3 remove child at point

Body:
hi i'm new to AS3 and i was wondering what is the best way to remove a child at a point.
i tried

Holder.removeChild(Holder.getObjectsUnderPoint(new Point(exampleX, exampleY))[0]);

however that returned ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.

any suggestions?

Body:
The getObjectsUnderPoint() method will return an Array of DisplayObjects that may not necessarily be direct children of your Holder object, they may be grand children or grand grand children etc...

You could set a conditional like this:

var objects:Array =  Holder.getObjectsUnderPoint( yourPoint );
for each( var child:DisplayObject in objects )
{
    if( child.parent == Holder )
       Holder.removeChild( child ) ;
}

Holder.contains doesn't filter anything since it will return the grandChildren as well... My mistake!


问:
Return multiple React elements in a method without a wrapper element
I'm trying to return multiple React elements from a helper method. I could solve it simply by moving around some code, but I'm wondering if there's a cleaner way to solve it. I have a method that returns part of the render method, and that functions needs to return both a React element and some text. It's clearer through an example:

```<code>class Foo extends React.Component {
  _renderAuthor() {
    if (!this.props.author) {
      return null;
    }

    return [
      ' by ',
      <a href={getAuthorUrl(this.props.author)}>{this.props.author}</a>,
    ]; // Triggers warning: Each child in an array or iterator should have a unique "key" prop.

  render() {
    return (
      <div>
        {this.props.title}
        {this._renderAuthor()}
      </div>
    );
  }
}
</code>```

I know the render method has to return exactly 1 React element. Using a helper method like this would trigger a warning, and fixing the warning (by adding keys) would make the code too convoluted. Is there a clean way to do this without triggering a warning?

Edit:

Another use case:

```<code>render() {
  return (
    <div>
      {user
        ? <h2>{user.name}</h2>
          <p>{user.info}</p>
        : <p>User not found</p>}
    </div>
  );
}
</code>```

Edit 2:

Turns out this isn't possible yet, I wrote about 2 workarounds here: https://www.wptutor.io/web/js/react-multiple-elements-without-wrapper

答:
Perhaps a more simple way would be to rethink how you're architecting your application. However, in a more simple way.

You're triggering the warning because you're trying to render from an array and not react elements but directly html. In order to approach this, you would have to do

```<code>{this._renderAuthor().map(
    (k,i) => (React.addons.createFragment({k}))
    )  }
</code>```

React addons createFragment function basically does that, it reduces your html elements into react fragments that you can render.

React createFragment documentation

Alternatively, in a much better approach, you can create an AuthorLink stateless component like this..

```<code>function AuthorLink(props) {
  return (
    <div className="author-link">
      <span> by </span>
      <a href={props.authorUrl}> {props.author} </a>
    </div>
  });
}
</code>```

and use this in your main component's render

```<code>render() {
  const { author } = this.props;
  return (
    <div>
      {this.props.datePosted}
      <AuthorLink url={getAuthorUrl(author)} author={author} />
    </div>
  );
}
</code>```

Body:
I'm trying to return multiple React elements from a helper method. I could solve it simply by moving around some code, but I'm wondering if there's a cleaner way to solve it. I have a method that returns part of the render method, and that functions needs to return both a React element and some text. It's clearer through an example:

class Foo extends React.Component {
  _renderAuthor() {
    if (!this.props.author) {
      return null;
    }

    return [
      ' by ',
      {this.props.author},
    ]; // Triggers warning: Each child in an array or iterator should have a unique "key" prop.

  render() {
    return (

        {this.props.title}
        {this._renderAuthor()}

    );
  }
}

I know the render method has to return exactly 1 React element. Using a helper method like this would trigger a warning, and fixing the warning (by adding keys) would make the code too convoluted. Is there a clean way to do this without triggering a warning?

Edit:

Another use case:

render() {
  return (

      {user
        ?
{user.name}

{user.info}

        :
User not found
}

  );
}

Edit 2:

Turns out this isn't possible yet, I wrote about 2 workarounds here: https://www.wptutor.io/web/js/react-multiple-elements-without-wrapper

Body:
Perhaps a more simple way would be to rethink how you're architecting your application. However, in a more simple way.

You're triggering the warning because you're trying to render from an array and not react elements but directly html. In order to approach this, you would have to do

{this._renderAuthor().map(
    (k,i) => (React.addons.createFragment({k}))
    )  }

React addons createFragment function basically does that, it reduces your html elements into react fragments that you can render.

React createFragment documentation

Alternatively, in a much better approach, you can create an AuthorLink stateless component like this..

function AuthorLink(props) {
  return (
    <div className="author-link">
      <span> by </span>
      <a href={props.authorUrl}> {props.author} </a>
    </div>
  });
}

and use this in your main component's render

render() {
  const { author } = this.props;
  return (
    <div>
      {this.props.datePosted}
      <AuthorLink url={getAuthorUrl(author)} author={author} />
    </div>
  );
}


问:
Java: Detecting duplicates in Array
I have to write a program that, giving in input various chess pieces, adds them in an array and then finds possible duplicates...</p>

答:
First problem:

When you are adding the first chess piece, i is 0, right? And in the inner for loop, k also starts off as 1, right? So obviously, chessboard[k] and chessboard[i] are equal because k and i are equal!

To solve this, simply include a i != k condition:

```<code>  for (int k=0; k<chessboard.length ; k++){
         // note the condition here
         if (k != i && chessboard[k] == (chessboard[i]) && chessboard[k] == null){
                 JOptionPane.showMessageDialog(null, "Error! There is a duplicate piece on the chessboard: "+chessboard[k]);
                 System.exit(0);
             }
          }
  break;
  }
</code>```

Second problem:

== compares whether the two operands are the same object. Even if two chess piece objects have the same color, type and position, they can still be two independent objects. What you really need here is a way to compare the chess piece objects logically (when two chess pieces' positions are equal, they are equal).

To do this, just add an equals method to Piece. This is a simple implementation:

```<code>@Override
public boolean equals(Object obj) {
    if (obj instance of Piece) {
        Piece other = (Piece)obj;
        return other.position.equals(this.position);
    } else {
        return false;
    }
}
</code>```

You can then call this method, instead of using ==.

Third problem:

This is not really a problem, but I suggest you to change the type of the array to Piece[] instead of Object[], unless you want to store stuff other than chess pieces in there.

Title: Java: Detecting duplicates in Array

Body:
First problem:

When you are adding the first chess piece, i is 0, right? And in the inner for loop, k also starts off as 1, right? So obviously, chessboard[k] and chessboard[i] are equal because k and i are equal!

To solve this, simply include a i != k condition:

  for (int k=0; k<chessboard.length ; k++){
         // note the condition here
         if (k != i && chessboard[k] == (chessboard[i]) && chessboard[k] == null){
                 JOptionPane.showMessageDialog(null, "Error! There is a duplicate piece on the chessboard: "+chessboard[k]);
                 System.exit(0);
             }
          }
  break;
  }

Second problem:

== compares whether the two operands are the same object. Even if two chess piece objects have the same color, type and position, they can still be two independent objects. What you really need here is a way to compare the chess piece objects logically (when two chess pieces' positions are equal, they are equal).

To do this, just add an equals method to Piece. This is a simple implementation:

@Override
public boolean equals(Object obj) {
    if (obj instance of Piece) {
        Piece other = (Piece)obj;
        return other.position.equals(this.position);
    } else {
        return false;
    }
}

You can then call this method, instead of using ==.

Third problem:

This is not really a problem, but I suggest you to change the type of the array to Piece[] instead of Object[], unless you want to store stuff other than chess pieces in there.


问:
Embedded Javascript interpreter for php
Is there some api available for embedding javascript in php - something similar to Jint for .NET.

I would like to allow user to customize workflow by being able to access limited php classes and methods that can be run at server-side.

User writes a code block that gets executed later... for example, js/ecma script code like ...

```<code>if (Contact.Age < 12){
  Contact.setEligibility = false;
}
else{
  Contact.setEligibility = true;
}
</code>```

答:
There's a pseudo-Javascript interpreter called 'phpjs' (php functions implemented in javascript), which I happen to know about. And a fully syntax compatible JS interpreter (written in pure PHP) called Javascript for PHP5: http://j4p5.sourceforge.net/ - implements the JS language, not the DOM or much functions.

If you want a full-fledged and "real" Javascript runtime, then there is a PECL extension for that. http://pecl.php.net/package/spidermonkey (requires custom compiling PHP interpreter).

Title: Embedded Javascript interpreter for php

Body:
Is there some api available for embedding javascript in php - something similar to Jint for .NET.

I would like to allow user to customize workflow by being able to access limited php classes and methods that can be run at server-side.

User writes a code block that gets executed later... for example, js/ecma script code like ...

if (Contact.Age < 12){
  Contact.setEligibility = false;
}
else{
  Contact.setEligibility = true;
}


问:
JS decrement existing array values- NaN error
I have some troubles with NaN values in my array.
I can display that table, but after decrement opration(code at the bottom) when I want display actualized values I get all NaN. I don't have any idea how to fix that. I appreciate any help.

script.js

```<code>[![var result = "<table border=1>";
    for (var i = 0; i < wymiar; i++)
    {
        result += "<tr>";
        for (var j = 0; j < wymiar; j++)
        {
            tablica\[i, j\] = Math.floor((Math.random() * 10) + 1);
            result += "<td>"+tablica\[i,j\]+"</td>";
        }
        result += "</tr>";
    }
    result += "</table>";
    document.getElementById("macierzLosowa").innerHTML = result;][1]][1]

var result1 = "<table border=1>";
    for (var i = 0; i < wymiar; i++)
    {
        result1 += "<tr>";
        for (var j = 0; j < wymiar; j++)
        {
            if (tablica[i, j] < minWWierszu[i])
            {
                minWWierszu[i] = tablica[i, j];
            }
        }
        for (var j = 0; j < wymiar; j++)
        {
            tablica[i, j] -= minWWierszu[i];
            result1 += "<td>"+tablica[i,j]+"</td>";
        }
        result1 += "</tr>";
    }
    result1 += "</table>";
    document.getElementById("NajmniejszeWiersz").innerHTML = result1;
</code>```

index.html

```<code><div id="NajmniejszeWiersz"></div>
</code>```

Live example: https://jsfiddle.net/RadoszSzymon/aydr6bcm/2/

答:
There are several bugs in your code. The most important are:

1) JS has no support for multi-dimensional array in a way you are used to. The way to create a multi-dimensional array is to create an array of arrays. Also access to the cell of 2d array should be tablica[i][j] rather than tablica[i, j]. The wrong one works because , in many languages with C-inspired syntax is actually a valid operator returning its second argument. Thus tablica[i, j] is actually the same as tablica[j] rather than access to (i, j) cell of 2d-array

2) You initialize minWKolumnie two times (and don't use at all) but don't initialize values of minWWierszu that you actually use. The code should be

var minWWierszu = new Array();
var minWKolumnie = new Array();
var tablica = new Array();

for (var i = 0; i < wymiar; i++)
{
    minWKolumnie[i] = Number.MAX_VALUE;
    minWWierszu[i] = Number.MAX_VALUE;
    tablica[i] = new Array();
}
```

<p>Note that in JS you may (many do) use just <code>[]</code> instead of <code>new Array()</code> to create an empty array. </p>

<p>You also need to init (suprisingly unused) <code>jakas</code> 2d array in a similar way but as you create the variable much later I put it into the next loop:</p>

<pre class="lang-js prettyprint-override"><code>var jakas = new Array();
for (var i = 0; i < wymiar; i++)
{
    jakas[i] = new Array();
    for (var j = 0; j < wymiar; j++)
    {
        jakas[i][j] = tablica[i][j];
    }
}
</code>```

After you fix that, code seems to work, look at the updated JS fiddle

Body:
I have some troubles with NaN values in my array.
I can display that table, but after decrement opration(code at the bottom) when I want display actualized values I get all NaN. I don't have any idea how to fix that. I appreciate any help.

script.js

[![var result = "
";
    for (var i = 0; i < wymiar; i++)
    {
        result += "
";
        for (var j = 0; j < wymiar; j++)
        {
            tablica\[i, j\] = Math.floor((Math.random() * 10) + 1);
            result += ""+tablica\[i,j\]+"	";
        }
        result += "
";
    }
    result += "
";
    document.getElementById("macierzLosowa").innerHTML = result;][1]][1]

var result1 = "
";
    for (var i = 0; i < wymiar; i++)
    {
        result1 += "
";
        for (var j = 0; j < wymiar; j++)
        {
            if (tablica[i, j] < minWWierszu[i])
            {
                minWWierszu[i] = tablica[i, j];
            }
        }
        for (var j = 0; j < wymiar; j++)
        {
            tablica[i, j] -= minWWierszu[i];
            result1 += ""+tablica[i,j]+"	";
        }
        result1 += "
";
    }
    result1 += "
";
    document.getElementById("NajmniejszeWiersz").innerHTML = result1;

index.html

Live example: https://jsfiddle.net/RadoszSzymon/aydr6bcm/2/

Body:
There are several bugs in your code. The most important are:

1) JS has no support for multi-dimensional array in a way you are used to. The way to create a multi-dimensional array is to create an array of arrays. Also access to the cell of 2d array should be tablica[i][j] rather than tablica[i, j]. The wrong one works because , in many languages with C-inspired syntax is actually a valid operator returning its second argument. Thus tablica[i, j] is actually the same as tablica[j] rather than access to (i, j) cell of 2d-array

2) You initialize minWKolumnie two times (and don't use at all) but don't initialize values of minWWierszu that you actually use. The code should be

var minWWierszu = new Array();
var minWKolumnie = new Array();
var tablica = new Array();

for (var i = 0; i < wymiar; i++)
{
    minWKolumnie[i] = Number.MAX_VALUE;
    minWWierszu[i] = Number.MAX_VALUE;
    tablica[i] = new Array();
}

Note that in JS you may (many do) use just [] instead of new Array() to create an empty array.

You also need to init (suprisingly unused) jakas 2d array in a similar way but as you create the variable much later I put it into the next loop:

var jakas = new Array();
for (var i = 0; i < wymiar; i++)
{
    jakas[i] = new Array();
    for (var j = 0; j < wymiar; j++)
    {
        jakas[i][j] = tablica[i][j];
    }
}

After you fix that, code seems to work, look at the updated JS fiddle


问:
Pattern Matching for Alternate instances of Eq
So, I create a data type

```<code>data Expr a = Const a
    | Expr a :*: Expr a
</code>```

And I define an instance for Eq for this data type

```<code>instance (Eq m) => Eq (Expr m) where
    Const a == Const b = a == b
    (a :*: b) == (c :*: d) = ((a == c) && (b == d)) || ((a == d) && (b == c))
</code>```

This definition means that order does not matter when comparing two expressions. However, when I use pattern matching to write a function that takes Exprs I cannot just write

```<code>f (Const 1 :*: a) = ...
</code>```

but must also write

```<code>f (a :*: Const 1) = ...
</code>```

in order to catch all cases, even though if I where to compare the two using (==) it would return true.

Is there a way to write just one of the above to expressions and let the instance of Eq take care of the rest? Does pattern matching even use or require an instance of Eq?

答:
An Eq instance has no bearing whatsoever on pattern matches. == is just a library function and checks a particular property that doesn't necessarily have much to do with implementation structure, whereas pattern matches are all about deconstructing a type in its actual ADT structure.

That said, it is possible to fake something similar to what you asked, but I daresay it's not a very good idea to actually do this – doesn't scale and might lead to strange issues later on.

```<code>{-# LANGUAGE PatternSynonyms, ViewPatterns #-}

matchConstFactor :: Expr a -> Maybe (a, Expr a)
matchConstFactor (Const a :*: b) = Just (a, b)
matchConstFactor (a :*: Const b) = Just (b, a)
matchConstFact _ = Nothing

pattern (:.*:) :: a -> Expr a -> Expr a
pattern a :.*: b <- (matchConstFactor -> Just (a, b))
 where a :.*: b = Const a :*: b
</code>```

Body:
So, I create a data type

data Expr a = Const a
    | Expr a :*: Expr a

And I define an instance for Eq for this data type

instance (Eq m) => Eq (Expr m) where
    Const a == Const b = a == b
    (a :*: b) == (c :*: d) = ((a == c) && (b == d)) || ((a == d) && (b == c))

This definition means that order does not matter when comparing two expressions. However, when I use pattern matching to write a function that takes Exprs I cannot just write

f (Const 1 :*: a) = ...

but must also write

f (a :*: Const 1) = ...

in order to catch all cases, even though if I where to compare the two using (==) it would return true.

Is there a way to write just one of the above to expressions and let the instance of Eq take care of the rest? Does pattern matching even use or require an instance of Eq?

Body:
An Eq instance has no bearing whatsoever on pattern matches. == is just a library function and checks a particular property that doesn't necessarily have much to do with implementation structure, whereas pattern matches are all about deconstructing a type in its actual ADT structure.

That said, it is possible to fake something similar to what you asked, but I daresay it's not a very good idea to actually do this – doesn't scale and might lead to strange issues later on.

{-# LANGUAGE PatternSynonyms, ViewPatterns #-}

matchConstFactor :: Expr a -> Maybe (a, Expr a)
matchConstFactor (Const a :*: b) = Just (a, b)
matchConstFactor (a :*: Const b) = Just (b, a)
matchConstFact _ = Nothing

pattern (:.*:) :: a -> Expr a -> Expr a
pattern a :.*: b <- (matchConstFactor -> Just (a, b))
 where a :.*: b = Const a :*: b


答:
Is there a way to write just one of the above to expressions and let the instance of (Eq) take care of the rest?

No.

Does pattern matching even use or require an instance of (Eq)

Only when matching against (number, character or string) literals. You can see the rules in 3.17.2 of https://www.haskell.org/onlinereport/exps.html#pattern-matching and note that case 7 is the only one which mentions ==.

But you can use view patterns:

```<code>const1 (Const 1 :*: a) = Just a
const1 (a :*: Const 1) = Just a
const1 _ = Nothing

f (const1 -> Just a) = ...
</code>```

This may be too ugly if you need other symmetries in other cases and I can't think of a solution for this at the moment.

Title: Pattern Matching for Alternate instances of Eq

Body:
Is there a way to write just one of the above to expressions and let the instance of (Eq) take care of the rest?

No.

Does pattern matching even use or require an instance of (Eq)

Only when matching against (number, character or string) literals. You can see the rules in 3.17.2 of https://www.haskell.org/onlinereport/exps.html#pattern-matching and note that case 7 is the only one which mentions ==.

But you can use view patterns:

const1 (Const 1 :*: a) = Just a
const1 (a :*: Const 1) = Just a
const1 _ = Nothing

f (const1 -> Just a) = ...

This may be too ugly if you need other symmetries in other cases and I can't think of a solution for this at the moment.


问:
Dynamic search option in MVC 1.0
I'm looking for a dynamic way to implement search in my MVC 1.0 application.

Let's say that I have a user control containing a textbox, a dropdown and a button. The user will put a query in the textbox, select the column from which to search in the dropdown and then press the search button.

On doing the above activity I want to do this in the model:

```<code>context.MyViewOrTableName.Where(p => (p.ColumnNameFromTheDropdown.Contains(DataFromTheTextbox)));
</code>```

Whether the above scenario is possible in MVC 1.0 and if so then how?
Any help would be appreciated.

Solution:

```<code>context.MyViewOrTableName.Where("" + ColumnNameFromTheDropdown + ".Contains(@0)", DataFromTheTextbox);
</code>```

This happened only after including the namespace System.Linq.Dynamic created by Scott and referred by Omar in the post below.

答:
I'm currently doing a similar thing.

That is, I have an MVC View which contains various search options (checkbox, dropdown, textbox), and I wanted an elegant way to return "search results".

So I created a simple class - e.g "ProductSearchCriteria".

This class contains nothing but getters/setters for the different search options (which I populate when the form is submitted via model binding).

I then accept this type as a parameter on my BLL method:

```<code>public ICollection<Product> FindProductsForCriteria(ProductSearchCriteria criteria)
{
   return _repository // GenericRepository<Product>
      .Find() // IQueryable<Product>
      .WithSearchCriteria(criteria) // IQueryable<Product>
      .ToList(); // List<Product>
}
</code>```

As to how to apply the filters, well that depends on a few things. Firstly, I don't know if your using Linq-To-Sql, NHibernate, Entity-Framework, etc. Also it depends on your architecture (repository).

You're not going to be able to "dynamically" apply filters via lambda expressions (not easily, anyway).

What I did was create an extension method to gracefully apply the filters:

```<code>public static IQueryable<Product> WithSearchCriteria(this IQueryable<Product> source, ProductSearchCriteria criteria)
{
    var query = source;

   if (criteria.SearchFilterOne != null)
       query = query.Where(x => x.FieldInModel == criteria.SearchFilterOne);
   // inspect other criteria
}
</code>```

As I said, it depends on your architecture and ORM. I use Entity Framework 4.0, which supports deferred execution, meaning I can build up queries on my objects (IQueryable), and apply filters before executing the query.

Title: Dynamic search option in MVC 1.0

Body:
I'm looking for a dynamic way to implement search in my MVC 1.0 application.

Let's say that I have a user control containing a textbox, a dropdown and a button. The user will put a query in the textbox, select the column from which to search in the dropdown and then press the search button.

On doing the above activity I want to do this in the model:

context.MyViewOrTableName.Where(p => (p.ColumnNameFromTheDropdown.Contains(DataFromTheTextbox)));

Whether the above scenario is possible in MVC 1.0 and if so then how?
Any help would be appreciated.

Solution:

context.MyViewOrTableName.Where("" + ColumnNameFromTheDropdown + ".Contains(@0)", DataFromTheTextbox);

This happened only after including the namespace System.Linq.Dynamic created by Scott and referred by Omar in the post below.

Body:
I'm currently doing a similar thing.

That is, I have an MVC View which contains various search options (checkbox, dropdown, textbox), and I wanted an elegant way to return "search results".

So I created a simple class - e.g "ProductSearchCriteria".

This class contains nothing but getters/setters for the different search options (which I populate when the form is submitted via model binding).

I then accept this type as a parameter on my BLL method:

public ICollection<Product> FindProductsForCriteria(ProductSearchCriteria criteria)
{
   return _repository // GenericRepository<Product>
      .Find() // IQueryable<Product>
      .WithSearchCriteria(criteria) // IQueryable<Product>
      .ToList(); // List<Product>
}

As to how to apply the filters, well that depends on a few things. Firstly, I don't know if your using Linq-To-Sql, NHibernate, Entity-Framework, etc. Also it depends on your architecture (repository).

You're not going to be able to "dynamically" apply filters via lambda expressions (not easily, anyway).

What I did was create an extension method to gracefully apply the filters:

public static IQueryable<Product> WithSearchCriteria(this IQueryable<Product> source, ProductSearchCriteria criteria)
{
    var query = source;

   if (criteria.SearchFilterOne != null)
       query = query.Where(x => x.FieldInModel == criteria.SearchFilterOne);
   // inspect other criteria
}

As I said, it depends on your architecture and ORM. I use Entity Framework 4.0, which supports deferred execution, meaning I can build up queries on my objects (IQueryable), and apply filters before executing the query.

ContentLicense: CC BY-SA 4.0


问:
Masonry grid is not loading
I'm struggling a bit – the masonry grid on my website isn't loading on the initial visit to the page (only loads if I refresh again?) All the images in the grid are loading fine, just the script isn't running.

you can view it on the homepage of this site: http://moniquewilmoth.com

答:
Your page is loading multiple versions of jquery (3.1.0 via googleapis-cdn, 3.1.1.from local server and 2.2.0 from cloudflare-CDN) and two versions of masonry (4.1.1 from local server and 4.2.0 via unpkg-CDN).

I think, these different versions are in conflict with each other and causing the trouble. Import only one (the newest) version of these scripts and it should run.

In my case, Masonry is running by testing on Chrome and Firefox on Win 10, but failed IE and Edge (but worked again after reloading the page).

If you intended local fallbacks for CDN-versions, look here:
How to load local script files as fallback in cases where CDN are blocked/unavailable?

Title: Masonry grid is not loading


问:
Openshift for Play: The remote end hung up unexpectedly
I am trying to launch a play project in openshift. The first phase which was nearly 15% of the project was successfully completed and uploaded. So, I guess the initial configuration was okay. Now, after I completed nearly the rest of the project, then when I am trying to push the project using ssh, everytime after a certain time the remote server hangs up with the following message.

```<code>remote: [info] Done packaging.
remote: model contains 69 documentable templates
Connection to blogofprime-thatsqt.rhcloud.com closed by remote host.
fatal: The remote end hung up unexpectedly
error: error in sideband demultiplexer
To ssh://5455ef32e0b8cd379e000293@blogofprime-thatsqt.rhcloud.com/~/git/blogofprime.git/
 + 557ec12...4034b71 HEAD -> master (forced update)
</code>```

Every-time after a certain step remote server hangs up.

My openshift.conf file:

```<code># This is the main configuration file for the application.
# ~~~~~

include "application"

# Secret key
# ~~~~~
# The secret key is used to secure cryptographics functions.
# If you deploy your application to several instances be sure to use the same key!
application.secret="V0sLX<RAciXw_>7^O8y=I4BRW/M4@vhVhF=H44`lMfgAV2hs^Pp?tsfroKt1J3eX"

# The application languages
# ~~~~~
application.langs="en"

# Database configuration
# ~~~~~
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
#

db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://"${OPENSHIFT_MYSQL_DB_HOST}":"${OPENSHIFT_MYSQL_DB_PORT}"/"${OPENSHIFT_APP_NAME}
db.default.user=${OPENSHIFT_MYSQL_DB_USERNAME}
db.default.password=${OPENSHIFT_MYSQL_DB_PASSWORD}

# Evolutions
# ~~~~~
# You can disable evolutions if needed
# evolutionplugin=disabled

# Ebean configuration
# ~~~~~
# You can declare as many Ebean servers as you want.
# By convention, the default server is named `default`
#
ebean.default="models.*"

# Logger
# ~~~~~
# You can also configure logback (http://logback.qos.ch/), by providing a logger.xml file in the conf directory .

# Root logger:
logger.root=ERROR

# Logger used by the framework:
logger.play=INFO

# Logger provided to your application:
logger.application=DEBUG
</code>```

My build.sbt file:

```<code>name := "thatsqt"

version := "1.0-SNAPSHOT"

scalaVersion := "2.11.2" // or "2.10.4"

libraryDependencies ++= Seq(
  // Select Play modules
  jdbc,      // The JDBC connection pool and the play.api.db API
  //anorm,     // Scala RDBMS Library
  javaJdbc,  // Java database API
  javaEbean, // Java Ebean plugin
  javaJpa,   // Java JPA plugin
  filters,   // A set of built-in filters
  javaCore,  // The core Java API
  // WebJars pull in client-side web librarie
  "org.webjars" %% "webjars-play" % "2.3.0",
  "com.typesafe.play" %% "play-slick" % "0.8.0",
  // Add your own project dependencies in the form:
  // "group" % "artifact" % "version"
  "mysql" % "mysql-connector-java" % "5.1.27"
)

fork in Test := false

lazy val root = (project in file(".")).enablePlugins(PlayJava)

EclipseKeys.withSource := true
</code>```

Platform:
I am using Mac OS X and typesafe activator for play framework.

What I tried:
I tried to unset TMOUT in both server and client. At this point I am not very sure whether this is a timeout problem or something else.

My project Link: https://github.com/magurmach/PlayOpenshiftThatsQt

How can I solve this problem?

答:
Does your project include large binary files? This can cause git to take up a lot of RAM server-side, and a small Openshift gear will kill things that take too much RAM.  The solution is to ssh into your Openshift box (using "rhc ssh" or equivalent) and tell the server-side git to limit its RAM use:

```<code>cd git/*.git
git config pack.windowMemory "25m"
git config pack.packSizeLimit "25m"
git config pack.threads "1"
</code>```

and why they didn't do that by default I have no idea.

Also, next time you want to put large binary files into your project, you don't have to check them into the git repository (which will take up space tracking their entire history): you could just instruct your app to download them from another server as needed (the second server needs only the ability to host static files).

Body:
I am trying to launch a play project in openshift. The first phase which was nearly 15% of the project was successfully completed and uploaded. So, I guess the initial configuration was okay. Now, after I completed nearly the rest of the project, then when I am trying to push the project using ssh, everytime after a certain time the remote server hangs up with the following message.

remote: [info] Done packaging.
remote: model contains 69 documentable templates
Connection to blogofprime-thatsqt.rhcloud.com closed by remote host.
fatal: The remote end hung up unexpectedly
error: error in sideband demultiplexer
To ssh://5455ef32e0b8cd379e000293@blogofprime-thatsqt.rhcloud.com/~/git/blogofprime.git/
 + 557ec12...4034b71 HEAD -> master (forced update)

Every-time after a certain step remote server hangs up.

My openshift.conf file:

# This is the main configuration file for the application.
# ~~~~~

include "application"

# Secret key
# ~~~~~
# The secret key is used to secure cryptographics functions.
# If you deploy your application to several instances be sure to use the same key!
application.secret="V0sLX<RAciXw_>7^O8y=I4BRW/M4@vhVhF=H44`lMfgAV2hs^Pp?tsfroKt1J3eX"

# The application languages
# ~~~~~
application.langs="en"

# Database configuration
# ~~~~~
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
#

db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://"${OPENSHIFT_MYSQL_DB_HOST}":"${OPENSHIFT_MYSQL_DB_PORT}"/"${OPENSHIFT_APP_NAME}
db.default.user=${OPENSHIFT_MYSQL_DB_USERNAME}
db.default.password=${OPENSHIFT_MYSQL_DB_PASSWORD}

# Evolutions
# ~~~~~
# You can disable evolutions if needed
# evolutionplugin=disabled

# Ebean configuration
# ~~~~~
# You can declare as many Ebean servers as you want.
# By convention, the default server is named `default`
#
ebean.default="models.*"

# Logger
# ~~~~~
# You can also configure logback (http://logback.qos.ch/), by providing a logger.xml file in the conf directory .

# Root logger:
logger.root=ERROR

# Logger used by the framework:
logger.play=INFO

# Logger provided to your application:
logger.application=DEBUG

My build.sbt file:

name := "thatsqt"

version := "1.0-SNAPSHOT"

scalaVersion := "2.11.2" // or "2.10.4"

libraryDependencies ++= Seq(
  // Select Play modules
  jdbc,      // The JDBC connection pool and the play.api.db API
  //anorm,     // Scala RDBMS Library
  javaJdbc,  // Java database API
  javaEbean, // Java Ebean plugin
  javaJpa,   // Java JPA plugin
  filters,   // A set of built-in filters
  javaCore,  // The core Java API
  // WebJars pull in client-side web librarie
  "org.webjars" %% "webjars-play" % "2.3.0",
  "com.typesafe.play" %% "play-slick" % "0.8.0",
  // Add your own project dependencies in the form:
  // "group" % "artifact" % "version"
  "mysql" % "mysql-connector-java" % "5.1.27"
)

fork in Test := false

lazy val root = (project in file(".")).enablePlugins(PlayJava)

EclipseKeys.withSource := true

Platform:
I am using Mac OS X and typesafe activator for play framework.

What I tried:
I tried to unset TMOUT in both server and client. At this point I am not very sure whether this is a timeout problem or something else.

My project Link: https://github.com/magurmach/PlayOpenshiftThatsQt

How can I solve this problem?

Body:
Does your project include large binary files? This can cause git to take up a lot of RAM server-side, and a small Openshift gear will kill things that take too much RAM.  The solution is to ssh into your Openshift box (using "rhc ssh" or equivalent) and tell the server-side git to limit its RAM use:

cd git/*.git
git config pack.windowMemory "25m"
git config pack.packSizeLimit "25m"
git config pack.threads "1"

and why they didn't do that by default I have no idea.

Also, next time you want to put large binary files into your project, you don't have to check them into the git repository (which will take up space tracking their entire history): you could just instruct your app to download them from another server as needed (the second server needs only the ability to host static files).


问:
javascript in partial view not getting triggered
i have a little challenge with my javascript getting to my partial view. Any help will be highly appreciated
this is my code:

This is the controller code for the partial View. (from a controller called searchController)

```<code> public PartialViewResult PdfPartialView()
    {
        return PartialView();
    }
</code>```

this is the code that opens the partial view

```<code> @Ajax.ActionLink("View pdf", "PdfPartialView", new AjaxOptions { UpdateTargetId = "pdfContainer" })
</code>```

And this is the partial view code:

```<code> @model dynamic
<h4>Partial View That display PDF....</h4><br/>
<embed src="C:/Users/ionyejekwe/Documents/Visual Studio 2015/Projects/OnlineSearchLagos/OnlineSearchLagos/assets/img/gtb.pdf" width="1300" height="600" type="application/pdf"></embed>

<script>
    $(document).ready(function () {
        //parent.document.location.reload();
        alert('hello');
        // Handler for .ready() called.
        window.setTimeout(function () {
            location.href = "https://www.google.co.in";
        }, 5000);
    });
</script>
</code>```

the javascript code is not being triggered.
Please how do i go about this?

答:
With the info you provided, it's probably because you have your script inside $(document).ready().

What you're doing here is binding an Ajax call to an ActionLink. Completed Ajax calls won't trigger a separate ready event for document, so that script will not execute this way.

Something you could do is define a self-calling function;

```<code><script>
    (function(){
        //parent.document.location.reload();
        alert('hello');
        // Handler for .ready() called.
        window.setTimeout(function () {
            location.href = "https://www.google.co.in";
        }, 5000);
   })();
</script>
</code>```

Or, depending on the purpose of the script, put it in a function and bind that to the OnSuccess event of the Ajax call.

Body:
i have a little challenge with my javascript getting to my partial view. Any help will be highly appreciated
this is my code:

This is the controller code for the partial View. (from a controller called searchController)

 public PartialViewResult PdfPartialView()
    {
        return PartialView();
    }

this is the code that opens the partial view

 @Ajax.ActionLink("View pdf", "PdfPartialView", new AjaxOptions { UpdateTargetId = "pdfContainer" })

And this is the partial view code:

 @model dynamic

Partial View That display PDF....

<embed src="C:/Users/ionyejekwe/Documents/Visual Studio 2015/Projects/OnlineSearchLagos/OnlineSearchLagos/assets/img/gtb.pdf" width="1300" height="600" type="application/pdf"></embed>

the javascript code is not being triggered.
Please how do i go about this?

Body:
With the info you provided, it's probably because you have your script inside $(document).ready().

What you're doing here is binding an Ajax call to an ActionLink. Completed Ajax calls won't trigger a separate ready event for document, so that script will not execute this way.

Something you could do is define a self-calling function;

<script>
    (function(){
        //parent.document.location.reload();
        alert('hello');
        // Handler for .ready() called.
        window.setTimeout(function () {
            location.href = "https://www.google.co.in";
        }, 5000);
   })();
</script>

Or, depending on the purpose of the script, put it in a function and bind that to the OnSuccess event of the Ajax call.


问:
Python Create a List file and write query
so sorry for my question if it seems so easy but I am newbie user of python and I can not find a way to solve it.

I have a "dish.py" file which includes some sub-lists

```<code>Fruits={"Ap":Apple
        "Br":Black Mulberry
        "Ch":Black Cherry
        }
Meals={"BN":Bean
        "MT":Meat
        "VG":Vegetable
        }
Legumes={"LN":Green Lentil
        "P": Pea
        "PN":Runner Peanut
        }
</code>```

I want to impelement the dish.py file in a code that at the end, I want to create a query inside of the file

```<code>with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish:
           content = dish.read()
print dish.closed
dm=dict([dish])
nl=[x for x in dm if x[0]=='P']
for x in dm:
    x=str(raw_input("Enter word:"))
   if x in dm:
        print dm[x]
    elif x[0]==("P"):
        nl.append(x)
        print .join( nl)
</code>```

It may be look so messy but

dm=dict([dish]) I want to create a dictionary for query

nl=[x for x in dm if x[0]=='P'] I want to write words begin with "P" letter

Here is my questions:

1. Q: I suppose there is a problem with my dish.py file. How can I reorganize it?

2. Q: How can I apply a query to the file and extract the words begin with "P"
Thank you so much in advance

答:
dict() can't load strings:

```<code>>>> dict("{'a': 1, 'b': 2}")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
  dict("{'a': 1, 'b': 2}")
ValueError: dictionary update sequence element 0 has length 1; 2 is required
</code>```

As a sequence it would be ("{", "'", "a", "'", ":",...

Instead I would use the json module, change the dish.py format (changing extension to .json and using JSON syntax) and change the code.

dish.json

```<code>{
  "Fruits": {
     "Ap": "Apple",
     "Br": "Black Mulberry",
     "Ch": "Black Cherry"
  },
  "Meals": {
     "BN": "Bean",
     "MT": "Meat",
     "VG": "Vegetable"
  },
  "Legumes": {
     "GL": "Green Lentin",
     "P": "Pea",
     "PN": "Running Peanut"
  }
}
</code>```

__init__.py

```<code>import json
with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish:
    content = dish.read()
print(dish.closed)
dm = json.loads(content) # loads JSON
nl=[x for x in dm if x[0]=='P']
for x in dm:
    x = str(raw_input("Enter word:"))
    if x in dm:
        print dm[x]
    elif x[0] == ("P"):
        nl.append(x)
        print "".join(nl)
</code>```

Q: How can I apply a query to the file and extract the words begin with "P" Thank you so much in advance

Assuming that you want to get every string separated by either space or newline and return them into a list, i'd do this:

```<code>import re #Importing RegExp module

def wordsBeginP():
  with open("words.txt") as wordsfile: # Querying a file
    words = wordsfile.open

  parsed = re.sub(r"\n", " ", words) # Replace \n to " "
  return [for i in parsed.split(" ") if i[0] == "P"] # Return list of words
</code>```

Body:
so sorry for my question if it seems so easy but I am newbie user of python and I can not find a way to solve it.

I have a "dish.py" file which includes some sub-lists

Fruits={"Ap":Apple
        "Br":Black Mulberry
        "Ch":Black Cherry
        }
Meals={"BN":Bean
        "MT":Meat
        "VG":Vegetable
        }
Legumes={"LN":Green Lentil
        "P": Pea
        "PN":Runner Peanut
        }

I want to impelement the dish.py file in a code that at the end, I want to create a query inside of the file

with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish:
           content = dish.read()
print dish.closed
dm=dict([dish])
nl=[x for x in dm if x[0]=='P']
for x in dm:
    x=str(raw_input("Enter word:"))
   if x in dm:
        print dm[x]
    elif x[0]==("P"):
        nl.append(x)
        print .join( nl)

It may be look so messy but

dm=dict([dish]) I want to create a dictionary for query

nl=[x for x in dm if x[0]=='P'] I want to write words begin with "P" letter

Here is my questions:

1. Q: I suppose there is a problem with my dish.py file. How can I reorganize it?

2. Q: How can I apply a query to the file and extract the words begin with "P"
Thank you so much in advance

Body:
dict() can't load strings:

>>> dict("{'a': 1, 'b': 2}")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
  dict("{'a': 1, 'b': 2}")
ValueError: dictionary update sequence element 0 has length 1; 2 is required

As a sequence it would be ("{", "'", "a", "'", ":",...

Instead I would use the json module, change the dish.py format (changing extension to .json and using JSON syntax) and change the code.

dish.json

{
  "Fruits": {
     "Ap": "Apple",
     "Br": "Black Mulberry",
     "Ch": "Black Cherry"
  },
  "Meals": {
     "BN": "Bean",
     "MT": "Meat",
     "VG": "Vegetable"
  },
  "Legumes": {
     "GL": "Green Lentin",
     "P": "Pea",
     "PN": "Running Peanut"
  }
}

__init__.py

import json
with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish:
    content = dish.read()
print(dish.closed)
dm = json.loads(content) # loads JSON
nl=[x for x in dm if x[0]=='P']
for x in dm:
    x = str(raw_input("Enter word:"))
    if x in dm:
        print dm[x]
    elif x[0] == ("P"):
        nl.append(x)
        print "".join(nl)

Q: How can I apply a query to the file and extract the words begin with "P" Thank you so much in advance

Assuming that you want to get every string separated by either space or newline and return them into a list, i'd do this:

import re #Importing RegExp module

def wordsBeginP():
  with open("words.txt") as wordsfile: # Querying a file
    words = wordsfile.open

  parsed = re.sub(r"\n", " ", words) # Replace \n to " "
  return [for i in parsed.split(" ") if i[0] == "P"] # Return list of words


问:
How does WordPress recognize my mobile theme?
I already know HTML, CSS and PHP but I'm a complete beginner in WordPress. I've already set up my WordPress-Theme for Desktop and I'm happy with it and now I've tried to make some tweaks for the mobile theme, but when I open my page on my mobile phone, those changes don't show up. They do show up, in fact, when I scale down my browser window - but not on mobile.

I've tried to make the mobile theme by overwriting the CSS-Selectors with the following:

```<code>@media (max-width: 700px) {
    …
}
</code>```

Could it be that WordPress doesn't recognice the @media-Selector? Is there any other CSS-only way to do this without using any plug-ins?

I've already tried finding an answer to my question but all I can find is about plug-ins.

Thanks in advance!

答:
This can't be a WordPress issue, as CSS is interpreted only by the client (being the mobile device or your pc). This may be fixed by adding

```<code><meta name="viewport" content="width=device-width">
</code>```

to your ?

Body:
I already know HTML, CSS and PHP but I'm a complete beginner in WordPress. I've already set up my WordPress-Theme for Desktop and I'm happy with it and now I've tried to make some tweaks for the mobile theme, but when I open my page on my mobile phone, those changes don't show up. They do show up, in fact, when I scale down my browser window - but not on mobile.

I've tried to make the mobile theme by overwriting the CSS-Selectors with the following:

@media (max-width: 700px) {
    …
}

Could it be that WordPress doesn't recognice the @media-Selector? Is there any other CSS-only way to do this without using any plug-ins?

I've already tried finding an answer to my question but all I can find is about plug-ins.

Thanks in advance!

Body:
This can't be a WordPress issue, as CSS is interpreted only by the client (being the mobile device or your pc). This may be fixed by adding

<meta name="viewport" content="width=device-width">

to your <head>?


问:
Facebook API Authentication
if I want to authenticate a user through facebook is it necessary to get an 'offline_access' permission for my application.

It should be possible for the user to link his application profile to his facebook account. So if he is already logged in to facebook he didn't has to authenticate again in my application.

I'm using the PHP-SDK with Zend.

Thank you.

- lony

答:
The php-sdk facebook class has a method - getLoginUrl.

You can pass an array to it, change the array params based on what permissions you need.

```<code>getLoginUrl(array(
                    'req_perms' => 'publish_stream,offline_access'));
</code>```

A detailed list of permissions can be found here -

http://developers.facebook.com/docs/reference/api/user

Title: Facebook API Authentication

Body:
The php-sdk facebook class has a method - getLoginUrl.

You can pass an array to it, change the array params based on what permissions you need.

getLoginUrl(array(
                    'req_perms' => 'publish_stream,offline_access'));

A detailed list of permissions can be found here -

http://developers.facebook.com/docs/reference/api/user


问:
Delete all Data belonging to user
I am rebuilding a social media app like Instagram.

My user can decide to delete their account and then I would like to automatically delete all things belonging to the user.

Most of the stuff I can delete easily, but things like posts is where I struggle because the uid is just a sub child of the key where the post is saved into.

My Database tree:

```<code> "Feed" : {
"es5fIbnKFpX4szcCbroUqHjJg6E3" : {
  "-KjTBFFE5QzktG1IT5u0" : true,
  "-KjTHFNe1RRS8Ly6bKsA" : true,
  "-KjY30xwWA2IJBwlvyzf" : true
}
"myPosts" : {
"jlkRoaucY6Q4GBkzhor5yAAl97I2" : {
  "-KjTBFFE5QzktG1IT5u0" : true,
  "-KjTHFNe1RRS8Ly6bKsA" : true,
  "-KjY30xwWA2IJBwlvyzf" : true
}
 "posts" : {
"-KjTBFFE5QzktG1IT5u0" : {
  "bookmarkCount" : 0,
  "caption" : "Toll",
  "commentCount" : 1,
  "creationDate" : 1.494081403379004E9,
  "hoursSinceUpload" : 0,
  "likeCount" : 0,
  "photoUrl" : "https://firebasestorage.googleapis.com/v0/b/funcloud-8e84e.appspot.com/o/Posts%2F76192CBE-55F0-4907-889A-849E196D5796?alt=media&token=de675609-4b73-411d-b402-f1ff3db64f79",
  "ratio" : 1.502732240437158,
  "score" : 16.38698994684219,
  "uid" : "jlkRoaucY6Q4GBkzhor5yAAl97I2"
},
"-KjTHFNe1RRS8Ly6bKsA" : {
  "bookmarkCount" : 1,
  "bookmarks" : {
    "jlkRoaucY6Q4GBkzhor5yAAl97I2" : true
  },
  "caption" : "Traumhaft",
  "commentCount" : 0,
  "creationDate" : 1.494082976550228E9,
  "hoursSinceUpload" : 0,
  "likeCount" : 2,
  "likes" : {
    "es5fIbnKFpX4szcCbroUqHjJg6E3" : true,
    "jlkRoaucY6Q4GBkzhor5yAAl97I2" : true
  },
  "photoUrl" : "https://firebasestorage.googleapis.com/v0/b/funcloud-8e84e.appspot.com/o/Posts%2F306BF7E1-9FEF-493A-ABF8-C0E061E8648F?alt=media&token=128bdd90-023a-49ac-8361-19c02c631183",
  "ratio" : 1.502732240437158,
  "score" : 166.6491847103437,
  "uid" : "jlkRoaucY6Q4GBkzhor5yAAl97I2"
}
"users" : {
"es5fIbnKFpX4szcCbroUqHjJg6E3" : {
  "email" : "user3@mail.de",
  "profilText" : "Schreib etwas über dich",
  "profileImageUrl" : "https://firebasestorage.googleapis.com/v0/b/funcloud-8e84e.appspot.com/o/profile_image%2Fes5fIbnKFpX4szcCbroUqHjJg6E3?alt=media&token=ce8d8722-39bc-457a-8149-e51c837ef0a3",
  "username" : "Blondine",
  "username_lowercase" : "blondine"
}
</code>```

My function where I delete data

```<code>    static func removeUserData() {

    let user = Auth.auth().currentUser

    let uid = API.User.CURRENT_USER?.uid

    Database.database().reference().child("users").child(uid!).removeValue()
    Database.database().reference().child("Feed").child(uid!).removeValue()
    Database.database().reference().child("Favoriten").child(uid!).removeValue()
    Database.database().reference().child("LikesFromUsers").child(uid!).removeValue()
    Database.database().reference().child("post-comments").child(uid!).removeValue()
    Database.database().reference().child("notification").child(uid!).removeValue()
    Database.database().reference().child("followers").child(uid!).removeValue()
    Database.database().reference().child("following").child(uid!).removeValue()
Database.database().reference().child("LikesCommentsFromUsers").child(uid!).removeValue()
Database.database().reference().child("comments").child(uid!).removeValue()

    user?.delete(completion: { (error) in
        if let error = error {
            print(error.localizedDescription)
        } else {
            print("success")

        }
    })
}
</code>```

I would love to iterate through all posts and look for every post which contains the uid of the current user and then delete these posts.

Thanks in advance :)

答:
I would build a server task that can run this asynchronously, removing the responsibility from the mobile device. If the app crashes or loses connection, you'll get a severely broken data set. You need to be able to run it in a stable and verifiable environment. This inherently solves your problem as well, since now you can (at your server's leisure) cycle through and delete all posts owned by the user.

As far as your app is concerned, you'll just need to call a single API after validating that the user wants to delete their account, and voila.

Title: Delete all Data belonging to user

Body:
I am rebuilding a social media app like Instagram.

My user can decide to delete their account and then I would like to automatically delete all things belonging to the user.

Most of the stuff I can delete easily, but things like posts is where I struggle because the uid is just a sub child of the key where the post is saved into.

My Database tree:

 "Feed" : {
"es5fIbnKFpX4szcCbroUqHjJg6E3" : {
  "-KjTBFFE5QzktG1IT5u0" : true,
  "-KjTHFNe1RRS8Ly6bKsA" : true,
  "-KjY30xwWA2IJBwlvyzf" : true
}
"myPosts" : {
"jlkRoaucY6Q4GBkzhor5yAAl97I2" : {
  "-KjTBFFE5QzktG1IT5u0" : true,
  "-KjTHFNe1RRS8Ly6bKsA" : true,
  "-KjY30xwWA2IJBwlvyzf" : true
}
 "posts" : {
"-KjTBFFE5QzktG1IT5u0" : {
  "bookmarkCount" : 0,
  "caption" : "Toll",
  "commentCount" : 1,
  "creationDate" : 1.494081403379004E9,
  "hoursSinceUpload" : 0,
  "likeCount" : 0,
  "photoUrl" : "https://firebasestorage.googleapis.com/v0/b/funcloud-8e84e.appspot.com/o/Posts%2F76192CBE-55F0-4907-889A-849E196D5796?alt=media&token=de675609-4b73-411d-b402-f1ff3db64f79",
  "ratio" : 1.502732240437158,
  "score" : 16.38698994684219,
  "uid" : "jlkRoaucY6Q4GBkzhor5yAAl97I2"
},
"-KjTHFNe1RRS8Ly6bKsA" : {
  "bookmarkCount" : 1,
  "bookmarks" : {
    "jlkRoaucY6Q4GBkzhor5yAAl97I2" : true
  },
  "caption" : "Traumhaft",
  "commentCount" : 0,
  "creationDate" : 1.494082976550228E9,
  "hoursSinceUpload" : 0,
  "likeCount" : 2,
  "likes" : {
    "es5fIbnKFpX4szcCbroUqHjJg6E3" : true,
    "jlkRoaucY6Q4GBkzhor5yAAl97I2" : true
  },
  "photoUrl" : "https://firebasestorage.googleapis.com/v0/b/funcloud-8e84e.appspot.com/o/Posts%2F306BF7E1-9FEF-493A-ABF8-C0E061E8648F?alt=media&token=128bdd90-023a-49ac-8361-19c02c631183",
  "ratio" : 1.502732240437158,
  "score" : 166.6491847103437,
  "uid" : "jlkRoaucY6Q4GBkzhor5yAAl97I2"
}
"users" : {
"es5fIbnKFpX4szcCbroUqHjJg6E3" : {
  "email" : "user3@mail.de",
  "profilText" : "Schreib etwas über dich",
  "profileImageUrl" : "https://firebasestorage.googleapis.com/v0/b/funcloud-8e84e.appspot.com/o/profile_image%2Fes5fIbnKFpX4szcCbroUqHjJg6E3?alt=media&token=ce8d8722-39bc-457a-8149-e51c837ef0a3",
  "username" : "Blondine",
  "username_lowercase" : "blondine"
}

My function where I delete data

    static func removeUserData() {

    let user = Auth.auth().currentUser

    let uid = API.User.CURRENT_USER?.uid

    Database.database().reference().child("users").child(uid!).removeValue()
    Database.database().reference().child("Feed").child(uid!).removeValue()
    Database.database().reference().child("Favoriten").child(uid!).removeValue()
    Database.database().reference().child("LikesFromUsers").child(uid!).removeValue()
    Database.database().reference().child("post-comments").child(uid!).removeValue()
    Database.database().reference().child("notification").child(uid!).removeValue()
    Database.database().reference().child("followers").child(uid!).removeValue()
    Database.database().reference().child("following").child(uid!).removeValue()
Database.database().reference().child("LikesCommentsFromUsers").child(uid!).removeValue()
Database.database().reference().child("comments").child(uid!).removeValue()

    user?.delete(completion: { (error) in
        if let error = error {
            print(error.localizedDescription)
        } else {
            print("success")

        }
    })
}

I would love to iterate through all posts and look for every post which contains the uid of the current user and then delete these posts.

Thanks in advance :)


问:
Show X axis on top and bottom in line chart rendered with Chart.js 2.4.0
I have a line chart rendered with Chart.js and I display the X axis at the bottom:

```<code>xAxes: [{  type: 'linear',
           position: 'bottom',
</code>```

I would like to have two X axis, one at the bottom and one at the top.
I see in the documentation that position is a string, thus one value only.

Is it possible to accomplish this?

答:
This is an old question, but I just had the same problem. Luckily the value of xAxes is an array, so you define multiple axes like this:</p>

```<code>xAxes: [
    { position: 'top' },
    { position: 'bottom', ... other definitions here ... }
]
</code>```

Body:
I have a line chart rendered with Chart.js and I display the X axis at the bottom:

xAxes: [{  type: 'linear',
           position: 'bottom',

I would like to have two X axis, one at the bottom and one at the top.
I see in the documentation that position is a string, thus one value only.

Is it possible to accomplish this?

Body:
This is an old question, but I just had the same problem. Luckily the value of xAxes is an array, so you define multiple axes like this:

xAxes: [
    { position: 'top' },
    { position: 'bottom', ... other definitions here ... }
]


问:
Symfony2 ManyToMany in one query
I have 2 entities related ManyToMany

```<code>class Product
{

/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=100, unique=true)
 */
private $name;

/**
 * @ORM\ManyToMany(targetEntity="ProductTransfer", inversedBy="product")
 * @ORM\JoinTable(name="products_transfers")
 */
private $transfers;
</code>```

and second one

```<code>class ProductTransfer
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var int
 *
 * @ORM\Column(name="stock_from_id", type="integer")
 */
private $stockFromId;

/**
 * @var int
 *
 * @ORM\Column(name="stock_to_id", type="integer")
 */
private $stockToId;

/**
 * @var int
 *
 * @ORM\Column(name="product_id", type="integer")
 */
private $productId;

/**
 * @ORM\ManyToMany(targetEntity="Product",mappedBy="transfers")
 */
private $product;
</code>```

All works great, additional table were created by Doctrine.

But when I'm trying to get all rows from ProductTransfers I see in profiler that each row need one single query with 2 joins.

So for 5000 products it will be really many queries.

Is there any way to get them all in one query like in "clean SQL"?
If there is no way to do it with Doctrine, what is best way to achieve that?

Like:

```<code>SELECT * FROM product_transfer pt
LEFT JOIN products_transfers pts ON pt.product_id=pts.product_id
LEFT JOIN product p ON pts.product_id=p.id;
</code>```

edit:
created method in repository

```<code>public function loadTransfersByStock($stockId)
{

    $q = $this->getEntityManager()
        ->createQuery(
            'SELECT pt,p FROM AppBundle:ProductTransfer pt
            LEFT JOIN AppBundle:Product p WITH pt.productId=p.id
            WHERE pt.stockToId = :stockId'
        );

    return $q->setParameter('stockId', $stockId)->getResult();
}
</code>```

and then result is

```<code>ProductsController.php on line 495:
array:3 [▼
  0 => ProductTransfer {#1071 ▶}
  1 => Product {#1084 ▶}
  2 => ProductTransfer {#1099 ▶}
]
</code>```

答:
By default Doctrine uses lazy loading in object relations - the rows for the relationships are only loaded when you try to access them. If you know you're going to be needing all the related rows, try changing to eager fetching.</p>

```<code>/**
 * @ORM\ManyToMany(targetEntity="ProductTransfer", inversedBy="product", fetch="EAGER")
 * @ORM\JoinTable(name="products_transfers")
 */
</code>```

Title: Symfony2 ManyToMany in one query

Body:
I have 2 entities related ManyToMany

class Product
{

/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=100, unique=true)
 */
private $name;

/**
 * @ORM\ManyToMany(targetEntity="ProductTransfer", inversedBy="product")
 * @ORM\JoinTable(name="products_transfers")
 */
private $transfers;

and second one

class ProductTransfer
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var int
 *
 * @ORM\Column(name="stock_from_id", type="integer")
 */
private $stockFromId;

/**
 * @var int
 *
 * @ORM\Column(name="stock_to_id", type="integer")
 */
private $stockToId;

/**
 * @var int
 *
 * @ORM\Column(name="product_id", type="integer")
 */
private $productId;

/**
 * @ORM\ManyToMany(targetEntity="Product",mappedBy="transfers")
 */
private $product;

All works great, additional table were created by Doctrine.

But when I'm trying to get all rows from ProductTransfers I see in profiler that each row need one single query with 2 joins.

So for 5000 products it will be really many queries.

Is there any way to get them all in one query like in "clean SQL"?
If there is no way to do it with Doctrine, what is best way to achieve that?

Like:

SELECT * FROM product_transfer pt
LEFT JOIN products_transfers pts ON pt.product_id=pts.product_id
LEFT JOIN product p ON pts.product_id=p.id;

edit:
created method in repository

public function loadTransfersByStock($stockId)
{

    $q = $this->getEntityManager()
        ->createQuery(
            'SELECT pt,p FROM AppBundle:ProductTransfer pt
            LEFT JOIN AppBundle:Product p WITH pt.productId=p.id
            WHERE pt.stockToId = :stockId'
        );

    return $q->setParameter('stockId', $stockId)->getResult();
}

and then result is

ProductsController.php on line 495:
array:3 [▼
  0 => ProductTransfer {#1071 ▶}
  1 => Product {#1084 ▶}
  2 => ProductTransfer {#1099 ▶}
]

Body:
By default Doctrine uses lazy loading in object relations - the rows for the relationships are only loaded when you try to access them. If you know you're going to be needing all the related rows, try changing to eager fetching.

/**
 * @ORM\ManyToMany(targetEntity="ProductTransfer", inversedBy="product", fetch="EAGER")
 * @ORM\JoinTable(name="products_transfers")
 */


问:
Change focus of text input with react
My goal here is to create a form, which tabs you to the next input element when you hit the return key and submits the form when you are on the last input.

This is being built for mobile, and since there is no option to use the 'next' button instead of the 'go keyboard' button in browser (for more information about this see this answer).

To better visualize this, here is a picture:

I've also written some code, but the point here is that I am not able to catch the event in the right place, so the form gets immediately submitted after the return or when I prevent the event, the focus is changed after I hit return 2 times.

See the example here: https://codepen.io/ofhouse/pen/Rgwzxy (I've also pasted the code below)

```<code>class TextInput extends React.Component {
  constructor(props) {
    super(props);
    this._onKeyPress = this._onKeyPress.bind(this);
  }

  componentDidMount() {
    if (this.props.focus) {
      this.textInput.focus();
    }
  }

  componentDidUpdate(nextProps) {
    if (nextProps.focus) {
      this.textInput.focus();
    }
  }

  _onKeyPress(e) {
    if (e.key === 'Enter') {
      this.props.onSubmit(e);
    }
  }

  render() {
    return (
      <div>
        <input
          type="text"
          onKeyPress={this._onKeyPress}
          ref={input => {
            this.textInput = input;
          }}
        />
      </div>
    );
  }
}

class Application extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      currentElement: 0,
    };
  }

  _submitForm(e) {
    // If I remove this preventDefault it works, but also the form is submitted --> SiteReload
    e.preventDefault();
  }

  _changeFocus(nextElement) {
    return e => {
      this.setState({
        currentElement: nextElement,
      });
    };
  }

  render() {
    const { currentElement } = this.state;
    return (
      <form>

        <h1>React input focus</h1>

        <TextInput focus={currentElement === 0} onSubmit={this._changeFocus(1)} />
        <TextInput focus={currentElement === 1} onSubmit={this._changeFocus(0)} />

        <div>
          <button type="submit" onClick={this._submitForm}>Submit</button>
        </div>

      </form>
    );
  }
}

ReactDOM.render(<Application />, document.getElementById('app'));
</code>```

答:
I don't think you're using the best approach, let me explain. The focusing of inputs is done by the focus method of the native DOM element. To know what input to focus based on which input has the current focus is a logic that has to be implemented in the container of those inputs, the Application component in your case.

I've made some significant changes to your code and now it's working: CodePen

Let me explain it:

First of all, we're preventing the submit of the keyPressed event of the input when the key pressed is 'Enter', to prevent the form submit

```<code>_onKeyPress(e) {
  if (e.key === 'Enter') {
    this.props.onSubmit(e);
    e.preventDefault();
  }
}
</code>```

We don't need either componenDidMount nor componentDidUpdate in TextInput all we need is a focus method:

```<code>focus() {
  this.textInput.focus();
}
</code>```

Most of the changes are made in the Application component. First of all, we don't need the state, what we really need is to have the inputs in an array so we can call focus on them.

```<code>constructor(props) {
  super(props);

  this.inputs = [];
}
</code>```

To change the focus, we just need the index of the input to call the focus method of the TextInput component:

```<code>_changeFocus(index) {
  return e => {
    this.inputs[index].focus();
  };
}
</code>```

Then we need a way to add the inputs into this.inputs, the ref property would be ideal, I've create the method _addInput as a helper for this:

```<code>_addInput(index) {
  return input => {
    this.inputs[index] = input;
  };
}
</code>```

Finally, when rendering the TextInputs you need to pass them _addInput to ref and _changeFocus to onSubmit, with their respective indexes:

```<code><TextInput ref={this._addInput(0)} onSubmit={this._changeFocus(1)} />
<TextInput ref={this._addInput(1)} onSubmit={this._changeFocus(0)} />
</code>```

In the second TextInput I'm changing the focus to the first one, but maybe submitting the form would be more useful.

Title: Change focus of text input with react

Body:
My goal here is to create a form, which tabs you to the next input element when you hit the return key and submits the form when you are on the last input.

This is being built for mobile, and since there is no option to use the 'next' button instead of the 'go keyboard' button in browser (for more information about this see this answer).

To better visualize this, here is a picture:

I've also written some code, but the point here is that I am not able to catch the event in the right place, so the form gets immediately submitted after the return or when I prevent the event, the focus is changed after I hit return 2 times.

See the example here: https://codepen.io/ofhouse/pen/Rgwzxy (I've also pasted the code below)

class TextInput extends React.Component {
  constructor(props) {
    super(props);
    this._onKeyPress = this._onKeyPress.bind(this);
  }

  componentDidMount() {
    if (this.props.focus) {
      this.textInput.focus();
    }
  }

  componentDidUpdate(nextProps) {
    if (nextProps.focus) {
      this.textInput.focus();
    }
  }

  _onKeyPress(e) {
    if (e.key === 'Enter') {
      this.props.onSubmit(e);
    }
  }

  render() {
    return (

        <input
          type="text"
          onKeyPress={this._onKeyPress}
          ref={input => {
            this.textInput = input;
          }}
        />

    );
  }
}

class Application extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      currentElement: 0,
    };
  }

  _submitForm(e) {
    // If I remove this preventDefault it works, but also the form is submitted --> SiteReload
    e.preventDefault();
  }

  _changeFocus(nextElement) {
    return e => {
      this.setState({
        currentElement: nextElement,
      });
    };
  }

  render() {
    const { currentElement } = this.state;
    return (
      <form>

React input focus

        <TextInput focus={currentElement === 0} onSubmit={this._changeFocus(1)} />
        <TextInput focus={currentElement === 1} onSubmit={this._changeFocus(0)} />

          <button type="submit" onClick={this._submitForm}>Submit</button>

      </form>
    );
  }
}

ReactDOM.render(<Application />, document.getElementById('app'));

Body:
I don't think you're using the best approach, let me explain. The focusing of inputs is done by the focus method of the native DOM element. To know what input to focus based on which input has the current focus is a logic that has to be implemented in the container of those inputs, the Application component in your case.

I've made some significant changes to your code and now it's working: CodePen

Let me explain it:

First of all, we're preventing the submit of the keyPressed event of the input when the key pressed is 'Enter', to prevent the form submit

_onKeyPress(e) {
  if (e.key === 'Enter') {
    this.props.onSubmit(e);
    e.preventDefault();
  }
}

We don't need either componenDidMount nor componentDidUpdate in TextInput all we need is a focus method:

focus() {
  this.textInput.focus();
}

Most of the changes are made in the Application component. First of all, we don't need the state, what we really need is to have the inputs in an array so we can call focus on them.

constructor(props) {
  super(props);

  this.inputs = [];
}

To change the focus, we just need the index of the input to call the focus method of the TextInput component:

_changeFocus(index) {
  return e => {
    this.inputs[index].focus();
  };
}

Then we need a way to add the inputs into this.inputs, the ref property would be ideal, I've create the method _addInput as a helper for this:

_addInput(index) {
  return input => {
    this.inputs[index] = input;
  };
}

Finally, when rendering the TextInputs you need to pass them _addInput to ref and _changeFocus to onSubmit, with their respective indexes:

<TextInput ref={this._addInput(0)} onSubmit={this._changeFocus(1)} />
<TextInput ref={this._addInput(1)} onSubmit={this._changeFocus(0)} />

In the second TextInput I'm changing the focus to the first one, but maybe submitting the form would be more useful.