问:
Getting an IndexOutOfBoundsException: -1 when no negative numbers are involved
I've been creating a graph to run my implementation of A* on, and I seem to be stuck at a certain error for finding the neighbours of a node. My logic is that in my 2D ArrayList which represents an adjacency matrix, I have in list 1: Nodes a b c d, and in List 2, Nodes a b c d, and the indexes at which they meet should have a value other than 0 in them to show that an edge exists. This is what I'm trying to do here:

```<code>public List<Node> neighbours(Node a){
        List<Node> neighbours = new ArrayList<Node>();
        for(int i = 0; i < nodes.size() - 1; i ++){
            int n = matrix.get(matrix.indexOf(a)).get(i);
            if (n != 0){
                neighbours.add(nodes.get(i));
            }
        }
        return neighbours;
    }
</code>```

However I get a nice Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 error, I've stared at this for 30 minutes but I have no clue where this -1 is coming from. I will also add the code for the construction of the matrix as this may hold a clue:

```<code>public void addNode (Node a){
        int count = 0;
        nodes.add(a);
        matrix.add(new ArrayList<Integer>(nodes.size()));
        for (List<Integer> list : matrix){
            count++;
            int diff = Math.abs(nodes.size() - list.size());
            if (diff != 0){
                for (int i = 0; i < diff; i ++)
                    matrix.get(count-1).add(0);
            }
        }
    }
</code>```

I update the size of the matrix each time a node is added.
I hope this isn't a case where the answer is just staring me in the face but I'm too tired to see it. Thanks for any help!

答:
You've already coded the -1 in:

```<code>    for(int i = 0; i < nodes.size() - 1; i ++){
</code>```

It is pretty sure the cause of the exception, So nodes is created but it has no elements in it (zero as size minus one returns -1). But without the full running example it's hard to say. It's not a problem of the code but of the sample data. Please include a fully running code.

Body:
I've been creating a graph to run my implementation of A* on, and I seem to be stuck at a certain error for finding the neighbours of a node. My logic is that in my 2D ArrayList which represents an adjacency matrix, I have in list 1: Nodes a b c d, and in List 2, Nodes a b c d, and the indexes at which they meet should have a value other than 0 in them to show that an edge exists. This is what I'm trying to do here:

public List<Node> neighbours(Node a){
        List<Node> neighbours = new ArrayList<Node>();
        for(int i = 0; i < nodes.size() - 1; i ++){
            int n = matrix.get(matrix.indexOf(a)).get(i);
            if (n != 0){
                neighbours.add(nodes.get(i));
            }
        }
        return neighbours;
    }

However I get a nice Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 error, I've stared at this for 30 minutes but I have no clue where this -1 is coming from. I will also add the code for the construction of the matrix as this may hold a clue:

public void addNode (Node a){
        int count = 0;
        nodes.add(a);
        matrix.add(new ArrayList<Integer>(nodes.size()));
        for (List<Integer> list : matrix){
            count++;
            int diff = Math.abs(nodes.size() - list.size());
            if (diff != 0){
                for (int i = 0; i < diff; i ++)
                    matrix.get(count-1).add(0);
            }
        }
    }

I update the size of the matrix each time a node is added.
I hope this isn't a case where the answer is just staring me in the face but I'm too tired to see it. Thanks for any help!

Body:
You've already coded the -1 in:

    for(int i = 0; i < nodes.size() - 1; i ++){

It is pretty sure the cause of the exception, So nodes is created but it has no elements in it (zero as size minus one returns -1). But without the full running example it's hard to say. It's not a problem of the code but of the sample data. Please include a fully running code.


来源: stackexchange

问:
Grouping Rows as Dictionary in Python
I have an input file as this :

```<code>5181        zzzzzzzzzzzzzzzz
6220        aaaaaaaa
1498        bbbbbbbbb
1498        ccccccccccc
</code>```

I want to group the lines which has same id number. So it will be like this:

```<code>5181        zzzzzzzzzzzzzzzz
6220        aaaaaaaa
1498        bbbbbbbbbb
1498        ccccccccccc
</code>```

I tried to create a dictionary with 3 keys but couldnt append all values.

This is what i wrote:

```<code>for i in package_ids:
    dict2[i] = (x for x in textt if int(i) in textt is True)
</code>```

答:
You can use a collections.defaultdict:

```<code>from collections import defaultdict
d = defaultdict(list)
file_data = [[int(a), b] for a, b in [i.strip('\n').split('\t') for i in open('filename.txt')]]
for a, b in file_data:
   d[a].append(b)

for a, b in sorted(d.items(), key=lambda x:x[0]):
    print(a, b)
</code>```

Without defaultdict:

```<code>d = {}
for a, b in file_data:
   if a not in d:
       d[a] = [b]
   else:
       d[a].append(b)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Grouping Rows as Dictionary in Python

Body:
I have an input file as this :

5181        zzzzzzzzzzzzzzzz
6220        aaaaaaaa
1498        bbbbbbbbb
1498        ccccccccccc

I want to group the lines which has same id number. So it will be like this:

5181        zzzzzzzzzzzzzzzz
6220        aaaaaaaa
1498        bbbbbbbbbb
1498        ccccccccccc

I tried to create a dictionary with 3 keys but couldnt append all values.

This is what i wrote:

for i in package_ids:
    dict2[i] = (x for x in textt if int(i) in textt is True)

Body:
You can use a collections.defaultdict:

from collections import defaultdict
d = defaultdict(list)
file_data = [[int(a), b] for a, b in [i.strip('\n').split('\t') for i in open('filename.txt')]]
for a, b in file_data:
   d[a].append(b)

for a, b in sorted(d.items(), key=lambda x:x[0]):
    print(a, b)

Without defaultdict:

d = {}
for a, b in file_data:
   if a not in d:
       d[a] = [b]
   else:
       d[a].append(b)


问:
C# WebClient Exception: The underlying connection was closed
i am sending xml data to UPS web site, some time i am getting response and some time i am getting the Exception: The underlying connection was closed

see a sample code which send xml to a specific UPS url.

```<code>    public ShippingAcceptResult ShippingAccept(string acceptDigestCode)
    {
    string strXml = "";
    try
    {
        xmlRequest = new System.Xml.XmlDocument();
        xmlRequest.LoadXml(@"<?xml version=""1.0""?>
     <ShipmentAcceptRequest>
       <Request>
          <TransactionReference>
         <CustomerContext>TR01</CustomerContext>
         <XpciVersion>1.0001</XpciVersion>
          </TransactionReference>
          <RequestAction>ShipAccept</RequestAction>
          <RequestOption>01</RequestOption>
       </Request>
       <ShipmentDigest>" + acceptDigestCode + "</ShipmentDigest></ShipmentAcceptRequest>");

        byte[] bb = new System.Text.ASCIIEncoding().GetBytes(string.Format(XML_CONNECT, sAccessCode.Trim(), sUserId.Trim(), sPassword.Trim()));
        byte[] bResponse = null;
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        ms.Write(bb, 0, bb.Length);
        xmlRequest.Save(ms);
        bb = ms.ToArray();
        xmlRespone = new XmlDocument();
        string serverName = (testMode) ? "wwwcie" : "onlinetools.ups.com";
        serverName = string.Format(UPS_SERVICE_URL, serverName, ShipRequestTypes.ShipAccept);

        using (var client = new NoKeepAlivesWebClient())
        {
        bResponse = client.UploadData(serverName, "POST", bb);
        }

        if (bResponse != null)
        {
        xmlRespone.LoadXml(System.Text.ASCIIEncoding.ASCII.GetString(bResponse));
        }
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show("ShippingAccept " + ex.Message);
        System.Windows.Forms.MessageBox.Show(strXml);
    }
    return new ShippingAcceptResult(xmlRespone);

}

public class NoKeepAlivesWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
        ((HttpWebRequest)request).KeepAlive = false;
        }

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

before i did not set KeepAlive = false then also i was getting same error message but now when i set KeepAlive = false then also some time getting the same connection close related error.

tell me the error is specific to any pc?

should i set timeout value for webclient like KeepAlive option?

so please someone drive me to right direction to get rid of this error.

tell me all possible reason for which error is occurring. thanks

答:
actually these line of code solve my issue

```<code>ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; //768 for TLS 1.1 and 3072 for TLS 1.2
//ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
//System.Net.ServicePointManager.ServerCertificateValidationCallback += (send, certificate, chain, sslPolicyErrors) => { return true; };
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
</code>```

few more code snippet i used along with ServicePointManager

```<code>using (var client = new NoKeepAlivesWebClient())
{
    bResponse = client.UploadData(serverName, "POST", bb);
}

/// Certificate validation callback.
/// </summary>
private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
    // If the certificate is a valid, signed certificate, return true.
    if (error == System.Net.Security.SslPolicyErrors.None)
    {
    return true;
    }

    Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'",
    cert.Subject,
    error.ToString());

    return false;
}

public class NoKeepAlivesWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
        ((HttpWebRequest)request).KeepAlive = false;
        ((HttpWebRequest)request).Timeout = 60000;
        }

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

Body:
i am sending xml data to UPS web site, some time i am getting response and some time i am getting the Exception: The underlying connection was closed

see a sample code which send xml to a specific UPS url.

    public ShippingAcceptResult ShippingAccept(string acceptDigestCode)
    {
    string strXml = "";
    try
    {
        xmlRequest = new System.Xml.XmlDocument();
        xmlRequest.LoadXml(@"<?xml version=""1.0""?>
     <ShipmentAcceptRequest>
       <Request>
          <TransactionReference>
         <CustomerContext>TR01</CustomerContext>
         <XpciVersion>1.0001</XpciVersion>
          </TransactionReference>
          <RequestAction>ShipAccept</RequestAction>
          <RequestOption>01</RequestOption>
       </Request>
       <ShipmentDigest>" + acceptDigestCode + "</ShipmentDigest></ShipmentAcceptRequest>");

        byte[] bb = new System.Text.ASCIIEncoding().GetBytes(string.Format(XML_CONNECT, sAccessCode.Trim(), sUserId.Trim(), sPassword.Trim()));
        byte[] bResponse = null;
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        ms.Write(bb, 0, bb.Length);
        xmlRequest.Save(ms);
        bb = ms.ToArray();
        xmlRespone = new XmlDocument();
        string serverName = (testMode) ? "wwwcie" : "onlinetools.ups.com";
        serverName = string.Format(UPS_SERVICE_URL, serverName, ShipRequestTypes.ShipAccept);

        using (var client = new NoKeepAlivesWebClient())
        {
        bResponse = client.UploadData(serverName, "POST", bb);
        }

        if (bResponse != null)
        {
        xmlRespone.LoadXml(System.Text.ASCIIEncoding.ASCII.GetString(bResponse));
        }
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show("ShippingAccept " + ex.Message);
        System.Windows.Forms.MessageBox.Show(strXml);
    }
    return new ShippingAcceptResult(xmlRespone);

}

public class NoKeepAlivesWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
        ((HttpWebRequest)request).KeepAlive = false;
        }

        return request;
    }
}

before i did not set KeepAlive = false then also i was getting same error message but now when i set KeepAlive = false then also some time getting the same connection close related error.

tell me the error is specific to any pc?

should i set timeout value for webclient like KeepAlive option?

so please someone drive me to right direction to get rid of this error.

tell me all possible reason for which error is occurring. thanks

Body:
actually these line of code solve my issue

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; //768 for TLS 1.1 and 3072 for TLS 1.2
//ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
//System.Net.ServicePointManager.ServerCertificateValidationCallback += (send, certificate, chain, sslPolicyErrors) => { return true; };
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

few more code snippet i used along with ServicePointManager

using (var client = new NoKeepAlivesWebClient())
{
    bResponse = client.UploadData(serverName, "POST", bb);
}

/// Certificate validation callback.
/// </summary>
private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
    // If the certificate is a valid, signed certificate, return true.
    if (error == System.Net.Security.SslPolicyErrors.None)
    {
    return true;
    }

    Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'",
    cert.Subject,
    error.ToString());

    return false;
}

public class NoKeepAlivesWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
        ((HttpWebRequest)request).KeepAlive = false;
        ((HttpWebRequest)request).Timeout = 60000;
        }

        return request;
    }
}


问:
WordPress domain redirection
Beginner question:
I need to perform a 301 redirect from one Wordpress site (domain), to another Wordpress domain, like this:
From:
http://mycompany.com
To:
http://mycompany.se

A problem is that I have no FTP credentials for my From-site. I can't reach the .htaccess file.

Is there a plugin to use? I have studied the Redirection plugin, but this one seems working on pages within the same domain only(?)

I guess I need to be careful, because if some plugin edits the .htaccess file and something breaks, I can't reach the file...
Thankful for any help!

答:
You can easily find multiple plugins to perform 301 redirection in wordpress,but if you want to edit .htaccess you can install the plugin called "WP htaccess control" https://wordpress.org/plugins/wp-htaccess-control/ .
Through this plugin you can edit the .hraccess file from admin side.
Thanks.</p>

Title: WordPress domain redirection


问:
Javamail, Weblogic, IMAP, SSL and Exchange 2010
first of all, sorry for my english (I'm from Spain)

I'm trying to connect to an Exchange 2010 mail server with IMAP and SSL from Javamail inside a Weblogic 8.1 server.

This is my code

```<code>Properties prop = new Properties();

// IMAP
// Disable TLS
prop.setProperty("mail.imap.starttls.enable", "false");

// Use SSL
prop.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.imap.socketFactory.fallback", "false");

// Use port 993
prop.setProperty("mail.imap.port", "993");
prop.setProperty("mail.imap.socketFactory.port", "993");

prop.setProperty("mail.imaps.class", "com.sun.mail.imap.IMAPSSLStore");

Session session = Session.getDefaultInstance(prop);
session.setDebug(true);
Store store = session.getStore("imap");
store.connect(host, user, password);
</code>```

At this point, I get  javax.mail.AuthenticationFailedException: Command received in Invalid state.
The user parameter is a combination of "domain\user-login\mail-box-alias". I use this because I saw it in this way in a how-to guide.
I already installed a valid SSL certificade in my Weblogic Server.

I don't know where the error is.

With debug I get this:

DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]

OK The Microsoft Exchange IMAP4 service is ready.

A0 CAPABILITY

CAPABILITY IMAP4 IMAP4rev1 LOGINDISABLED STARTTLS CHILDREN IDLE NAMESPACE LITERAL+

A0 OK CAPABILITY completed.

A1 LOGIN "domain\user\mailbox-alias" password

A1 BAD Command received in Invalid state.

ERROR 2: javax.mail.AuthenticationFailedException: Command received in Invalid state.

答:
If you're using port 993, you want imaps instead of imap as your protocol:

```<code>Store store = session.getStore("imaps");
</code>```

On port 143, the connection is plaintext.  You can then optionally start a TLS encryption layer by issuing the STARTTLS IMAP command.  (That's what's controlled by the mail.imap.starttls.enable property.)

On port 993, the initial connection must be an encrypted SSL connection.  This SSL handshake has to be done before any text is sent or received from the server.

ContentLicense: CC BY-SA 2.5

Body:
first of all, sorry for my english (I'm from Spain)

I'm trying to connect to an Exchange 2010 mail server with IMAP and SSL from Javamail inside a Weblogic 8.1 server.

This is my code

Properties prop = new Properties();

// IMAP
// Disable TLS
prop.setProperty("mail.imap.starttls.enable", "false");

// Use SSL
prop.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.imap.socketFactory.fallback", "false");

// Use port 993
prop.setProperty("mail.imap.port", "993");
prop.setProperty("mail.imap.socketFactory.port", "993");

prop.setProperty("mail.imaps.class", "com.sun.mail.imap.IMAPSSLStore");

Session session = Session.getDefaultInstance(prop);
session.setDebug(true);
Store store = session.getStore("imap");
store.connect(host, user, password);

At this point, I get  javax.mail.AuthenticationFailedException: Command received in Invalid state.
The user parameter is a combination of "domain\user-login\mail-box-alias". I use this because I saw it in this way in a how-to guide.
I already installed a valid SSL certificade in my Weblogic Server.

I don't know where the error is.

With debug I get this:

DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]

OK The Microsoft Exchange IMAP4 service is ready.

A0 CAPABILITY

CAPABILITY IMAP4 IMAP4rev1 LOGINDISABLED STARTTLS CHILDREN IDLE NAMESPACE LITERAL+

A0 OK CAPABILITY completed.

A1 LOGIN "domain\user\mailbox-alias" password

A1 BAD Command received in Invalid state.

ERROR 2: javax.mail.AuthenticationFailedException: Command received in Invalid state.

Body:
If you're using port 993, you want imaps instead of imap as your protocol:

Store store = session.getStore("imaps");

On port 143, the connection is plaintext.  You can then optionally start a TLS encryption layer by issuing the STARTTLS IMAP command.  (That's what's controlled by the mail.imap.starttls.enable property.)

On port 993, the initial connection must be an encrypted SSL connection.  This SSL handshake has to be done before any text is sent or received from the server.


问:
how to update the number component in a list of strings
I have a list:

```<code>['a1', 'a2', 'a3']
</code>```

I want to update it so that each number component is incremented by 1:

```<code>['a2', 'a3', 'a4']
</code>```

What would be the most efficient way to do it?

答:
Try the following code,

```<code>import re

lst = ['a1', 'a2', 'a3']
print map(lambda item:(item[0] + str(int(re.search(r'\d+', item).group())+1)), lst)
</code>```

This code finds the integer value in each element of the list using regular expression and increments the integer value and concatenate with corresponding string value.

References:-

Python map function

Python lambda (Anonymous) Function

Python regular expression - search method

Body:
I have a list:

['a1', 'a2', 'a3']

I want to update it so that each number component is incremented by 1:

['a2', 'a3', 'a4']

What would be the most efficient way to do it?

Body:
Try the following code,

import re

lst = ['a1', 'a2', 'a3']
print map(lambda item:(item[0] + str(int(re.search(r'\d+', item).group())+1)), lst)

This code finds the integer value in each element of the list using regular expression and increments the integer value and concatenate with corresponding string value.

References:-

Python map function

Python lambda (Anonymous) Function

Python regular expression - search method


问:
Polylang Wordpress plugin custom string translations not working in expected way
I'm using Polylang plugin on recent website. Posts and pages, also categories translations work perfectly. But I have problem with translations of custom strings.

I am registering string in my functions.php file with:

```<code>pll_register_string('read_more', 'Read More');
</code>```

Then, in my template view I'm trying to get access to it by:

```<code>pll_e('read_more');
</code>```

In response, I'm getting the "read_more"...
The same if I tried to:

```<code>pll_e('Read more');
</code>```

According to function reference of that plugin, it's a proper way. Maybe someone had a similiar problem in the past and can help.

Edit: I've conquer the problem by using Polylang extension for custom string. But, maybe someone can resolve this anyway.

答:
I am not sure if it helps you perfectly but the best approach I am using in this case is to create .po and .mo file for each language, upload it to a website and register it in functions.php or in plugin with this function (you must set path where .po and .mo files will be stored - bellow it's plugin path but you can change it to whatever you want and also you can change "my-theme" tag to your own):

```<code>// Adding language files
function theme_setup_hook () {
 load_theme_textdomain('my-theme', plugin_dir_path(__FILE__).'/languages');
}
add_action( 'after_setup_theme', 'theme_setup_hook' );
</code>```

In .po file using Poedit (lightweight open source app which can be downloaded here https://poedit.net/) you just set the language of the file in Properties and select the folder on your disc where files with code with strings to translate are written. Also you must set Keywords in properties where I put these: __ and _e.

In the template's code you then write all strings which needs to be translated like this:

for simple echo:

```<code><?php _e('string to translate','my-theme'); ?>
</code>```

for using in scripts:

```<code><?php
 $string = __('string to translate','my-theme');
 echo $string;
?>
</code>```

After that just Update the po file in Poedit and since you have set proper path all strings are updated here and you can all translate them. Then save the file. Poedit automatically create also .mo file so upload both of files (po and mo) back to server and that's it.
For each language you can do that with separate file which is named like en_GB.po etc.

I hope it helps.

Body:
I'm using Polylang plugin on recent website. Posts and pages, also categories translations work perfectly. But I have problem with translations of custom strings.

I am registering string in my functions.php file with:

pll_register_string('read_more', 'Read More');

Then, in my template view I'm trying to get access to it by:

pll_e('read_more');

In response, I'm getting the "read_more"...
The same if I tried to:

pll_e('Read more');

According to function reference of that plugin, it's a proper way. Maybe someone had a similiar problem in the past and can help.

Edit: I've conquer the problem by using Polylang extension for custom string. But, maybe someone can resolve this anyway.

Body:
I am not sure if it helps you perfectly but the best approach I am using in this case is to create .po and .mo file for each language, upload it to a website and register it in functions.php or in plugin with this function (you must set path where .po and .mo files will be stored - bellow it's plugin path but you can change it to whatever you want and also you can change "my-theme" tag to your own):

// Adding language files
function theme_setup_hook () {
 load_theme_textdomain('my-theme', plugin_dir_path(__FILE__).'/languages');
}
add_action( 'after_setup_theme', 'theme_setup_hook' );

In .po file using Poedit (lightweight open source app which can be downloaded here https://poedit.net/) you just set the language of the file in Properties and select the folder on your disc where files with code with strings to translate are written. Also you must set Keywords in properties where I put these: __ and _e.

In the template's code you then write all strings which needs to be translated like this:

for simple echo:

<?php _e('string to translate','my-theme'); ?>

for using in scripts:

<?php
 $string = __('string to translate','my-theme');
 echo $string;
?>

After that just Update the po file in Poedit and since you have set proper path all strings are updated here and you can all translate them. Then save the file. Poedit automatically create also .mo file so upload both of files (po and mo) back to server and that's it.
For each language you can do that with separate file which is named like en_GB.po etc.

I hope it helps.


问:
Error in manifest - All com.android.support libraries must use the exact same version specification
I am getting "All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.0.1, 25.3.1. Examples include com.android.support:animated-vector-drawable:27.0.1 and com.android.support:customtabs:25.3.1" error in Android manifest.

Earlier I used a version like " compile 'com.android.support:appcompat-v7:27+'" then i modified as per suggestion from android studio. But still I am getting the same error. Please help.

```<code>apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
    applicationId "com.app"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.android.support:appcompat-v7:27.0.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:cardview-v7:27.0.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'info.hoang8f:android-segmented:1.0.6'
compile 'com.android.volley:volley:1.0.0'
compile 'com.android.support:design:27.0.1'
compile 'de.hdodenhof:circleimageview:2.1.0'
testCompile 'junit:junit:4.12'
</code>```

}

答:
One of your third-party libraries may using support library version  25.3.1.
Try changing your support library version to  25.3.1 and sync your project.</p>

Body:
I am getting "All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.0.1, 25.3.1. Examples include com.android.support:animated-vector-drawable:27.0.1 and com.android.support:customtabs:25.3.1" error in Android manifest.

Earlier I used a version like " compile 'com.android.support:appcompat-v7:27+'" then i modified as per suggestion from android studio. But still I am getting the same error. Please help.

apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
    applicationId "com.app"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.android.support:appcompat-v7:27.0.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:cardview-v7:27.0.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'info.hoang8f:android-segmented:1.0.6'
compile 'com.android.volley:volley:1.0.0'
compile 'com.android.support:design:27.0.1'
compile 'de.hdodenhof:circleimageview:2.1.0'
testCompile 'junit:junit:4.12'

}


问:
Bootstrap 3 dropdown select
We are trying re-implement our sign-up form with bootstrap. Our sign up form contains a drop-down list which represents a company type. I have searched extensively online but I do not see any example where a form input would be a drop down.

Bootstrap gives a ton of examples of drop-downs related to various action but what I need is a drop down input. I have come up with two solutions:

First:

```<code><label>Type of Business</label>
<select class="form-control">
    <option>small</option>
    <option>medium</option>
    <option>large</option>
</select>
</code>```

There is a problem here: although the box itself is styled correctly the drop-down itself has no styles applied.

Second version:

```<code><div class="btn-group">
    <button type="button" class="form-control btn btn-default dropdown-toggle" data-toggle="dropdown">
        Select Business type <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu">
        <li><a href="#">small</a></li>
        <li><a href="#">medium</a></li>
        <li><a href="#">large</a></li>
    </ul>
</div>
</code>```

This one looks nice:

but it's a button. When an option is selected, I do not want to perform any action all I want is to change text and bind the selection with a corresponding input field.

Both of these approaches seams to be a wrong choice for my action. I refuse to believe that Bootstrap does not contain a simple drop-down single select component bound to an input field.

What am I missing ? Please help.

答:
Try this:   </p>

```<code><div class="form-group">
     <label class="control-label" for="Company">Company</label>
     <select id="Company" class="form-control" name="Company">
         <option value="small">small</option>
         <option value="medium">medium</option>
         <option value="large">large</option>
     </select>
 </div>
</code>```

Title: Bootstrap 3 dropdown select

Body:
We are trying re-implement our sign-up form with bootstrap. Our sign up form contains a drop-down list which represents a company type. I have searched extensively online but I do not see any example where a form input would be a drop down.

Bootstrap gives a ton of examples of drop-downs related to various action but what I need is a drop down input. I have come up with two solutions:

First:

Type of Business
<select class="form-control">
    <option>small</option>
    <option>medium</option>
    <option>large</option>
</select>

There is a problem here: although the box itself is styled correctly the drop-down itself has no styles applied.

Second version:

    <button type="button" class="form-control btn btn-default dropdown-toggle" data-toggle="dropdown">
        Select Business type
    </button>

small

medium

large

This one looks nice:

but it's a button. When an option is selected, I do not want to perform any action all I want is to change text and bind the selection with a corresponding input field.

Both of these approaches seams to be a wrong choice for my action. I refuse to believe that Bootstrap does not contain a simple drop-down single select component bound to an input field.

What am I missing ? Please help.

Body:
Try this:

<div class="form-group">
     <label class="control-label" for="Company">Company</label>
     <select id="Company" class="form-control" name="Company">
         <option value="small">small</option>
         <option value="medium">medium</option>
         <option value="large">large</option>
     </select>
 </div>


问:
Linked HTML 5 video from sub-domain not playing in browser
I have a web app with my media files being uploaded to a sub-domain. The images are displaying well but NOT so for videos across all browsers, the files is not linked to the site and it shows MIME type not supported. Everything works well on localhost.

The video file URL is correct and can be downloaded from the browser, I have copied the video file to the main domain and it worked but trying to load it from the sub-domain is not going well at all.

Please what may be the cause of this and how can i overcome it? I am using ASP.NET MVC 5, IIS 8.0, MIME types are set.

答: I finally got it working. I had set MIME types from my main domain but it still needed to be set on the sub-domain as well. After days of battling I just got it by trial.


问:
What sig2ext in Matlab?
What is sig2ext.m file in Matlab? If I want to use the function, should I install any specific toolbox.
Basically, I am trying to do a rainflow counting.</p>

答:
It looks like the function is part of this package:

https://mathworks.com/matlabcentral/fileexchange/3026-rainflow-counting-algorithm?focused=5148893&tab=function

If you want to use that function, all you have to do is to download the package, change your current Matlab working directory to the folder in which you unzipped the package, and create a new script in which you invoke it.

Alternatively, you can just copy and paste the function code into a new script file you previouslty created:

```<code>function [ext, exttime] = sig2ext(sig, dt, clsn)
% SIG2EXT - search for local extrema in the time history (signal),
%
% function [ext, exttime] = sig2ext(sig, dt, clsn)
%
% SYNTAX
%   sig2ext(sig)
%   [ext]=sig2ext(sig)
%   [ext,exttime]=sig2ext(sig)
%   [ext,exttime]=sig2ext(sig, dt)
%   [ext,exttime]=sig2ext(sig, dt, clsn)
%
% OUTPUT
%   EXT     - found extrema (turning points of the min and max type)
%             in time history SIG,
%   EXTTIME - option, time of extremum occurrence counted from
%             sampling time DT (in seconds) or time vector DT.
%             If no sampling time present, DT = 1 is assumed.
%
% INPUT
%   SIG     - required, time history of loading,
%   DT      - option, descripion as above, scalar or vector of
%             the same length as SIG,
%   CLSN    - option, a number of classes of SIG (division is performed
%             before searching of extrema), no CLSN means no division
%             into classes.
%
% The function caused without an output draws a course graph with
% the searched extrema.
%

% By Adam Niesony
% Revised, 10-Nov-2009
% Visit the MATLAB Central File Exchange for latest version

error(nargchk(1,3,nargin))

% Is the time analysed?
TimeAnalize=(nargout==0)|(nargout==2);

% Sprawdzam czy przyrost dt jest podany prawidowo
if nargin==1,
    dt=1;
else
    dt=dt(:);
end

% Zamieniam dane sig na jedn kolumn
sig=sig(:);

% Dzielimy na klasy jeeli jest podane CLSN
if nargin==3,
    if nargout==0,
        oldsig=sig;
    end
    clsn=round(clsn);
    smax=max(sig);
    smin=min(sig);
    sig=clsn*((sig-smin)./(smax-smin));
    sig=fix(sig);
    sig(sig==clsn)=clsn-1;
    sig=(smax-smin)/(clsn-1)*sig+smin;
end

% Tworz wektor binarny w gdzie 1 oznacza ekstremum lub rwno,
% Uznaj e pierwszy i ostatni punkt to ekstremum
w1=diff(sig);
w=logical([1;(w1(1:end-1).*w1(2:end))<=0;1]);
ext=sig(w);
if TimeAnalize,
    if length(dt)==1,
        exttime=(find(w==1)-1).*dt;
    else
        exttime=dt(w);
    end
end

% Usuwam potrjne wartoci
w1=diff(ext);
w=~logical([0; w1(1:end-1)==0 & w1(2:end)==0; 0]);
ext=ext(w);
if TimeAnalize,
    exttime=exttime(w);
end

% Usuwam podwjne wartoci i przesuwam czas na rodek
w=~logical([0; ext(1:end-1)==ext(2:end)]);
ext=ext(w);
if TimeAnalize,
    w1=(exttime(2:end)-exttime(1:end-1))./2;
    exttime=[exttime(1:end-1)+w1.*~w(2:end); exttime(end)];
    exttime=exttime(w);
end

% Jeszcze raz sprawdzam ekstrema
if length(ext)>2,  % warunek: w tym momencie moe ju by mao punktw
    w1=diff(ext);
    w=logical([1; w1(1:end-1).*w1(2:end)<0; 1]);
    ext=ext(w);
    if TimeAnalize,
        exttime=exttime(w);
    end
end

if nargout==0,
    if length(dt)==1,
        dt=(0:length(sig)-1).*dt;
    end
    if nargin==3,
        plot(dt,oldsig,'b-',dt,sig,'g-',exttime,ext,'ro')
        legend('signal','singal divided in classes','extrema')
    else
        plot(dt,sig,'b-',exttime,ext,'ro')
        legend('signal','extrema')
    end
    xlabel('time')
    ylabel('signal & extrema')
    clear ext exttime
end
</code>```

Title: What sig2ext in Matlab?

Body:
It looks like the function is part of this package:

https://mathworks.com/matlabcentral/fileexchange/3026-rainflow-counting-algorithm?focused=5148893&tab=function

If you want to use that function, all you have to do is to download the package, change your current Matlab working directory to the folder in which you unzipped the package, and create a new script in which you invoke it.

Alternatively, you can just copy and paste the function code into a new script file you previouslty created:

function [ext, exttime] = sig2ext(sig, dt, clsn)
% SIG2EXT - search for local extrema in the time history (signal),
%
% function [ext, exttime] = sig2ext(sig, dt, clsn)
%
% SYNTAX
%   sig2ext(sig)
%   [ext]=sig2ext(sig)
%   [ext,exttime]=sig2ext(sig)
%   [ext,exttime]=sig2ext(sig, dt)
%   [ext,exttime]=sig2ext(sig, dt, clsn)
%
% OUTPUT
%   EXT     - found extrema (turning points of the min and max type)
%             in time history SIG,
%   EXTTIME - option, time of extremum occurrence counted from
%             sampling time DT (in seconds) or time vector DT.
%             If no sampling time present, DT = 1 is assumed.
%
% INPUT
%   SIG     - required, time history of loading,
%   DT      - option, descripion as above, scalar or vector of
%             the same length as SIG,
%   CLSN    - option, a number of classes of SIG (division is performed
%             before searching of extrema), no CLSN means no division
%             into classes.
%
% The function caused without an output draws a course graph with
% the searched extrema.
%

% By Adam Niesony
% Revised, 10-Nov-2009
% Visit the MATLAB Central File Exchange for latest version

error(nargchk(1,3,nargin))

% Is the time analysed?
TimeAnalize=(nargout==0)|(nargout==2);

% Sprawdzam czy przyrost dt jest podany prawidowo
if nargin==1,
    dt=1;
else
    dt=dt(:);
end

% Zamieniam dane sig na jedn kolumn
sig=sig(:);

% Dzielimy na klasy jeeli jest podane CLSN
if nargin==3,
    if nargout==0,
        oldsig=sig;
    end
    clsn=round(clsn);
    smax=max(sig);
    smin=min(sig);
    sig=clsn*((sig-smin)./(smax-smin));
    sig=fix(sig);
    sig(sig==clsn)=clsn-1;
    sig=(smax-smin)/(clsn-1)*sig+smin;
end

% Tworz wektor binarny w gdzie 1 oznacza ekstremum lub rwno,
% Uznaj e pierwszy i ostatni punkt to ekstremum
w1=diff(sig);
w=logical([1;(w1(1:end-1).*w1(2:end))<=0;1]);
ext=sig(w);
if TimeAnalize,
    if length(dt)==1,
        exttime=(find(w==1)-1).*dt;
    else
        exttime=dt(w);
    end
end

% Usuwam potrjne wartoci
w1=diff(ext);
w=~logical([0; w1(1:end-1)==0 & w1(2:end)==0; 0]);
ext=ext(w);
if TimeAnalize,
    exttime=exttime(w);
end

% Usuwam podwjne wartoci i przesuwam czas na rodek
w=~logical([0; ext(1:end-1)==ext(2:end)]);
ext=ext(w);
if TimeAnalize,
    w1=(exttime(2:end)-exttime(1:end-1))./2;
    exttime=[exttime(1:end-1)+w1.*~w(2:end); exttime(end)];
    exttime=exttime(w);
end

% Jeszcze raz sprawdzam ekstrema
if length(ext)>2,  % warunek: w tym momencie moe ju by mao punktw
    w1=diff(ext);
    w=logical([1; w1(1:end-1).*w1(2:end)<0; 1]);
    ext=ext(w);
    if TimeAnalize,
        exttime=exttime(w);
    end
end

if nargout==0,
    if length(dt)==1,
        dt=(0:length(sig)-1).*dt;
    end
    if nargin==3,
        plot(dt,oldsig,'b-',dt,sig,'g-',exttime,ext,'ro')
        legend('signal','singal divided in classes','extrema')
    else
        plot(dt,sig,'b-',exttime,ext,'ro')
        legend('signal','extrema')
    end
    xlabel('time')
    ylabel('signal & extrema')
    clear ext exttime
end


问:
How to read and parse xml file present in azure data lake store using .NET?
I have few xml files in azure data lake store. i want to fetch those files from azure data lake and parse it.
How can i do that?</p>

答:
You can use Azure Data Lake Store .NET SDK. Following tutorial walks you through on performing various file operations on files stored on Data Lake Store.

https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-data-operations-net-sdk


问:
Validate that exposed primary/foreign keys in a form are intact
I have a Survey form. Every question has 3-4 pre-defined answers as radio buttons. The value of a radio button is the primary key of the answer in the database.

As all answers to all questions are stored in one table, if a user increments the value, the ID may still be a valid foreign key, but it does not belong to that question.

What's the best practice to be sure the value of the radio button is not manipulated?

答:
be sure the value of radiobutton is not manipulated

You can't, and that's the wrong approach.  Always assume that client-side information can be manipulated.

Instead, validate the business logic of the request being made to the server.  When your server-side code receives a submitted set of questions and answers, verify against the data you have that the data being submitted is valid.

This could be done by querying your database first, performing your validation logic, and then saving the data.  It could be done by creating a stored procedure or some other database-side logic to ensure valid data and then you only interact with the database once.  Etc.  Either way, it's up to you to define and validate the business rules set forth in your system.


问:
TortoiseSVN Switch errors
I'm trying to switch an existing trunk check out to a specific branch, I get this error:

```<code>Can't move
'C:\Work\project123\include\.svn\tmp\all-wcprops'
to
'C:\Work\project123\include\.svn\all-wcprops':
The file or directory is corrupted and unreadable.
</code>```

I've run cleanup but no change.

答:
If you don't have any local modifications, just delete C:\Work\project123\include, update to get a fresh copy and then switch again.  Please backup first!

Update: One of the reasons could be that the files in C:\Work\project123\include\.svn\tmp got locked by an antivirus or some indexing service.  To find out which process has handles to these files you can use Process Explorer's search function.

Title: TortoiseSVN Switch errors

Body:
I'm trying to switch an existing trunk check out to a specific branch, I get this error:

Can't move
'C:\Work\project123\include\.svn\tmp\all-wcprops'
to
'C:\Work\project123\include\.svn\all-wcprops':
The file or directory is corrupted and unreadable.

I've run cleanup but no change.


问:
Exception when using Shell32 to get File extended properties
I am trying to use Shell32 to get extended file properties in c#.

My code for this is as follows.

```<code>        var file = FileUpload1.PostedFile;

        List<string> arrHeaders = new List<string>();

        Shell shell = new ShellClass();

        //Exception is thrown at next line
        Folder rFolder = shell.NameSpace(Path.GetDirectoryName(file.FileName));
        FolderItem rFiles = rFolder.ParseName(Path.GetFileName(file.FileName));

        for (int i = 0; i < short.MaxValue; i++)
        {
            string value = rFolder.GetDetailsOf(rFiles, i).Trim();
            arrHeaders.Add(value);
        }
</code>```

I am getting exception as follows.

Message - Unable to cast COM object of type 'Shell32.ShellClass' to interface type 'Shell32.IShellDispatch6'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{286E6F1B-7113-4355-9562-96B7E9D64C54}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

Stack Trace -    at System.StubHelpers.StubHelpers.GetCOMIPFromRCW(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget, Boolean& pfNeedsRelease)
   at Shell32.ShellClass.NameSpace(Object vDir)
   at PBSWebApplication.Test.Button1_OnClick(Object sender, EventArgs e) in c:\Projects\PBSWebApplication\PBSWebApplication\PBSWebApplication\Test.aspx.cs:line 33
   at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
   at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

How to fix this?

Thanks.

答:
I had simliar issue and the answer from jeronevw on this forum fixed it for me:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/b25e2b8f-141a-4a1c-a73c-1cb92f953b2b/instantiate-shell32shell-object-in-windows-8?forum=clr </p>

```<code>public Shell32.Folder GetShell32NameSpaceFolder(Object folder)
{
  Type shellAppType = Type.GetTypeFromProgID("Shell.Application");

  Object shell = Activator.CreateInstance(shellAppType);
  return (Shell32.Folder)shellAppType.InvokeMember("NameSpace",
System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { folder });
}
</code>```

<p>All credits for jeronevw </p>

Body:
I am trying to use Shell32 to get extended file properties in c#.

My code for this is as follows.

        var file = FileUpload1.PostedFile;

        List<string> arrHeaders = new List<string>();

        Shell shell = new ShellClass();

        //Exception is thrown at next line
        Folder rFolder = shell.NameSpace(Path.GetDirectoryName(file.FileName));
        FolderItem rFiles = rFolder.ParseName(Path.GetFileName(file.FileName));

        for (int i = 0; i < short.MaxValue; i++)
        {
            string value = rFolder.GetDetailsOf(rFiles, i).Trim();
            arrHeaders.Add(value);
        }

I am getting exception as follows.

Message - Unable to cast COM object of type 'Shell32.ShellClass' to interface type 'Shell32.IShellDispatch6'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{286E6F1B-7113-4355-9562-96B7E9D64C54}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

Stack Trace -    at System.StubHelpers.StubHelpers.GetCOMIPFromRCW(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget, Boolean& pfNeedsRelease)
   at Shell32.ShellClass.NameSpace(Object vDir)
   at PBSWebApplication.Test.Button1_OnClick(Object sender, EventArgs e) in c:\Projects\PBSWebApplication\PBSWebApplication\PBSWebApplication\Test.aspx.cs:line 33
   at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
   at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

How to fix this?

Thanks.

Body:
I had simliar issue and the answer from jeronevw on this forum fixed it for me:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/b25e2b8f-141a-4a1c-a73c-1cb92f953b2b/instantiate-shell32shell-object-in-windows-8?forum=clr

public Shell32.Folder GetShell32NameSpaceFolder(Object folder)
{
  Type shellAppType = Type.GetTypeFromProgID("Shell.Application");

  Object shell = Activator.CreateInstance(shellAppType);
  return (Shell32.Folder)shellAppType.InvokeMember("NameSpace",
System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { folder });
}

All credits for jeronevw


问:
How to feed CNN output as input series in a RNN (using Tensorflow)
I have implemented a simple CNN using tensorflow. Up until now I used to put a fully connected layer of size 2 at the last convolutional layer to distinct between my 2 classes.
Now I want to feed that last convolutional layer to an RNN and then perform the classification.

The output of the last convolutional layer is called "cnn_output" and is a tensor of that form

<tf.Tensor 'Sigmoid_1:0' shape=(?, 168, 32) dtype=float32>

before feeding it to the rnn I split it using this command:

input_series = tf.split(axis=2, num_or_size_splits= 32, value = cnn_output)

the result of the split is 32 tensor of that type:

<tf.Tensor 'split:0' shape=(?, 168, 1) dtype=float32>

the variables for the rnn are defined as below:

cell = tf.contrib.rnn.BasesLSTMCell(32, state_is_tuple=True)

cell_state = tf.placeholder(tf.float32, [168,32])

hidden_state = tf.placeholder(tf.float32, [168,32])

init_state = tf.contrib.rnn.LSTMStateTuple( cell_state, hidden_state)

to feed the output of the cnn to the rnn I use this command

states_series, current_state = tf.nn.static_rnn(cell, input_series, init_state)

At this line I get the following error

ValueError: linear is expecting 2D arguments: [TensorShape([Dimension(None), Dimension(168), Dimension(1)]), TensorShape([Dimension(168), Dimension(32)])]

To me it seems that there is something wrong with that first unknown dimension of the tensors but I am not sure how to deal with it.

I tried change the shape of the cell_state and hidden_state to [None,168,32] but didn't seem to help.

I also tried to use the dynamic_rnn (not sure about the difference with static_rnn) but didn't work either

EDIT UPDATE:
I manage to run the code without error by reshaping the input_series of the rnn with this command:

```<code>input_series = [tf.reshape(ipt,[-1,168 ])for ipt in input_series]
</code>```

which resulted in tensors like this

```<code><tf.Tensor 'Reshape_21:0' shape=(?, 168) dtype=float32>
</code>```

Although I am not sure yet if the rnn unit works properly. I will check it out and update

答:
I think your error comes from the fact that your placeholders are 2D and not 3D. You forgot to add a batch dimension.

Try to define them like this:

```<code>cell_state = tf.placeholder(tf.float32, [None,168,32])
hidden_state = tf.placeholder(tf.float32, [None,168,32])
</code>```

(You might have to change the 32 to 1, given that your inputs have 1 channel each)

Body:
I have implemented a simple CNN using tensorflow. Up until now I used to put a fully connected layer of size 2 at the last convolutional layer to distinct between my 2 classes.
Now I want to feed that last convolutional layer to an RNN and then perform the classification.

The output of the last convolutional layer is called "cnn_output" and is a tensor of that form

<tf.Tensor 'Sigmoid_1:0' shape=(?, 168, 32) dtype=float32>

before feeding it to the rnn I split it using this command:

input_series = tf.split(axis=2, num_or_size_splits= 32, value = cnn_output)

the result of the split is 32 tensor of that type:

<tf.Tensor 'split:0' shape=(?, 168, 1) dtype=float32>

the variables for the rnn are defined as below:

cell = tf.contrib.rnn.BasesLSTMCell(32, state_is_tuple=True)

cell_state = tf.placeholder(tf.float32, [168,32])

hidden_state = tf.placeholder(tf.float32, [168,32])

init_state = tf.contrib.rnn.LSTMStateTuple( cell_state, hidden_state)

to feed the output of the cnn to the rnn I use this command

states_series, current_state = tf.nn.static_rnn(cell, input_series, init_state)

At this line I get the following error

ValueError: linear is expecting 2D arguments: [TensorShape([Dimension(None), Dimension(168), Dimension(1)]), TensorShape([Dimension(168), Dimension(32)])]

To me it seems that there is something wrong with that first unknown dimension of the tensors but I am not sure how to deal with it.

I tried change the shape of the cell_state and hidden_state to [None,168,32] but didn't seem to help.

I also tried to use the dynamic_rnn (not sure about the difference with static_rnn) but didn't work either

EDIT UPDATE:
I manage to run the code without error by reshaping the input_series of the rnn with this command:

input_series = [tf.reshape(ipt,[-1,168 ])for ipt in input_series]

which resulted in tensors like this

<tf.Tensor 'Reshape_21:0' shape=(?, 168) dtype=float32>

Although I am not sure yet if the rnn unit works properly. I will check it out and update

Body:
I think your error comes from the fact that your placeholders are 2D and not 3D. You forgot to add a batch dimension.

Try to define them like this:

cell_state = tf.placeholder(tf.float32, [None,168,32])
hidden_state = tf.placeholder(tf.float32, [None,168,32])

(You might have to change the 32 to 1, given that your inputs have 1 channel each)


问:
Jmeter throughput controller actions run per iteration
I have the following scenario.

```<code>HTTP Cookie Manager - clear cookies after each iteration
Login http action -> 30%
Show profile (the user must be logged in) -> 20%
Purchase (the user must be logged in) -> 50%
</code>```

The problem is, in presence of throughput controller there is no guarantee that per iteration the user will be logged in before any other action that requires the user to be logged in, so after any iteration the cookies will be cleared which means the session will be invalidated, there is a probability the the action will fail since no user logged in.

Taking into account the clear the cookies is a need.

If there is a way like per each iteration the login will be triggered once and the other actions will be repeated to target the throughput controller.
Is there any idea that is suitable for my scenario using jmeter?

答:
Your scenario does not make a lot of sense as given the user needs to be logged in in order to perform Show profile and/or  Purchase tasks you should perform login for 100% of users before viewing the profile or making the purchase. So I would recommend moving your Login http action outside the Throughput Controller like:

Login http action

Show profile

Throughput Controller

Purchase

Throughput Controller

Another option will be using Switch Controller, this way you will get confidence that each child test element will be executed at least once. Check out Running JMeter Samplers with Defined Percentage Probability article for more details.

Body:
I have the following scenario.

HTTP Cookie Manager - clear cookies after each iteration
Login http action -> 30%
Show profile (the user must be logged in) -> 20%
Purchase (the user must be logged in) -> 50%

The problem is, in presence of throughput controller there is no guarantee that per iteration the user will be logged in before any other action that requires the user to be logged in, so after any iteration the cookies will be cleared which means the session will be invalidated, there is a probability the the action will fail since no user logged in.

Taking into account the clear the cookies is a need.

If there is a way like per each iteration the login will be triggered once and the other actions will be repeated to target the throughput controller.
Is there any idea that is suitable for my scenario using jmeter?


问:
Test - FirebaseApp is not initialized in this process
I'm trying to run a test with Robolectric and it has an integration with Firebase. I have a project MyProject - Test that I'll be using to run the tests in a real instance of the database.

The problem is that, when running cleanup before test, I have the error:

```<code>java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process null. Make sure to call FirebaseApp.initializeApp(Context) first.

at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
at com.cgbros.silkhub.activity.listener.LoginActivityUnitTest.cleanUp(LoginActivityUnitTest.kt:26) <28 internal calls>
</code>```

The test file:
https://gist.github.com/augustoerico/e88d3e5b59ae5d023d83c114b8ffa708
(I tried to copy-paste the source here. Failed miserably...)

Any insights on how I can make this work?

Thank you!

答:
I also had the same issue a few day ago and i solve it in the same way the error says. You get that error because you're trying to get an instance of Firebase without initialize it. Please add this line of code before you try to get an instance of Firebase like this:

```<code>FirebaseApp.initializeApp(this);
</code>```

Also, as Franks says, please be sure you have the following line of code added in your build.gradle file, as the last line of your entire file.

```<code>apply plugin: 'com.google.gms.google-services'
</code>```

Body:
I'm trying to run a test with Robolectric and it has an integration with Firebase. I have a project MyProject - Test that I'll be using to run the tests in a real instance of the database.

The problem is that, when running cleanup before test, I have the error:

java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process null. Make sure to call FirebaseApp.initializeApp(Context) first.

at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
at com.cgbros.silkhub.activity.listener.LoginActivityUnitTest.cleanUp(LoginActivityUnitTest.kt:26) <28 internal calls>

The test file:
https://gist.github.com/augustoerico/e88d3e5b59ae5d023d83c114b8ffa708
(I tried to copy-paste the source here. Failed miserably...)

Any insights on how I can make this work?

Thank you!

Body:
I also had the same issue a few day ago and i solve it in the same way the error says. You get that error because you're trying to get an instance of Firebase without initialize it. Please add this line of code before you try to get an instance of Firebase like this:

FirebaseApp.initializeApp(this);

Also, as Franks says, please be sure you have the following line of code added in your build.gradle file, as the last line of your entire file.

apply plugin: 'com.google.gms.google-services'


问:
Elements in common for each two elements in first column dataframes
I'm new with Pandas. I have the following dataframe.

Group           type

    G1          a1
    G1          a2
    G1          a3
    G2          a2
    G2          a1
    G3          a1
    G4          a1
    G5          a4
    G5          a1```
</div>
</div>
</p>

<p>And I would like to obtain for each couple of groups how many "types" they have in common. Something like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Group           type  count

    G1          a1
    G1          a2
    G1          a3
    G2          a2
    G2          a1
    G3          a1
    G4          a1
    G5          a4
    G5          a1

count: (G1, G2, 2) (Elements in common: a1,a2)
count: (G1, G3, 1) (Elements in common: a1)
count: (G1, G4, 1) (Elements in common: a1)
...</code>```

Do you have any idea how could I implement this? Is there any function from the pandas library that could guide me into the right direction.

答:
Given a dataframe:

```<code>import pandas as pd
df = pd.DataFrame([['G1', 'G1', 'G2', 'G2'], ['a1', 'a2', 'a1', 'a3']]).T
df.columns = ['group', 'type']
</code>```

Then there are two options:

```<code>df.groupby('type').count()
</code>```

or if you want to know them explicitly:

```<code>df.groupby(['type', 'group']).count()
</code>```

Thus you can do, e.g.:

```<code>df1.loc['a1']
</code>```

with output:

```<code>group
G1
G2
</code>```

Body:
I'm new with Pandas. I have the following dataframe.

Group           type

    G1          a1
    G1          a2
    G1          a3
    G2          a2
    G2          a1
    G3          a1
    G4          a1
    G5          a4
    G5          a1

And I would like to obtain for each couple of groups how many "types" they have in common. Something like this:

Group           type  count

    G1          a1
    G1          a2
    G1          a3
    G2          a2
    G2          a1
    G3          a1
    G4          a1
    G5          a4
    G5          a1

count: (G1, G2, 2) (Elements in common: a1,a2)
count: (G1, G3, 1) (Elements in common: a1)
count: (G1, G4, 1) (Elements in common: a1)
...

Do you have any idea how could I implement this? Is there any function from the pandas library that could guide me into the right direction.

Body:
Given a dataframe:

import pandas as pd
df = pd.DataFrame([['G1', 'G1', 'G2', 'G2'], ['a1', 'a2', 'a1', 'a3']]).T
df.columns = ['group', 'type']

Then there are two options:

df.groupby('type').count()

or if you want to know them explicitly:

df.groupby(['type', 'group']).count()

Thus you can do, e.g.:

df1.loc['a1']

with output:

group
G1
G2


问:
CSS3 Background Gradient Overlay HTML5 Video
I want to apply a CSS3 gradient overlay to a video. I have a feeling this could be to do with z-indexing / stack orders so here is my code.

Div structure:

```<code><div class="wrapper">
    <div class="gradient">
        <video></video>
    </div>
</div>
</code>```

The CSS I'm using is a background-image radial gradient:

```<code>.gradient {
        background-image:
        radial-gradient(
            circle at 36% 48%, #000000,
            rgba(11, 39, 65, 0.32) 87%,
            rgba(0, 0, 0, 0.0)
        );
    }
</code>```

The styling is applied to the gradient div along with position: relative; and z-index: 10; to make the gradient overlay the video.

The gradient doesn't appear at all - how is this achievable?

答:
2022 update

We can use the pseudo-element ::after to display a gradient over the whole image without unnecessary HTML markup. I've also chosen to use the aspect-ratio property to size the video but feel free to use any technique you like.

.wrapper {
  position: relative;
  width: 100%;
}

.wrapper::after {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  content: '';
  background-image: radial-gradient(
    circle at 36% 48%,
    #000000,
    rgba(11, 39, 65, 0.32) 87%,
    rgba(0, 0, 0, 0)
  );
}

video {
  width: 100%;
  aspect-ratio: 4/3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <video>
    <source
      src="https://upload.wikimedia.org/wikipedia/commons/8/8c/Dancing-for-Food-in-the-Deep-Sea-Bacterial-Farming-by-a-New-Species-of-Yeti-Crab-pone.0026243.s002.ogv"
      type="video/webm"
    />
  </video>
</div></code>```

Historical answer

You must set width and height to the div containing the gradient in order to be displayed. Then, use z-index to put the div on top of the video

You can do it that way :

.wrapper {
  position: absolute;
  width: 100%;
}

.gradient {
  background-image: radial-gradient(
    circle at 36% 48%,
    #000000,
    rgba(11, 39, 65, 0.32) 87%,
    rgba(0, 0, 0, 0)
  );
  width: 100%;
  height: calc(100vh - 80px);
  min-height: 600px;
  object-fit: cover;
  position: relative;
  z-index: 2;
}

video {
  position: absolute;
  top: 0;
  z-index: -1;
  width: 100%;
  height: calc(100vh - 80px);
  min-height: 600px;
  object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="gradient"></div>
  <video>
    <source
      src="https://upload.wikimedia.org/wikipedia/commons/8/8c/Dancing-for-Food-in-the-Deep-Sea-Bacterial-Farming-by-a-New-Species-of-Yeti-Crab-pone.0026243.s002.ogv"
      type="video/webm"
    />
  </video>
</div></code>```

Notice that I've pulled the video element out of the gradient div, so it can be displayed on top of it.

Hope it'll help.

Body:
I want to apply a CSS3 gradient overlay to a video. I have a feeling this could be to do with z-indexing / stack orders so here is my code.

Div structure:

        <video></video>

The CSS I'm using is a background-image radial gradient:

.gradient {
        background-image:
        radial-gradient(
            circle at 36% 48%, #000000,
            rgba(11, 39, 65, 0.32) 87%,
            rgba(0, 0, 0, 0.0)
        );
    }

The styling is applied to the gradient div along with position: relative; and z-index: 10; to make the gradient overlay the video.

The gradient doesn't appear at all - how is this achievable?

Body:
2022 update

We can use the pseudo-element ::after to display a gradient over the whole image without unnecessary HTML markup. I've also chosen to use the aspect-ratio property to size the video but feel free to use any technique you like.

.wrapper {
  position: relative;
  width: 100%;
}

.wrapper::after {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  content: '';
  background-image: radial-gradient(
    circle at 36% 48%,
    #000000,
    rgba(11, 39, 65, 0.32) 87%,
    rgba(0, 0, 0, 0)
  );
}

video {
  width: 100%;
  aspect-ratio: 4/3;
}

<div class="wrapper">
  <video>
    <source
      src="https://upload.wikimedia.org/wikipedia/commons/8/8c/Dancing-for-Food-in-the-Deep-Sea-Bacterial-Farming-by-a-New-Species-of-Yeti-Crab-pone.0026243.s002.ogv"
      type="video/webm"
    />
  </video>
</div>

Historical answer

You must set width and height to the div containing the gradient in order to be displayed. Then, use z-index to put the div on top of the video

You can do it that way :

.wrapper {
  position: absolute;
  width: 100%;
}

.gradient {
  background-image: radial-gradient(
    circle at 36% 48%,
    #000000,
    rgba(11, 39, 65, 0.32) 87%,
    rgba(0, 0, 0, 0)
  );
  width: 100%;
  height: calc(100vh - 80px);
  min-height: 600px;
  object-fit: cover;
  position: relative;
  z-index: 2;
}

video {
  position: absolute;
  top: 0;
  z-index: -1;
  width: 100%;
  height: calc(100vh - 80px);
  min-height: 600px;
  object-fit: cover;
}

<div class="wrapper">
  <div class="gradient"></div>
  <video>
    <source
      src="https://upload.wikimedia.org/wikipedia/commons/8/8c/Dancing-for-Food-in-the-Deep-Sea-Bacterial-Farming-by-a-New-Species-of-Yeti-Crab-pone.0026243.s002.ogv"
      type="video/webm"
    />
  </video>
</div>

Notice that I've pulled the video element out of the gradient div, so it can be displayed on top of it.

Hope it'll help.

ContentLicense: CC BY-SA 4.0


问:
Sync clock over ethernet using custom message
I have a setup where I have some PLC's connected to a windows PC, I am doing the code on the windows PC in C#. I want to be able to sync the clock of the PLC's with the PC.

The PLC don't support the windows built in time sync services, so I need to do it myself.

My first idea is to just send a message (TCP) to the PLC periodically containing the time of the windows PC. I don't need to be precise on milliseconds, a second would be fine. So my first guess is that this would be enough.

But now I think that if it wasn't so difficult it could be cool to make something that took the time of sending a message on TCP into account to get a more precise sync.

Any ideas on how to achieve that?

答:
Since TCP has some overhead and the amount of data is pretty small, why not use UDP?

Send a UDP request to the server, receive the current time as answer and use half of the answer time as transport delay - rough but easy to do.


问:
What is the correct way to implement Struct abstraction in Go?
I'm having some issues understanding Go's struct inheritance. I'm trying to do somewhat of an abstraction for an object type. See the example code below:

```<code>package main

type Animal struct{}
type Dog struct {
    Animal
    Color string
}

type Person struct {
    Name string
    Age  int
    Pet  *Animal
}

func main() {
    dog := &Dog{Color: "brown"}
    tom := &Person{Name: "Tom", Age: 13, Pet: dog}
}
</code>```

This is causing a compilation error:

cannot use dog (type *Dog) as type *Animal in field value

What is the correct way to go about doing an abstraction like this? Is it possible in Go?

End goal for the example would be to have different types of Pets - Dog, Cat, Hamser, etc. Then be able to store that into a struct expecting type Animal.

To visualize, something like:

```<code>type Person struct {
    Name string
    Age  int
    Pet  *Dog OR *Cat OR *Hamster
}
</code>```

Go Playground Link

答:
Just to add to the accepted answer, the use of interfaces or embedding is not really a requirement, at least not in this simple example.

For example, if you have a set of types that have the same structure but do not have any methods, i.e. pure data without behaviour, in such a case you can use a single type to represent the set and an additional "enum" to represent the "kind".

For example:

```<code>type AnimalKind string

const (
    AnimalKindDog AnimalKind = "dog"
    AnimalKindCat AnimalKind = "cat"
)

type Animal struct {
    Kind  AnimalKind
    Color string
}

// ...

dog := &Animal{Kind: AnimalKindDog, Color: "brown"}
tom := &Person{Name: "Tom", Age: 13, Pet: dog}
</code>```

Body:
I'm having some issues understanding Go's struct inheritance. I'm trying to do somewhat of an abstraction for an object type. See the example code below:

package main

type Animal struct{}
type Dog struct {
    Animal
    Color string
}

type Person struct {
    Name string
    Age  int
    Pet  *Animal
}

func main() {
    dog := &Dog{Color: "brown"}
    tom := &Person{Name: "Tom", Age: 13, Pet: dog}
}

This is causing a compilation error:

cannot use dog (type *Dog) as type *Animal in field value

What is the correct way to go about doing an abstraction like this? Is it possible in Go?

End goal for the example would be to have different types of Pets - Dog, Cat, Hamser, etc. Then be able to store that into a struct expecting type Animal.

To visualize, something like:

type Person struct {
    Name string
    Age  int
    Pet  *Dog OR *Cat OR *Hamster
}

Go Playground Link

Body:
Just to add to the accepted answer, the use of interfaces or embedding is not really a requirement, at least not in this simple example.

For example, if you have a set of types that have the same structure but do not have any methods, i.e. pure data without behaviour, in such a case you can use a single type to represent the set and an additional "enum" to represent the "kind".

For example:

type AnimalKind string

const (
    AnimalKindDog AnimalKind = "dog"
    AnimalKindCat AnimalKind = "cat"
)

type Animal struct {
    Kind  AnimalKind
    Color string
}

// ...

dog := &Animal{Kind: AnimalKindDog, Color: "brown"}
tom := &Person{Name: "Tom", Age: 13, Pet: dog}


问:
Scale UIButton Animation- Swift
I'm trying to do scale animation for UIButton when its clicked but what I'm trying to accomplish is when the button clicked I need the UIButton to be smaller to the inside then it comes back to its same size (like a bubble).

I tried the following:

```<code>button.transform = CGAffineTransformMakeScale(-1, 1)

UIView.animateWithDuration(0.5, animations: { () -> Void in

    button.transform = CGAffineTransformMakeScale(1,1)

})
</code>```

答:
Scaling Button or any view about three times or more use following code. swift 3 or swift 4 with xcode 9.</p>

```<code> UIView.animate(withDuration: 0.2, animations: {
        self.cartShowHideBtnView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)

    }, completion: { (finish: Bool) in
            UIView.animate(withDuration: 0.2, animations: {
                self.cartShowHideBtnView.transform = CGAffineTransform.identity

            }, completion:{(finish: Bool) in
                UIView.animate(withDuration: 0.2, animations: {
                    self.cartShowHideBtnView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)

                }, completion: { (finish: Bool) in
                    UIView.animate(withDuration: 0.2, animations: {
                        self.cartShowHideBtnView.transform = CGAffineTransform.identity

                    }, completion:{(finish: Bool) in
                        UIView.animate(withDuration: 0.2, animations: {
                            self.cartShowHideBtnView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)

                        }, completion: { (finish: Bool) in
                            UIView.animate(withDuration: 0.2, animations: {
                                self.cartShowHideBtnView.transform = CGAffineTransform.identity
                        })
                    })
                })
            })
        })
    })
</code>```

Title: Scale UIButton Animation- Swift

Body:
I'm trying to do scale animation for UIButton when its clicked but what I'm trying to accomplish is when the button clicked I need the UIButton to be smaller to the inside then it comes back to its same size (like a bubble).

I tried the following:

button.transform = CGAffineTransformMakeScale(-1, 1)

UIView.animateWithDuration(0.5, animations: { () -> Void in

    button.transform = CGAffineTransformMakeScale(1,1)

})

Body:
Scaling Button or any view about three times or more use following code. swift 3 or swift 4 with xcode 9.

 UIView.animate(withDuration: 0.2, animations: {
        self.cartShowHideBtnView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)

    }, completion: { (finish: Bool) in
            UIView.animate(withDuration: 0.2, animations: {
                self.cartShowHideBtnView.transform = CGAffineTransform.identity

            }, completion:{(finish: Bool) in
                UIView.animate(withDuration: 0.2, animations: {
                    self.cartShowHideBtnView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)

                }, completion: { (finish: Bool) in
                    UIView.animate(withDuration: 0.2, animations: {
                        self.cartShowHideBtnView.transform = CGAffineTransform.identity

                    }, completion:{(finish: Bool) in
                        UIView.animate(withDuration: 0.2, animations: {
                            self.cartShowHideBtnView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)

                        }, completion: { (finish: Bool) in
                            UIView.animate(withDuration: 0.2, animations: {
                                self.cartShowHideBtnView.transform = CGAffineTransform.identity
                        })
                    })
                })
            })
        })
    })


问:
Chrome auto-filling the username/password in my application
I have an application, within which a user creates login details for various sub-users.

When I navigate to any such form for creating a new user, Chrome by default fills the username and password for currently logged-in user in to the form.

I thought Chrome might be picking these fields based on their id or name (which were earlier id=username and id=password respectively). However, even after changing these id and name, Chrome fills the field in the form.

How and Why does Chrome do this. I have been through this
 and few other links but could not fix this.

Any suggestions ?

答:
This is because of browser history. try this and it will no longer be problem

Open the Chrome menu using the button on the far right of the browser
toolbar.

Choose the Settings menu option.

Click the Show advanced
settings… link located at the bottom of the page. In the “Passwords
and forms” section, click the Manage passwords link


问:
Yii2: how to specify multiples database schemas?
I am using PostgreSQL and the default database schema in my Yii2 application.

I created a new schema called laboratory and I need to define it in the common/config/main-local.php file.

This is my current main-local.php file:

```<code><?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'pgsql:host=localhost;dbname=travel',
            'username' => 'aaaa',
            'password' => 'bbbb',
            'charset' => 'utf8',
        ],
    ],
];
</code>```

How can I add the laboratory schema in this file? I need both schemas.

Is Yii2 supporting multiples schemas?

答:
It wasn't necessary to change it:

```<code><?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'pgsql:host=localhost;dbname=travel',
            'username' => 'aaaa',
            'password' => 'bbbb',
            'charset' => 'utf8',
        ],
    ],
];
</code>```

Then Gii code generator recognizes the laboratory schema (but autocomplete for Table Name doesn't work).

Body:
I am using PostgreSQL and the default database schema in my Yii2 application.

I created a new schema called laboratory and I need to define it in the common/config/main-local.php file.

This is my current main-local.php file:

<?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'pgsql:host=localhost;dbname=travel',
            'username' => 'aaaa',
            'password' => 'bbbb',
            'charset' => 'utf8',
        ],
    ],
];

How can I add the laboratory schema in this file? I need both schemas.

Is Yii2 supporting multiples schemas?

Body:
It wasn't necessary to change it:

<?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'pgsql:host=localhost;dbname=travel',
            'username' => 'aaaa',
            'password' => 'bbbb',
            'charset' => 'utf8',
        ],
    ],
];

Then Gii code generator recognizes the laboratory schema (but autocomplete for Table Name doesn't work).


问:
Returning a random post with get_posts(); in Wordpress
I am currently trying to return one random post from a custom post type in Wordpress. Currently, all it returns is the last post posted within that custom post type. I am currently using this code to get the posts:</p>

```<code><?php $posts = get_posts(array('posts_per_page' => 1, 'order_by' => 'rand', 'order' => 'ASC', 'post_type' => 'call_to_action')); if( $posts ): ?>
  <?php foreach ( $posts as $post ) : setup_postdata( $post ); ?>
    // Some code
  <?php endforeach; ?>
  <?php wp_reset_postdata(); ?>
<?php endif; ?>
</code>```

答: Change 'order_by' => 'rand' to 'orderby' => 'rand'

Body:
I am currently trying to return one random post from a custom post type in Wordpress. Currently, all it returns is the last post posted within that custom post type. I am currently using this code to get the posts:

<?php $posts = get_posts(array('posts_per_page' => 1, 'order_by' => 'rand', 'order' => 'ASC', 'post_type' => 'call_to_action')); if( $posts ): ?>
  <?php foreach ( $posts as $post ) : setup_postdata( $post ); ?>
    // Some code
  <?php endforeach; ?>
  <?php wp_reset_postdata(); ?>
<?php endif; ?>


问:
What is the difference between SocketAddress and InetAddress in Java
It's unclear what SocketAddres is designed for. As far as I see there is just one reasonable way to use it: through InetSocketAddress. It's confusing.</p>

答:
From the Documentation of SocketAddress:

This class represents a Socket Address with no protocol attachment. As an abstract class, it is meant to be subclassed with a specific, protocol dependent, implementation.

From the Documentation of InetAddress:

This class represents an Internet Protocol (IP) address.

So one represents a socket without any protocol as abstract class, the other represents an IP-address. What you are most probably looking for is an InetSocketAddress (a socket, bound to a specific IP/Hostname and port).


问:
Typo3 7.6.22 Bootstrap Package / RTE / unable to use font colors
in my current configuration (TYPO3 CMS 7.6.22 Bootstrap Package) the font color picker in RTE does not work. can you help?

I added this TypoScript to PageTSConfig

now it is possible to select colors in RTE

but after saving the page - the color disappiered in RTE and is not displayed in the frontend

here is my template configuration.

答:
Thanks to Thomas Löffler!

after changing the pageTSConfig, the format functions are working!


问:
How to properly print a list of unicode characters in python?
I am trying to search for emoticons in python strings.
So I have, for example,

```<code>em_test = ['\U0001f680']
print(em_test)
['']
test = 'This is a test string '
if any(x in test for x in em_test):
    print ("yes, the emoticon is there")
else:
    print ("no, the emoticon is not there")

yes, the emoticon is there
</code>```

and if a search em_test in

'This is a test string '

I can actually find it.

So I have made a csv file with all the emoticons I want defined by their unicode.
The CSV looks like this:

\U0001F600

\U0001F601

\U0001F602

\U0001F923

and when I import it and print it I actullay do not get the emoticons but rather just the text representation:

```<code>['\\U0001F600',
 '\\U0001F601',
 '\\U0001F602',
 '\\U0001F923',
...
]
</code>```

and hence I cannot use this to search for these emoticons in another string...
I somehow know that the double backslash \ is only representation of a single slash but somehow the unicode reader does not get it... I do not know what I'm missing.

Any suggestions?

答:
1. keeping your csv as-is:

it's a bloated solution, but using ast.literal_eval works:

```<code>import ast

s = '\\U0001F600'

x = ast.literal_eval('"{}"'.format(s))
print(hex(ord(x)))
print(x)
</code>```

I get 0x1f600 (which is correct char code) and some emoticon character (). (well I had to copy/paste a strange char from my console to this answer textfield but that's a console issue by my end, otherwise that works)

just surround with quotes to allow ast to take the input as string.

2. using character codes directly

maybe you'd be better off by storing the character codes themselves instead of the \U format:

```<code>print(chr(0x1F600))
</code>```

does exactly the same (so ast is slightly overkill)

your csv could contain:

```<code>0x1F600
0x1F601
0x1F602
0x1F923
</code>```

then chr(int(row[0],16)) would do the trick when reading it: example if one 1 row in CSV (or first row)

```<code>with open("codes.csv") as f:
   cr = csv.reader(f)
   codes = [int(row[0],16) for row in cr]
</code>```

Body:
I am trying to search for emoticons in python strings.
So I have, for example,

em_test = ['\U0001f680']
print(em_test)
['']
test = 'This is a test string '
if any(x in test for x in em_test):
    print ("yes, the emoticon is there")
else:
    print ("no, the emoticon is not there")

yes, the emoticon is there

and if a search em_test in

'This is a test string '

I can actually find it.

So I have made a csv file with all the emoticons I want defined by their unicode.
The CSV looks like this:

\U0001F600

\U0001F601

\U0001F602

\U0001F923

and when I import it and print it I actullay do not get the emoticons but rather just the text representation:

['\\U0001F600',
 '\\U0001F601',
 '\\U0001F602',
 '\\U0001F923',
...
]

and hence I cannot use this to search for these emoticons in another string...
I somehow know that the double backslash \ is only representation of a single slash but somehow the unicode reader does not get it... I do not know what I'm missing.

Any suggestions?

Body:
1. keeping your csv as-is:

it's a bloated solution, but using ast.literal_eval works:

import ast

s = '\\U0001F600'

x = ast.literal_eval('"{}"'.format(s))
print(hex(ord(x)))
print(x)

I get 0x1f600 (which is correct char code) and some emoticon character (). (well I had to copy/paste a strange char from my console to this answer textfield but that's a console issue by my end, otherwise that works)

just surround with quotes to allow ast to take the input as string.

2. using character codes directly

maybe you'd be better off by storing the character codes themselves instead of the \U format:

print(chr(0x1F600))

does exactly the same (so ast is slightly overkill)

your csv could contain:

0x1F600
0x1F601
0x1F602
0x1F923

then chr(int(row[0],16)) would do the trick when reading it: example if one 1 row in CSV (or first row)

with open("codes.csv") as f:
   cr = csv.reader(f)
   codes = [int(row[0],16) for row in cr]


问:
How display php echo results in different styles?
I have 2 php echo results from my mysql database. Their request is common and wrapped into one line :

```<code>$sql = "SELECT * FROM test WHERE id IN ('9','10')";
</code>```

I want only the first result to be displayed in h3 style, and the second result to be displayed in normal p style.  Using the code below the 2 results are displayed in h3 style.

How do I fix it ?

Thank you in advance.

```<code>enter code here

<div class="one-third wow fadeIn">
<span class="circle"><span class="ico pig"></span></span>
<h3>

<?php
$conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
if ($conn->connect_error)
{
echo "connection error" ;
}

$sql = "SELECT * FROM test WHERE id IN ('9','10')";
$result = $conn->query($sql);

?>
<?php
if ($result->num_rows > 0) { while($data = $result->fetch_assoc())
{echo $data ['FR']."<br>"; }    } else {echo "---"; }?></h3>
<p>
</code>```

答:
Try this<br>

        </p>

```<code>    <?php
        $conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
        if ($conn->connect_error)
        {
                echo "connection error" ;
        }
        $sql = "SELECT * FROM test WHERE id IN ('9','10')";
        $result = $conn->query($sql);
    ?>
    <?php
    $i = 0;
    if ($result->num_rows > 0) {
            while($data = $result->fetch_assoc()){
                  if($i == 0){
                        echo "<h3>".$data ['FR']."<br></h3>";
                    }else{
                        echo "<p>".$data ['FR']."<br></p>";
                    }
                     $i++;
            }
    } else {
        echo "---";
    }
    ?>
</code>```

Body:
I have 2 php echo results from my mysql database. Their request is common and wrapped into one line :

$sql = "SELECT * FROM test WHERE id IN ('9','10')";

I want only the first result to be displayed in h3 style, and the second result to be displayed in normal p style.  Using the code below the 2 results are displayed in h3 style.

How do I fix it ?

Thank you in advance.

enter code here

<?php
$conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
if ($conn->connect_error)
{
echo "connection error" ;
}

$sql = "SELECT * FROM test WHERE id IN ('9','10')";
$result = $conn->query($sql);

?>
<?php
if ($result->num_rows > 0) { while($data = $result->fetch_assoc())
{echo $data ['FR']."
"; }    } else {echo "---"; }?>

Body:
Try this

    <?php
        $conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
        if ($conn->connect_error)
        {
                echo "connection error" ;
        }
        $sql = "SELECT * FROM test WHERE id IN ('9','10')";
        $result = $conn->query($sql);
    ?>
    <?php
    $i = 0;
    if ($result->num_rows > 0) {
            while($data = $result->fetch_assoc()){
                  if($i == 0){
                        echo "<h3>".$data ['FR']."<br></h3>";
                    }else{
                        echo "<p>".$data ['FR']."<br></p>";
                    }
                     $i++;
            }
    } else {
        echo "---";
    }
    ?>


问:
git shows difference between dev and master even directly after merge of dev into master
This is happening to me in 2 separate repo's.

My dev branch is ahead of my master branch by several commits. I open a pull request to merge dev into master (squash and merge). After merging, when I compare dev and master again, it shows the same exact diff list of commits.

Opening up another pull request again shows the same commit.

I have resolved the issue by deleting dev entirely and creating a new branch with checkout -b when on master, but can someone explain why this occured?

答:
GitHub's "Squash and merge" is not a conventional merge - a brand new commit is created, and then fast-forward merged onto the target branch.  Thus the two branches will appear to be unrelated in the commit graph, so a subsequent diff will show a confusing result.

So S&M is generally only a good idea when the source branch is ephemeral - i.e. if it's not needed once the PR is done.  So it generally makes sense for short-lived feature branches, but not for your use case.


问:
What is the vanilla JS version of Jquery's $.getJSON
I need to build a project to get into a JS bootcamp I am applying for.  They tell me I may only use vanilla JS, specifically that frameworks and Jquery are not permitted.  Up to this point when I wanted to retrieve a JSON file from an api I would say

```<code>$.getJSON(url, functionToPassJsonFileTo)
</code>```

for JSON calls and

```<code>$.getJSON(url + "&callback?", functionToPassJsonPFileTo)
</code>```

for JSONP calls.  I just started programming this month so please bear in mind I don't know the difference between JSON or JSONP or how they relate to this thing called ajax.  Please explain how I would get what the 2 lines above achieve in Vanilla Javascript.  Thank you.

So to clarify,

```<code>function jsonp(uri){
    return new Promise(function(resolve, reject){
        var id = '_' + Math.round(10000 * Math.random())
        var callbackName = 'jsonp_callback_' + id
        window[callbackName] = function(data){
            delete window[callbackName]
            var ele = document.getElementById(id)
            ele.parentNode.removeChild(ele)
            resolve(data)
        }

        var src = uri + '&callback=' + callbackName
        var script = document.createElement('script')
        script.src = src
        script.id = id
        script.addEventListener('error', reject)
        (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
    })
}
</code>```

would be the JSONP equivalent?

答:
ES6 has Fetch API which provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

It is easier than XMLHttpRequest.

```<code>fetch(url) // Call the fetch function passing the url of the API as a parameter
  .then(res => res.json())
  .then(function (res) {
    console.log(res)
    // Your code for handling the data you get from the API
  })
  .catch(function() {
    // This is where you run code if the server returns any errors
  });
</code>```

Body:
I need to build a project to get into a JS bootcamp I am applying for.  They tell me I may only use vanilla JS, specifically that frameworks and Jquery are not permitted.  Up to this point when I wanted to retrieve a JSON file from an api I would say

$.getJSON(url, functionToPassJsonFileTo)

for JSON calls and

$.getJSON(url + "&callback?", functionToPassJsonPFileTo)

for JSONP calls.  I just started programming this month so please bear in mind I don't know the difference between JSON or JSONP or how they relate to this thing called ajax.  Please explain how I would get what the 2 lines above achieve in Vanilla Javascript.  Thank you.

So to clarify,

function jsonp(uri){
    return new Promise(function(resolve, reject){
        var id = '_' + Math.round(10000 * Math.random())
        var callbackName = 'jsonp_callback_' + id
        window[callbackName] = function(data){
            delete window[callbackName]
            var ele = document.getElementById(id)
            ele.parentNode.removeChild(ele)
            resolve(data)
        }

        var src = uri + '&callback=' + callbackName
        var script = document.createElement('script')
        script.src = src
        script.id = id
        script.addEventListener('error', reject)
        (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
    })
}

would be the JSONP equivalent?

Body:
ES6 has Fetch API which provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

It is easier than XMLHttpRequest.

fetch(url) // Call the fetch function passing the url of the API as a parameter
  .then(res => res.json())
  .then(function (res) {
    console.log(res)
    // Your code for handling the data you get from the API
  })
  .catch(function() {
    // This is where you run code if the server returns any errors
  });


问:
How to check object null value in xamarin forms data trigger?
I'm trying to check if a binding object value is null in Xamarin Forms XAML DataTrigger but I can't get it to work. I have tried the following:

```<code><StackLayout IsVisible="True">
    <StackLayout.Triggers>
        <DataTrigger TargetType="StackLayout"
                        Binding="{Binding MyObject}"
                        Value="{x:Null}">
            <Setter Property="IsVisible" Value="False"></Setter>
        </DataTrigger>
    </StackLayout.Triggers>

    ...

</StackLayout>
</code>```

Does anyone know a way to do it? I have tested this only on Android.

Edit: I have filed a bug report to xamarin bugzilla https://bugzilla.xamarin.com/show_bug.cgi?id=57863

答: Its a bug with Xmarin Forms  here</p>

Body:
I'm trying to check if a binding object value is null in Xamarin Forms XAML DataTrigger but I can't get it to work. I have tried the following:

<StackLayout IsVisible="True">
    <StackLayout.Triggers>
        <DataTrigger TargetType="StackLayout"
                        Binding="{Binding MyObject}"
                        Value="{x:Null}">
            <Setter Property="IsVisible" Value="False"></Setter>
        </DataTrigger>
    </StackLayout.Triggers>

    ...

</StackLayout>

Does anyone know a way to do it? I have tested this only on Android.

Edit: I have filed a bug report to xamarin bugzilla https://bugzilla.xamarin.com/show_bug.cgi?id=57863

Body: Its a bug with Xmarin Forms  here


问:
Creating a Compilation Unit with type bindings
I am working with the AST API in java, and I am trying to create a Compilation Unit with type bindings. I wrote the following code:

```<code>private static CompilationUnit parse(ICompilationUnit unit) {
 ASTParser parser = ASTParser.newParser(AST.JLS3);
 parser.setKind(ASTParser.K_COMPILATION_UNIT);
 parser.setSource(unit);
 parser.setResolveBindings(true);
 CompilationUnit compiUnit = (CompilationUnit) parser.createAST(null);
 return compiUnit;
}
</code>```

Unfortunately, when I run this code in debug mode and inspect compiUnit I find that compiUnit.ast.resolver.isRecoveringBindings is false.

Can anyone think of a reason why it wouldn't be true, as I specified it to be?

Thank you

答:
You are mixing up two pieces of the API: binding resolving and binding recovery.  From the JavaDoc for setBindingsRecovery:

```<code>void org.eclipse.jdt.core.dom.ASTParser.setBindingsRecovery(boolean enabled)

Requests that the compiler should perform bindings recovery. When bindings recovery is enabled the compiler returns incomplete bindings.

Default to false.

This should be set to true only if bindings are resolved. It has no effect if there is no binding resolution.

Parameters:
enabled true if incomplete bindings are expected, and false if only complete bindings are expected.
</code>```

So, yes.  It is expected that bindings recovery is set to false because that is the default.  However, since you explicitly set bindings to be resolved, that should be set to true in the AST object.  You should check the method AST.hasBindingsResolved() to see if you can get your bindings.

To be clear: bindings resolution is about getting the parser/compiler to calculate type bindings as the AST is being created, while bindings recovery is about enabling bindings to be partially computed.  Honestly, I'm not exactly sure what bindings recovery helps with, but I am fairly certain that it is not something that you need.

Body:
I am working with the AST API in java, and I am trying to create a Compilation Unit with type bindings. I wrote the following code:

private static CompilationUnit parse(ICompilationUnit unit) {
 ASTParser parser = ASTParser.newParser(AST.JLS3);
 parser.setKind(ASTParser.K_COMPILATION_UNIT);
 parser.setSource(unit);
 parser.setResolveBindings(true);
 CompilationUnit compiUnit = (CompilationUnit) parser.createAST(null);
 return compiUnit;
}

Unfortunately, when I run this code in debug mode and inspect compiUnit I find that compiUnit.ast.resolver.isRecoveringBindings is false.

Can anyone think of a reason why it wouldn't be true, as I specified it to be?

Thank you

Body:
You are mixing up two pieces of the API: binding resolving and binding recovery.  From the JavaDoc for setBindingsRecovery:

void org.eclipse.jdt.core.dom.ASTParser.setBindingsRecovery(boolean enabled)

Requests that the compiler should perform bindings recovery. When bindings recovery is enabled the compiler returns incomplete bindings.

Default to false.

This should be set to true only if bindings are resolved. It has no effect if there is no binding resolution.

Parameters:
enabled true if incomplete bindings are expected, and false if only complete bindings are expected.

So, yes.  It is expected that bindings recovery is set to false because that is the default.  However, since you explicitly set bindings to be resolved, that should be set to true in the AST object.  You should check the method AST.hasBindingsResolved() to see if you can get your bindings.

To be clear: bindings resolution is about getting the parser/compiler to calculate type bindings as the AST is being created, while bindings recovery is about enabling bindings to be partially computed.  Honestly, I'm not exactly sure what bindings recovery helps with, but I am fairly certain that it is not something that you need.