问:
Equivalent to CryptoStream .NET in Java?
I have an encrypted string in visual basic. NET 2008, the functions to encrypt and decrypt are the following:

```<code>Imports System.Security.Cryptography

 Public Shared Function Encriptar(ByVal strValor As String) As String
    Dim strEncrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey)
        Dim des As New DESCryptoServiceProvider
        Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())
    Catch ex As Exception
        Return ""
    End Try
End Function

Public Shared Function Desencriptar(ByVal strValor As String) As String
    Dim sDecrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Dim inputByteArray(strValor.Length) As Byte
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey)
        Dim des As New DESCryptoServiceProvider
        If Trim(strValor).Length = 0 Then
            Throw New Exception("Password No debe estar en Blanco")
        End If
        inputByteArray = Convert.FromBase64String(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
        Return encoding.GetString(ms.ToArray(), 0, ms.ToArray.Count)
    Catch ex As Exception
        Return ""
    End Try
End Function
</code>```

for example the word "android" encrypted with this function gives me the result "B3xogi/Qfsc="

now I need to decrypt the string "B3xogi/Qfsc=" it from java, by the same key, which is "key12345", and the result should be "android"...anyone know how to do this?

Thanks in advance.

答:
Using Apache Commons Codec for hex and base64 encoding/decoding, you can use the following code:</p>

```<code>KeySpec ks = new DESKeySpec("key12345".getBytes("UTF-8"));
SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(ks);

IvParameterSpec iv = new IvParameterSpec(
        Hex.decodeHex("1234567890ABCDEF".toCharArray()));

Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);

byte[] decoded = cipher.doFinal(Base64.decodeBase64("B3xogi/Qfsc="));

System.out.println("Decoded: " + new String(decoded, "UTF-8"));
</code>```

Body:
I have an encrypted string in visual basic. NET 2008, the functions to encrypt and decrypt are the following:

Imports System.Security.Cryptography

 Public Shared Function Encriptar(ByVal strValor As String) As String
    Dim strEncrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey)
        Dim des As New DESCryptoServiceProvider
        Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())
    Catch ex As Exception
        Return ""
    End Try
End Function

Public Shared Function Desencriptar(ByVal strValor As String) As String
    Dim sDecrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Dim inputByteArray(strValor.Length) As Byte
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey)
        Dim des As New DESCryptoServiceProvider
        If Trim(strValor).Length = 0 Then
            Throw New Exception("Password No debe estar en Blanco")
        End If
        inputByteArray = Convert.FromBase64String(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
        Return encoding.GetString(ms.ToArray(), 0, ms.ToArray.Count)
    Catch ex As Exception
        Return ""
    End Try
End Function

for example the word "android" encrypted with this function gives me the result "B3xogi/Qfsc="

now I need to decrypt the string "B3xogi/Qfsc=" it from java, by the same key, which is "key12345", and the result should be "android"...anyone know how to do this?

Thanks in advance.

Body:
Using Apache Commons Codec for hex and base64 encoding/decoding, you can use the following code:

KeySpec ks = new DESKeySpec("key12345".getBytes("UTF-8"));
SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(ks);

IvParameterSpec iv = new IvParameterSpec(
        Hex.decodeHex("1234567890ABCDEF".toCharArray()));

Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);

byte[] decoded = cipher.doFinal(Base64.decodeBase64("B3xogi/Qfsc="));

System.out.println("Decoded: " + new String(decoded, "UTF-8"));


来源: stackexchange

问:
ionic 3 directive styling
Hi I'm currently at ionic 3.12.1 and I wanted to ask if there was any possibilities to style a directive directly.
If I add css classes to the directives the css class won't even show up.

```<code><ion-list class="tracker-list">
        <ion-list-header class="tracker-header">
            Action
        </ion-list-header>
        <ion-item>Terminator II</ion-item>
    </ion-list>
</code>```

Thanks!

答:
You best approach would be to look into ionic sass variables

In your example you would target the ion-list variables in your theme/variables.scss file REF: list variables

What you might need to do in order to get your current classes working is to wrap the classes in the 3 modes

```<code>.md,.wp,.ios{
 .tracker-list{
 }
 .tracker-header{
  }
}
</code>```

That tells iconic that your classes are more important then ionic's predefined classes.

ContentLicense: CC BY-SA 3.0

Title: ionic 3 directive styling

Body:
Hi I'm currently at ionic 3.12.1 and I wanted to ask if there was any possibilities to style a directive directly.
If I add css classes to the directives the css class won't even show up.

<ion-list class="tracker-list">
        <ion-list-header class="tracker-header">
            Action
        </ion-list-header>
        <ion-item>Terminator II</ion-item>
    </ion-list>

Thanks!

Body:
You best approach would be to look into ionic sass variables

In your example you would target the ion-list variables in your theme/variables.scss file REF: list variables

What you might need to do in order to get your current classes working is to wrap the classes in the 3 modes

.md,.wp,.ios{
 .tracker-list{
 }
 .tracker-header{
  }
}

That tells iconic that your classes are more important then ionic's predefined classes.


问:
Is there a way to restrict communication between two containers on the same pod to have improved isolation?
I have deployed two containers on a pod. One is privileged and the other is a normal user container. I want to restrict communication between the two containers so that they cannot access each other or talk to each other on local host. </p>

答: As long as this privileged container has no applications listening, there shouldn't be any reason for these two containers to talk to each other. In case it has any kind of application listening, make sure to add any kind of authentication so it prevents any unwanted communication.</p>


问:
Push specific row values to result array if row column value matches search string
I have an array with a lot of different $keys and $values

What I did is create a form that allows the user to insert an emailadres.

Then a foreach loop start running and saves the values of every found emailaddress to a new array

This is the outcome of that array:

```<code><?php
Array
(
    [0] => email@email.com
    [1] => 103646
    [2] => Company
    [3] => 1140
    [4] => email@email.com
    [5] => 103689
    [6] => Company
    [7] => 3400
)
?>
</code>```

What I would like it that every $value has it's own $key

I don't really know how to accomplish that.

This is my array making script:

```<code><?php
$saved = array();
$input = $_GET['emailaddress'];
foreach ($data as $files){
    $bedrijf = $files['Name'];
    $bill = $files['Bill'];
    $amount = $files['Amount'];
    $email = $files['email'];
    if ($email == $input){
        foreach($files as $values){
            $saved[] = $values;
        }

    }
}
echo'```';
print_r($saved);
echo'```';
?>
</code>```

答:
You can do that by one foreach. No need to increase complexity of the code.</p>

```<code>$i = 0;
foreach ($data as $files){
    $bedrijf = $files['Name'];
    $bill = $files['Bill'];
    $amount = $files['Amount'];
    $email = $files['email'];
    if ($email == $input){
            $saved[$i]['email'] = $email;
            $saved[$i]['Amount'] = $amount;
            $saved[$i]['bill '] = $bill;
            $saved[$i]['Name'] = $bedrijf ;
            $i++;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array with a lot of different $keys and $values

What I did is create a form that allows the user to insert an emailadres.

Then a foreach loop start running and saves the values of every found emailaddress to a new array

This is the outcome of that array:

<?php
Array
(
    [0] => email@email.com
    [1] => 103646
    [2] => Company
    [3] => 1140
    [4] => email@email.com
    [5] => 103689
    [6] => Company
    [7] => 3400
)
?>

What I would like it that every $value has it's own $key

I don't really know how to accomplish that.

This is my array making script:

<?php
$saved = array();
$input = $_GET['emailaddress'];
foreach ($data as $files){
    $bedrijf = $files['Name'];
    $bill = $files['Bill'];
    $amount = $files['Amount'];
    $email = $files['email'];
    if ($email == $input){
        foreach($files as $values){
            $saved[] = $values;
        }

    }
}
echo'
';
print_r($saved);
echo'
';
?>

Body:
You can do that by one foreach. No need to increase complexity of the code.

$i = 0;
foreach ($data as $files){
    $bedrijf = $files['Name'];
    $bill = $files['Bill'];
    $amount = $files['Amount'];
    $email = $files['email'];
    if ($email == $input){
            $saved[$i]['email'] = $email;
            $saved[$i]['Amount'] = $amount;
            $saved[$i]['bill '] = $bill;
            $saved[$i]['Name'] = $bedrijf ;
            $i++;
    }
}


问:
python: getting the output from multiple for loops outside of the for loop
I have a nested for loops as you can see below:

```<code>cv_list_dic = cv_list()
for cv in cv_list_dic['results']:
    cv_name = cv['name']
    if qq_cv(cv_name):
            cv_versions = (cv['versions'])
            cv_id_list = []
            for cv_ids in cv_versions:
                    ver_id = (cv_ids['id'])
                    cv_id_list.append(ver_id)
            max_id = (max(cv_id_list))
            qq_cv_id = (cv_name, max_id)
            print(qq_cv_id)
</code>```

the output is a list of tuples (there is much more tuples, its just example):

```<code>('cv1', 152)
('cv2', 35)
</code>```

My issue that I need those tuples  outside of those for loops.
I have tried to create an empty list and append to it but it's appending only the last item.

答:
This should work, define cv_list_dic as an empty list (before the loop starts) and append each iteration the result into this list.

```<code>cv_list_dic = cv_list()
qq_cv_id = []
for cv in cv_list_dic['results']:
    cv_name = cv['name']
    if qq_cv(cv_name):
            cv_versions = (cv['versions'])
            cv_id_list = []
            for cv_ids in cv_versions:
                    ver_id = (cv_ids['id'])
                    cv_id_list.append(ver_id)
            max_id = (max(cv_id_list))
            qq_cv_id.append((cv_name, max_id))
            print(qq_cv_id)
</code>```

Body:
I have a nested for loops as you can see below:

cv_list_dic = cv_list()
for cv in cv_list_dic['results']:
    cv_name = cv['name']
    if qq_cv(cv_name):
            cv_versions = (cv['versions'])
            cv_id_list = []
            for cv_ids in cv_versions:
                    ver_id = (cv_ids['id'])
                    cv_id_list.append(ver_id)
            max_id = (max(cv_id_list))
            qq_cv_id = (cv_name, max_id)
            print(qq_cv_id)

the output is a list of tuples (there is much more tuples, its just example):

('cv1', 152)
('cv2', 35)

My issue that I need those tuples  outside of those for loops.
I have tried to create an empty list and append to it but it's appending only the last item.

Body:
This should work, define cv_list_dic as an empty list (before the loop starts) and append each iteration the result into this list.

cv_list_dic = cv_list()
qq_cv_id = []
for cv in cv_list_dic['results']:
    cv_name = cv['name']
    if qq_cv(cv_name):
            cv_versions = (cv['versions'])
            cv_id_list = []
            for cv_ids in cv_versions:
                    ver_id = (cv_ids['id'])
                    cv_id_list.append(ver_id)
            max_id = (max(cv_id_list))
            qq_cv_id.append((cv_name, max_id))
            print(qq_cv_id)


问:
Adding and Updating a List object does not work in C#
Newbie with C# and Linq.

I am trying to add an object and update an object if exists in a List. The list is not getting updated or not getting added with new inputs.It is not throwing any exception. Kindly, help.

```<code>private IList<SettingsEntity> Settings = new List<SettingsEntity>();

public SettingsRepository() {
            Settings.Add(new SettingsEntity() { UserID = "alpha", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "bravo", ApplicationName = "view", SettingKey = "RefreshRate", SettingValue = "10", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "charlie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "foxtrot", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "lima", ApplicationName = "view", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "Julie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "tango", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "victor", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "yankee", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "zulu", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
        }

 public bool Save(SettingsEntity entity)
        {
            var flag = false;
            if (entity != null)
            {
                var existing = Settings.Where(se => se.UserID == entity.UserID && se.ApplicationName == entity.ApplicationName && se.SettingKey == entity.SettingKey).ToList();
                if (existing != null)
                {
                    existing.ForEach(f => f.SettingValue = entity.SettingValue);
                    flag = true;
                }
                else
                {
                    Settings.Add(entity);
                    flag = true;
                }
                return flag;
            }
            else {
                throw new ArgumentNullException();
            }

        }

 [HttpPost]
        public IActionResult Post([FromBody] SettingsEntity entity)
        {
            var result = _SettingsRepository.Save(entity);
            if (result == true)
            {
                return Ok();
            }
            else
            {
                return BadRequest();
            }
        }
</code>```

答:
This

```<code>var existing = Settings.Where(se => se.UserID == entity.UserID
                                 && se.ApplicationName == entity.ApplicationName
                                 && se.SettingKey == entity.SettingKey).ToList();
</code>```

will never be null.

Therefore your Settings.Add(entity) will never be called. Instead of testing for null you could write

```<code>if (existing.Any()) //or if (existing.Count > 0)
{
    ...
}
else
{
    //Save here
}
</code>```

Body:
Newbie with C# and Linq.

I am trying to add an object and update an object if exists in a List. The list is not getting updated or not getting added with new inputs.It is not throwing any exception. Kindly, help.

private IList<SettingsEntity> Settings = new List<SettingsEntity>();

public SettingsRepository() {
            Settings.Add(new SettingsEntity() { UserID = "alpha", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "bravo", ApplicationName = "view", SettingKey = "RefreshRate", SettingValue = "10", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "charlie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "foxtrot", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "lima", ApplicationName = "view", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "Julie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "tango", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "victor", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "yankee", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "zulu", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
        }

 public bool Save(SettingsEntity entity)
        {
            var flag = false;
            if (entity != null)
            {
                var existing = Settings.Where(se => se.UserID == entity.UserID && se.ApplicationName == entity.ApplicationName && se.SettingKey == entity.SettingKey).ToList();
                if (existing != null)
                {
                    existing.ForEach(f => f.SettingValue = entity.SettingValue);
                    flag = true;
                }
                else
                {
                    Settings.Add(entity);
                    flag = true;
                }
                return flag;
            }
            else {
                throw new ArgumentNullException();
            }

        }

 [HttpPost]
        public IActionResult Post([FromBody] SettingsEntity entity)
        {
            var result = _SettingsRepository.Save(entity);
            if (result == true)
            {
                return Ok();
            }
            else
            {
                return BadRequest();
            }
        }

Body:
This

var existing = Settings.Where(se => se.UserID == entity.UserID
                                 && se.ApplicationName == entity.ApplicationName
                                 && se.SettingKey == entity.SettingKey).ToList();

will never be null.

Therefore your Settings.Add(entity) will never be called. Instead of testing for null you could write

if (existing.Any()) //or if (existing.Count > 0)
{
    ...
}
else
{
    //Save here
}


问:
Getting XBee-API to compile and run under Netbeans
The question is howto install XBee-API in Netbeans for use with other projects?

The answer should be to simply download the maven project from github and import into Netbeans. Easy-peasy.  The reality is not so simple. As a Java noobie it has taken me a day to get Xbee API to compile and run under Netbeans.

XBee-API version 0.9.1 from Github is in a Maven project that imports directly into Netbeans but it won't compile without further work. For initial tests, I used the Digi SDK kit connected via a USB/serial cable to my win10 PC. I was running a XBee S2C Digimesh device.  Ultimately the reason I am using XBee_API is communicate with a Raspberry Pi 3B via I2C.

The first XBee-API class to try to run is "OpenCloseConnectionsTest" found in the Test folder.  This provides very detailed debug information that should help with troubleshooting.  If this will run, then everything else should as well.

First error was because the XBee-API POM file did not include a version tag.  My POM now looks like:

```<code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</code>```

Next I was missing RxTx files.  On my win10 installation I was missing the following files in the following locations:

```<code>...\Program Files\Java\jkd1.6.0_01\jre\bin\rxtxSerial.dll

...\Program Files\Java\jdk1.6.0_01\jre\lib\ext\RXTXcomm.jar
</code>```

I downloaded these from here. Once I placed these files in these locations, Netbeans found them without further action/config.  I still have a warning because these files aren't quite the same version.

Finally, I needed to edit the source code to set the comm port ID.  In my case, the XBee was on "COM5".

I could not find any single source that has all of the above information.  A lot of information I found was outdated and some was simply wrong.  Hopefully this write-up will help others.

答:
OK so I am working on an answer to my question.  So in order to get the very latest version 0.9.2 of XBee-API, I need to install a project from the Maven Central Repository into Netbeans.  I found a couple of posts that pointed me here.
I didn't find this useful at all.  The answer might be there somewhere but it assumes a level of understanding of Maven and Ant that I don't have, so I experimented.  I created a new Maven project in Netbeans and then copied the content of the XBee-API POM file I found in Maven Central and pasted that to replace the content of the default POM file in the new Maven project I had created.

My understanding is that Maven will download all the files needed based on the POM file, but it didn't.  Most of the files were downloaded, but not all.  I got the following warnings:

```<code>    Some problems were encountered while building the effective model for com.rapplogic:xbee-api:jar:0.9.2
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-gpg-plugin is missing. @ line 60, column 21
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 51, column 21
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-source-plugin is missing. @ line 86, column 21
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-javadoc-plugin is missing. @ line 99, column 21
</code>```

And also:

```<code>Failed to execute goal pl.project13.maven:git-commit-id-plugin:2.2.1:revision (get-the-git-infos) on project xbee-api: The plugin pl.project13.maven:git-commit-id-plugin:2.2.1 requires Maven version [3.1.1,) -> [Help 1]
</code>```

This might make sense to anyone that knows something about Maven, but that's not me.  It looks like I need to upgrade Maven which is only a couple of months old since that is how long I have been using Java for.

I found that I am already running the latest Maven ver 3.5.0.  The error message says I need 3.1.1 so upgrading Maven isn't possible and downgrading back to 3.1.1 seems like a bad idea.  Time to change tack and look at using a later version of the plugin.

I found others who have had this problem here and here but no solutions.  I found this response here that indicates the problem is that there is no version specified for each plugin in the POM.  So it seems like Apache has changed the rules (requiring a version to be specified in the POM) but haven't provided a tool to update POMs. This seems to be something that could be scanned for and corrected within Maven Central. The POM I am running is only 5 months old and yet it won't build without manual intervention.

To fix the version problem, I had to search Maven Central for each plugin to get the latest/right version number and amend the POM.  How bad is that!!  That process cleared all but one fatal error.  I have now hit an impasse described in the question here

The solution I am going to pursue is to work with the older version of XBee-API from Github.  This gives me the source code and it builds without issue.  I plan to modify this code to use I2C rather than RS232.  There is also beta code for a socket server.

Body:
The question is howto install XBee-API in Netbeans for use with other projects?

The answer should be to simply download the maven project from github and import into Netbeans. Easy-peasy.  The reality is not so simple. As a Java noobie it has taken me a day to get Xbee API to compile and run under Netbeans.

XBee-API version 0.9.1 from Github is in a Maven project that imports directly into Netbeans but it won't compile without further work. For initial tests, I used the Digi SDK kit connected via a USB/serial cable to my win10 PC. I was running a XBee S2C Digimesh device.  Ultimately the reason I am using XBee_API is communicate with a Raspberry Pi 3B via I2C.

The first XBee-API class to try to run is "OpenCloseConnectionsTest" found in the Test folder.  This provides very detailed debug information that should help with troubleshooting.  If this will run, then everything else should as well.

First error was because the XBee-API POM file did not include a version tag.  My POM now looks like:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>

Next I was missing RxTx files.  On my win10 installation I was missing the following files in the following locations:

...\Program Files\Java\jkd1.6.0_01\jre\bin\rxtxSerial.dll

...\Program Files\Java\jdk1.6.0_01\jre\lib\ext\RXTXcomm.jar

I downloaded these from here. Once I placed these files in these locations, Netbeans found them without further action/config.  I still have a warning because these files aren't quite the same version.

Finally, I needed to edit the source code to set the comm port ID.  In my case, the XBee was on "COM5".

I could not find any single source that has all of the above information.  A lot of information I found was outdated and some was simply wrong.  Hopefully this write-up will help others.

Body:
OK so I am working on an answer to my question.  So in order to get the very latest version 0.9.2 of XBee-API, I need to install a project from the Maven Central Repository into Netbeans.  I found a couple of posts that pointed me here.
I didn't find this useful at all.  The answer might be there somewhere but it assumes a level of understanding of Maven and Ant that I don't have, so I experimented.  I created a new Maven project in Netbeans and then copied the content of the XBee-API POM file I found in Maven Central and pasted that to replace the content of the default POM file in the new Maven project I had created.

My understanding is that Maven will download all the files needed based on the POM file, but it didn't.  Most of the files were downloaded, but not all.  I got the following warnings:

    Some problems were encountered while building the effective model for com.rapplogic:xbee-api:jar:0.9.2
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-gpg-plugin is missing. @ line 60, column 21
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 51, column 21
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-source-plugin is missing. @ line 86, column 21
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-javadoc-plugin is missing. @ line 99, column 21

And also:

Failed to execute goal pl.project13.maven:git-commit-id-plugin:2.2.1:revision (get-the-git-infos) on project xbee-api: The plugin pl.project13.maven:git-commit-id-plugin:2.2.1 requires Maven version [3.1.1,) -> [Help 1]

This might make sense to anyone that knows something about Maven, but that's not me.  It looks like I need to upgrade Maven which is only a couple of months old since that is how long I have been using Java for.

I found that I am already running the latest Maven ver 3.5.0.  The error message says I need 3.1.1 so upgrading Maven isn't possible and downgrading back to 3.1.1 seems like a bad idea.  Time to change tack and look at using a later version of the plugin.

I found others who have had this problem here and here but no solutions.  I found this response here that indicates the problem is that there is no version specified for each plugin in the POM.  So it seems like Apache has changed the rules (requiring a version to be specified in the POM) but haven't provided a tool to update POMs. This seems to be something that could be scanned for and corrected within Maven Central. The POM I am running is only 5 months old and yet it won't build without manual intervention.

To fix the version problem, I had to search Maven Central for each plugin to get the latest/right version number and amend the POM.  How bad is that!!  That process cleared all but one fatal error.  I have now hit an impasse described in the question here

The solution I am going to pursue is to work with the older version of XBee-API from Github.  This gives me the source code and it builds without issue.  I plan to modify this code to use I2C rather than RS232.  There is also beta code for a socket server.


问:
What's the different between supportsAVCaptureSessionPreset and canSetSessionPreset
In AVCaptureDevice, I can use supportsAVCaptureSessionPreset.

In AVCaptureSession, I Can use canSetSessionPreset.

What's the different between them, for they both detect whether a session preset is avaliable.

答:
It has something to do with the device and the session not being in sync. The session may support 4K thinking it is still connected to the old device  but once you connect the input it crashes saying the preset is not supported because the new device is only 720P.  On the other hand going up from 720P to 4k, Setting it to 4K is not allowed without the new input added to the session. It  will cause your preset to remain in 720P. I currently use both but I wonder if I can simply use the device without using the session.

This happens when switching between the back and front iPhone cameras.


问:
How to send image and fields to form via POST
I've a form like this:

```<code><form id="form" action="/post" method="POST" enctype="multipart/form-data">
    <input type="file" name="image" />
    <input type="text" name="name1" />
    <input type="text" name="name2" />
    <textarea name="text"></textarea>
    <input type="text" name="name3" />
</form>
</code>```

And I've a method like this:

```<code>- (void)sendFields {

UIImage *tempImage = imageViewToPost.image;

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:@"http://url/post/"]];

NSString *boundary = @"------------0xKhTmLbOuNdArY";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n%@\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"image\"; filename=\"photo.png\"\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[NSData dataWithData:UIImageJPEGRepresentation(tempImage, 90)]];
[body appendData:[[NSString stringWithFormat:@"\r\n%@\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"name1\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[nameToPost dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"name2\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[priceToPost dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"text\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[commentToPost dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"name3\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[coordsToPost dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
[request setHTTPBody:body];

NSError *error;
NSURLResponse *response;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *aStr = [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease];

NSLog(@"Result: %@", aStr);

[request release];

}
</code>```

It doesn't work. What's wrong here?

Thanks guys.

答:
I would recommend looking at the ASIHTTPRequest library. I have had success posting images and data with it. It's very simple to use and to get setup. Plus, is has a very nice asynchronous model built in.

ASIHTTPRequest

ContentLicense: CC BY-SA 2.5

Body:
I've a form like this:

<form id="form" action="/post" method="POST" enctype="multipart/form-data">
    <input type="file" name="image" />
    <input type="text" name="name1" />
    <input type="text" name="name2" />
    <textarea name="text"></textarea>
    <input type="text" name="name3" />
</form>

And I've a method like this:

- (void)sendFields {

UIImage *tempImage = imageViewToPost.image;

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:@"http://url/post/"]];

NSString *boundary = @"------------0xKhTmLbOuNdArY";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n%@\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"image\"; filename=\"photo.png\"\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[NSData dataWithData:UIImageJPEGRepresentation(tempImage, 90)]];
[body appendData:[[NSString stringWithFormat:@"\r\n%@\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"name1\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[nameToPost dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"name2\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[priceToPost dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"text\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[commentToPost dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"name3\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[coordsToPost dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
[request setHTTPBody:body];

NSError *error;
NSURLResponse *response;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *aStr = [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease];

NSLog(@"Result: %@", aStr);

[request release];

}

It doesn't work. What's wrong here?

Thanks guys.


答:
I have tried to create an empty list and append to it

That is right direction, so you just need to actually code it :)

```<code>cv_list_dic = cv_list()
results = [] # here is your list with results
for cv in cv_list_dic['results']:
    cv_name = cv['name']
    if qq_cv(cv_name):
            cv_versions = (cv['versions'])
            cv_id_list = []
            for cv_ids in cv_versions:
                    ver_id = (cv_ids['id'])
                    cv_id_list.append(ver_id)
            max_id = (max(cv_id_list))
            qq_cv_id = (cv_name, max_id)
            print(qq_cv_id)
            results.append(print(qq_cv_id))
</code>```

Title: python: getting the output from multiple for loops outside of the for loop

Body:
I have tried to create an empty list and append to it

That is right direction, so you just need to actually code it :)

cv_list_dic = cv_list()
results = [] # here is your list with results
for cv in cv_list_dic['results']:
    cv_name = cv['name']
    if qq_cv(cv_name):
            cv_versions = (cv['versions'])
            cv_id_list = []
            for cv_ids in cv_versions:
                    ver_id = (cv_ids['id'])
                    cv_id_list.append(ver_id)
            max_id = (max(cv_id_list))
            qq_cv_id = (cv_name, max_id)
            print(qq_cv_id)
            results.append(print(qq_cv_id))


问:
how to limit seekbar
I'd like to set max and minimum limits of SeekBar to 50 and 20 respectively.

SeekBar has a direct option top provide max value, but how to set its minimum value to 20 rather than 0?

答:
I have answered this question here : How to set seekbar min and max value.

With simple math you can set the min value, the max value and even the step of your seekbar.

Hope this helps !

Title: how to limit seekbar


问:
Is there a way to index an array by enums in Rust?
I want to represent a table of data in the memory like the following:

     | USD | EUR |
-----+-----+-----+
John | 100 | 50  |
-----+-----+-----+
Tom  | 300 | 200 |
-----+-----+-----+
Nick | 200 | 0   |
-----+-----+-----+
```

<p>There is a known set of people, each of them owns some currency.</p>

<p>And I have the following enums:</p>

```enum Person {
    John,
    Tom,
    Nick
}

enum Currency {
    USD,
    EUR
}
```

<p>I'd like to encode this data as 2D array, and it would be cool to be able to index array elements not by <code>usize</code> but by <code>enum</code>. E.g.:</p>

```data[Person::John][Currency::USD] = 100;
```

Is it possible to do with arrays and enums in Rust? Or is there any other data structure that would serve for this?

I am aware of HashMap, but it's not exactly what I want because:

HashMap works on the heap (what makes it much slower than regular stack allocated array)

HashMap gives me no guarantee that item exist. E.g. every time I want to get something I have to unwrap it and handle None case, what is not very handy in comparison with usage of normal array.

This is different from How do I match enum values with an integer? because I am not interested in converting enum to usize; I just want a handy way to access array/map items by enum.

答:
You want a HashMap:

```<code>use std::collections::HashMap;

#[derive(PartialEq, Eq, Hash)]
enum Person {
    John,
    Tom,
    Nick
}

#[derive(PartialEq, Eq, Hash)]
enum Currency {
    USD,
    EUR
}

type Table = HashMap<Person, HashMap<Currency, f32>>;

fn main() {
    let mut table = Table::new();
    let mut currency = HashMap::<Currency, f32>::new();

    currency.insert(Currency::USD, 100_f32);
    table.insert(Person::John, currency);

    println!("{}", table[&Person::John][&Currency::USD]);
}
</code>```

Body:
I want to represent a table of data in the memory like the following:

     | USD | EUR |
-----+-----+-----+
John | 100 | 50  |
-----+-----+-----+
Tom  | 300 | 200 |
-----+-----+-----+
Nick | 200 | 0   |
-----+-----+-----+

There is a known set of people, each of them owns some currency.

And I have the following enums:

enum Person {
    John,
    Tom,
    Nick
}

enum Currency {
    USD,
    EUR
}

I'd like to encode this data as 2D array, and it would be cool to be able to index array elements not by usize but by enum. E.g.:

data[Person::John][Currency::USD] = 100;

Is it possible to do with arrays and enums in Rust? Or is there any other data structure that would serve for this?

I am aware of HashMap, but it's not exactly what I want because:

HashMap works on the heap (what makes it much slower than regular stack allocated array)

HashMap gives me no guarantee that item exist. E.g. every time I want to get something I have to unwrap it and handle None case, what is not very handy in comparison with usage of normal array.

This is different from How do I match enum values with an integer? because I am not interested in converting enum to usize; I just want a handy way to access array/map items by enum.

Body:
You want a HashMap:

use std::collections::HashMap;

#[derive(PartialEq, Eq, Hash)]
enum Person {
    John,
    Tom,
    Nick
}

#[derive(PartialEq, Eq, Hash)]
enum Currency {
    USD,
    EUR
}

type Table = HashMap<Person, HashMap<Currency, f32>>;

fn main() {
    let mut table = Table::new();
    let mut currency = HashMap::<Currency, f32>::new();

    currency.insert(Currency::USD, 100_f32);
    table.insert(Person::John, currency);

    println!("{}", table[&Person::John][&Currency::USD]);
}


问:
Compare strings with trailing spaces in Firebird SQL?
I have an existing database with a table with a string[16] key field.
There are rows whose key ends with a space: "16 ".
I need to allow user to change from "16 " to e.g. "16" but also do a unique key check (i.e. the table does not have already a record with key="16").
I run the following query:

```<code>select * from plu__ where store=100 and plu_num = '16'
</code>```

It returns the row with key="16 "!
How do I check for unique key so that keys with trailing spaces are not included?

EDIT: The DDL and the char_length

```<code>CREATE TABLE PLU__
(
  PLU_NUM Varchar(16),
  CAPTION Varchar(50),
...
</code>```

答:
string[16] - there is no such datatype in Firebird. There are CHAR(16) and VARCHAR(16) (and BLOB SUBTYPE TEXT, but it is improbable here).  So you omit some crucial points about your system. You do not work with Firebird, but with some undisclosed intermediate layer, that is no one knows how opaque or transparent.

I suspect you or your system chose CHAR datatype instead of VARCHAR where all data is right-padded with space to the max. OR maybe the COLLATION of the column/table/database is so that trailing spaces do not matter.

Additionally, you may be just wrong. You claim that the row being Selected does contain the trailing blank, but I do not see it. For example, add CHAR_LENGTH(plu_num) to the columns in your SELECT and see what is there.

Additionally, if plu_num is number - should it not be integer or int64 rather than text?

Bottom of your screenshot shows "(NONE)". I suspect that is the "connection charset". This is allowed for backward compatibility with programs made 20 years ago, but it is quite dangerous today. You have to consult your system documentation, how to set the connection charset to URF-8 or Windows-1250 or something meaningful.

"How do I check for unique key so that keys with trailing spaces are not included?" you do not. You just can not do it reliably, because of different transactions and different programs making simultaneous connections. You would check it, decide you are clear, but right before you would insert your row - some other computer would insert it too. That gap can not be crossed that way, between your two commands of checking and inserting - anyone else can do it too. It is called race conditions.

You have to ask the server to do the checks.

For example, you have to introduce UNIQUE CONSTRAINT on the pair of columns (store, plu_num). That way the server would refuse to store two rows with the same values in those columns, visible in the same transaction.

Additionally, is it even normal to have values with spaces? Convert the field to integer datatype and be safe.
Or if you want to keep it textual and non-numeric you still can

Introduce CHECK CONSTRAINT that trim(plu_num) is not distinct from plu_num (or if plu_num is declared as a NOT NULL column to the server, then trim(plu_num) = plu_num). That way the server would refuse storing any value with spaces before or after the text.

In a case the datatype or the collation of the column makes no difference for comparing texts with and without trailing spaces (and in case you can not change that datatype or collation), you may try adding tokens, like ('+' || trim(plu_num) || '+') = ('+' || plu_num || '+')

Or instead of that CHECK CONSTRAINT, you can have proactively remove those spaces: set new before update or insert TRIGGER on the table, that would do like NEW.plu_num = TRIM(NEW.plu_num)

Documentation:

https://www.firebirdsql.org/refdocs/langrefupd20-distinct.html

http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-tbl.html#fblangref25-ddl-tbl-constraints

http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-tbl.html#fblangref25-ddl-tbl-altradd

http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-trgr.html

http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-datatypes-chartypes.html

Also, via http://www.translate.ru a bit more verbose:

http://firebirdsql.su/doku.php?id=constraint

http://firebirdsql.su/doku.php?id=alter_table

You may also check http://www.firebirdfaq.org/cat3/

Additionally, if you add the constraints onto existing table with non-valid data entered earlier before you introduced those checks, you might trap yourself into "non-restorable backup" situation. You would have to check for it, and sanitize your old data to abide by newly introduced constraints.

Option #4 explained in detail is below. Just this seems be a bad idea of database design! One should not just "let people edit number to remove trailing blanks", one should make the database design so that there would be no any numbers with trailing blank and would be no any way to insert them into the database.

```<code>CREATE TABLE "_NEW_TABLE" (
    ID   INTEGER NOT NULL,
    TXT  VARCHAR(10)
);

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"

ID  TXT CONCATENATION   CHAR_LENGTH
1   1   _1_ 1
2   2   _2_ 1
4   1   _1 _    2
5   2   _2 _    2
7    1  _ 1_    2
8    2  _ 2_    2

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"
where txt = '2'

ID  TXT CONCATENATION   CHAR_LENGTH
2   2   _2_     1
5   2   _2 _    2

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"
where txt || '+' = '2+' -- WARNING - this PROHIBITS index use on txt column, if there is any

ID  TXT CONCATENATION   CHAR_LENGTH
2   2   _2_     1

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"
where txt = '2' and char_length(txt) = char_length('2')
</code>```

Body:
I have an existing database with a table with a string[16] key field.
There are rows whose key ends with a space: "16 ".
I need to allow user to change from "16 " to e.g. "16" but also do a unique key check (i.e. the table does not have already a record with key="16").
I run the following query:

select * from plu__ where store=100 and plu_num = '16'

It returns the row with key="16 "!
How do I check for unique key so that keys with trailing spaces are not included?

EDIT: The DDL and the char_length

CREATE TABLE PLU__
(
  PLU_NUM Varchar(16),
  CAPTION Varchar(50),
...

Body:
string[16] - there is no such datatype in Firebird. There are CHAR(16) and VARCHAR(16) (and BLOB SUBTYPE TEXT, but it is improbable here).  So you omit some crucial points about your system. You do not work with Firebird, but with some undisclosed intermediate layer, that is no one knows how opaque or transparent.

I suspect you or your system chose CHAR datatype instead of VARCHAR where all data is right-padded with space to the max. OR maybe the COLLATION of the column/table/database is so that trailing spaces do not matter.

Additionally, you may be just wrong. You claim that the row being Selected does contain the trailing blank, but I do not see it. For example, add CHAR_LENGTH(plu_num) to the columns in your SELECT and see what is there.

Additionally, if plu_num is number - should it not be integer or int64 rather than text?

Bottom of your screenshot shows "(NONE)". I suspect that is the "connection charset". This is allowed for backward compatibility with programs made 20 years ago, but it is quite dangerous today. You have to consult your system documentation, how to set the connection charset to URF-8 or Windows-1250 or something meaningful.

"How do I check for unique key so that keys with trailing spaces are not included?" you do not. You just can not do it reliably, because of different transactions and different programs making simultaneous connections. You would check it, decide you are clear, but right before you would insert your row - some other computer would insert it too. That gap can not be crossed that way, between your two commands of checking and inserting - anyone else can do it too. It is called race conditions.

You have to ask the server to do the checks.

For example, you have to introduce UNIQUE CONSTRAINT on the pair of columns (store, plu_num). That way the server would refuse to store two rows with the same values in those columns, visible in the same transaction.

Additionally, is it even normal to have values with spaces? Convert the field to integer datatype and be safe.
Or if you want to keep it textual and non-numeric you still can

Introduce CHECK CONSTRAINT that trim(plu_num) is not distinct from plu_num (or if plu_num is declared as a NOT NULL column to the server, then trim(plu_num) = plu_num). That way the server would refuse storing any value with spaces before or after the text.

In a case the datatype or the collation of the column makes no difference for comparing texts with and without trailing spaces (and in case you can not change that datatype or collation), you may try adding tokens, like ('+' || trim(plu_num) || '+') = ('+' || plu_num || '+')

Or instead of that CHECK CONSTRAINT, you can have proactively remove those spaces: set new before update or insert TRIGGER on the table, that would do like NEW.plu_num = TRIM(NEW.plu_num)

Documentation:

https://www.firebirdsql.org/refdocs/langrefupd20-distinct.html

http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-tbl.html#fblangref25-ddl-tbl-constraints

http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-tbl.html#fblangref25-ddl-tbl-altradd

http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-trgr.html

http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-datatypes-chartypes.html

Also, via http://www.translate.ru a bit more verbose:

http://firebirdsql.su/doku.php?id=constraint

http://firebirdsql.su/doku.php?id=alter_table

You may also check http://www.firebirdfaq.org/cat3/

Additionally, if you add the constraints onto existing table with non-valid data entered earlier before you introduced those checks, you might trap yourself into "non-restorable backup" situation. You would have to check for it, and sanitize your old data to abide by newly introduced constraints.

Option #4 explained in detail is below. Just this seems be a bad idea of database design! One should not just "let people edit number to remove trailing blanks", one should make the database design so that there would be no any numbers with trailing blank and would be no any way to insert them into the database.

CREATE TABLE "_NEW_TABLE" (
    ID   INTEGER NOT NULL,
    TXT  VARCHAR(10)
);

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"

ID  TXT CONCATENATION   CHAR_LENGTH
1   1   _1_ 1
2   2   _2_ 1
4   1   _1 _    2
5   2   _2 _    2
7    1  _ 1_    2
8    2  _ 2_    2

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"
where txt = '2'

ID  TXT CONCATENATION   CHAR_LENGTH
2   2   _2_     1
5   2   _2 _    2

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"
where txt || '+' = '2+' -- WARNING - this PROHIBITS index use on txt column, if there is any

ID  TXT CONCATENATION   CHAR_LENGTH
2   2   _2_     1

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"
where txt = '2' and char_length(txt) = char_length('2')


问:
Codility MinAbsSum
I tried this Codility test: MinAbsSum.
https://codility.com/programmers/lessons/17-dynamic_programming/min_abs_sum/

I solved the problem by searching the whole tree of possibilities. The results were OK, however, my solution failed due to timeout for large input. In other words the time complexity was not as good as expected. My solution is O(nlogn), something normal with trees. But this coding test was in the section "Dynamic Programming", and there must be some way to improve it. I tried with summing the whole set first and then using this information, but always there is something missing in my solution. Does anybody have an idea on how to improve my solution using DP?

```<code>#include <vector>
using namespace std;

int sum(vector<int>& A, size_t i, int s)
{
   if (i == A.size())
      return s;

   int tmpl = s + A[i];
   int tmpr = s - A[i];
   return min (abs(sum(A, i+1, tmpl)), abs(sum(A, i+1, tmpr)));
}

int solution(vector<int> &A) {
   return sum(A, 0, 0);
}
</code>```

答:
I invented another solution, better than the previous one. I do not use recursion any more.
This solution works OK (all logical tests passed), and also passed some of the performance tests, but not all. How else can I improve it?</p>

```<code>#include <vector>
#include <set>
using namespace std;

int solution(vector<int> &A) {
    if (A.size() == 0) return 0;

    set<int> sums, tmpSums;
    sums.insert(abs(A[0]));
    for (auto it = begin(A) + 1; it != end(A); ++it)
    {
        for (auto s : sums)
        {
            tmpSums.insert(abs(s + abs(*it)));
            tmpSums.insert(abs(s - abs(*it)));
        }
        sums = tmpSums;
        tmpSums.clear();
    }

    return *sums.begin();
}
</code>```

Title: Codility MinAbsSum

Body:
I tried this Codility test: MinAbsSum.
https://codility.com/programmers/lessons/17-dynamic_programming/min_abs_sum/

I solved the problem by searching the whole tree of possibilities. The results were OK, however, my solution failed due to timeout for large input. In other words the time complexity was not as good as expected. My solution is O(nlogn), something normal with trees. But this coding test was in the section "Dynamic Programming", and there must be some way to improve it. I tried with summing the whole set first and then using this information, but always there is something missing in my solution. Does anybody have an idea on how to improve my solution using DP?

#include <vector>
using namespace std;

int sum(vector<int>& A, size_t i, int s)
{
   if (i == A.size())
      return s;

   int tmpl = s + A[i];
   int tmpr = s - A[i];
   return min (abs(sum(A, i+1, tmpl)), abs(sum(A, i+1, tmpr)));
}

int solution(vector<int> &A) {
   return sum(A, 0, 0);
}

Body:
I invented another solution, better than the previous one. I do not use recursion any more.
This solution works OK (all logical tests passed), and also passed some of the performance tests, but not all. How else can I improve it?

#include <vector>
#include <set>
using namespace std;

int solution(vector<int> &A) {
    if (A.size() == 0) return 0;

    set<int> sums, tmpSums;
    sums.insert(abs(A[0]));
    for (auto it = begin(A) + 1; it != end(A); ++it)
    {
        for (auto s : sums)
        {
            tmpSums.insert(abs(s + abs(*it)));
            tmpSums.insert(abs(s - abs(*it)));
        }
        sums = tmpSums;
        tmpSums.clear();
    }

    return *sums.begin();
}


问:
How can I add user input to a checklist, but then place it in a label?
I would like to add user input to a list, which contains a label, which contains an input of type "checkbox"?

I have seen other questions, and used their code, but they don't work. Nothing happens when I click "Add".

Here is the JavaScript I found on W3Schools and in a similar question to my own, as well as the W3Schools link:

https://www.w3schools.com/jsref/met_node_insertbefore.asp

```<code>function addToList() {
    var li = document.createElement("LI");
    var userInput = document.getElementById("userInput").value;
    var text = document.createTextNode(userInput);
    li.appendChild(text);
}
</code>```

I think I understand that using this code I am not going to be able to place the user input inside of the input tag, followed by the label, so I would like to know if there is a way to do that.

Here is my JavaScript if you would like to see it:

```<code>function addToList() {
    var li = document.createElement("LI");
    var userInput = document.getElementById("userInput").value;
    var text = document.createTextNode(userInput);
    li.appendChild(text);

    var list = document.getElementById("cntr_List");
    list.insertBefore(li, list.childNodes[0]);
}
</code>```

Here is the list itself (HTML of course) along with the input for text:

```<code><div class="center" id="cntr">
    <div class="header">
        <h2>Add an item</h2>
        <input type="text" id="userInput" style="width: 100%;" placeholder = "Add new task...">
            <span onclick="addToList()" style="cursor: pointer;" id="addBtn" >Add</span>
        </div>
        <ol style="list-style-type:none" id="cntr_list">
            <li><label onclick="openNav()"><input type="checkbox" value="ON" class="test" /> Item 1</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 2</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 3</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 4</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 5</label></li>
        </ol>
</div>
</code>```

If what I am doing is not feasible or bad HTML/JavaScript, please forgive me, for I am still learning. I am more than open to any suggestions you have that will give me the same or similar results. If there's no way to accomplish what I am attempting to achieve, feel free to say so, and tell me why.

答:
Try this :

function addToList() {
  // Create you "li" element
  var li = document.createElement('li');

  // Create your label and insert it inside your li
  var label = document.createElement('label');
  li.appendChild(label);

  // Create your checkbox and insert it inside your label
  var checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  checkbox.classList.add('test');
  checkbox.value = 'ON';
  label.appendChild(checkbox);

  // Get the input value, and insert it inside your label
  var userInput = document.getElementById("userInput").value;
  var text = document.createTextNode(userInput);
  label.appendChild(text);

  // And finally append it to your list.
  // There was a typo here : 'cntr_list' was 'cntr_List', beware as JavaScript is case-sensitive.
  var list = document.getElementById('cntr_list');
  list.insertBefore(li, list.childNodes[0]);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="center" id="cntr">
  <div class="header">
    <h2>Add an item</h2>
    <input type="text" id="userInput" style="width: 100%;" placeholder="Add new task...">
    <span onclick="addToList()" style="cursor: pointer;" id="addBtn">Add</span>
  </div>
  <ol style="list-style-type:none" id="cntr_list">
    <li><label onclick="openNav()"><input type="checkbox" value="ON" class="test" /> Item 1</label></li>
    <li><label><input type="checkbox" value="ON" class="test" /> Item 2</label></li>
    <li><label><input type="checkbox" value="ON" class="test" /> Item 3</label></li>
    <li><label><input type="checkbox" value="ON" class="test" /> Item 4</label></li>
    <li><label><input type="checkbox" value="ON" class="test" /> Item 5</label></li>
  </ol>
</div></code>```

Body:
I would like to add user input to a list, which contains a label, which contains an input of type "checkbox"?

I have seen other questions, and used their code, but they don't work. Nothing happens when I click "Add".

Here is the JavaScript I found on W3Schools and in a similar question to my own, as well as the W3Schools link:

https://www.w3schools.com/jsref/met_node_insertbefore.asp

function addToList() {
    var li = document.createElement("LI");
    var userInput = document.getElementById("userInput").value;
    var text = document.createTextNode(userInput);
    li.appendChild(text);
}

I think I understand that using this code I am not going to be able to place the user input inside of the input tag, followed by the label, so I would like to know if there is a way to do that.

Here is my JavaScript if you would like to see it:

function addToList() {
    var li = document.createElement("LI");
    var userInput = document.getElementById("userInput").value;
    var text = document.createTextNode(userInput);
    li.appendChild(text);

    var list = document.getElementById("cntr_List");
    list.insertBefore(li, list.childNodes[0]);
}

Here is the list itself (HTML of course) along with the input for text:

Add an item

        <input type="text" id="userInput" style="width: 100%;" placeholder = "Add new task...">
            Add

<input type="checkbox" value="ON" class="test" /> Item 1

<input type="checkbox" value="ON" class="test" /> Item 2

<input type="checkbox" value="ON" class="test" /> Item 3

<input type="checkbox" value="ON" class="test" /> Item 4

<input type="checkbox" value="ON" class="test" /> Item 5

If what I am doing is not feasible or bad HTML/JavaScript, please forgive me, for I am still learning. I am more than open to any suggestions you have that will give me the same or similar results. If there's no way to accomplish what I am attempting to achieve, feel free to say so, and tell me why.

Body:
Try this :

function addToList() {
  // Create you "li" element
  var li = document.createElement('li');

  // Create your label and insert it inside your li
  var label = document.createElement('label');
  li.appendChild(label);

  // Create your checkbox and insert it inside your label
  var checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  checkbox.classList.add('test');
  checkbox.value = 'ON';
  label.appendChild(checkbox);

  // Get the input value, and insert it inside your label
  var userInput = document.getElementById("userInput").value;
  var text = document.createTextNode(userInput);
  label.appendChild(text);

  // And finally append it to your list.
  // There was a typo here : 'cntr_list' was 'cntr_List', beware as JavaScript is case-sensitive.
  var list = document.getElementById('cntr_list');
  list.insertBefore(li, list.childNodes[0]);
}

<div class="center" id="cntr">
  <div class="header">
    <h2>Add an item</h2>
    <input type="text" id="userInput" style="width: 100%;" placeholder="Add new task...">
    <span onclick="addToList()" style="cursor: pointer;" id="addBtn">Add</span>
  </div>
  <ol style="list-style-type:none" id="cntr_list">
    <li><label onclick="openNav()"><input type="checkbox" value="ON" class="test" /> Item 1</label></li>
    <li><label><input type="checkbox" value="ON" class="test" /> Item 2</label></li>
    <li><label><input type="checkbox" value="ON" class="test" /> Item 3</label></li>
    <li><label><input type="checkbox" value="ON" class="test" /> Item 4</label></li>
    <li><label><input type="checkbox" value="ON" class="test" /> Item 5</label></li>
  </ol>
</div>


问:
Swift - Replace extra line breaks in server generated CSV file
I have created a statistics controller for administrators to export back-end information from a database. The controller has several fields with UIPickers to filter data and a button to send a request to the server, where the API (written in C#) takes care of the export.

The data is currently being exported to a CSV and added back to my controller. The problem is that the attached file contains one extra line break after every line of data. The CSV looks perfect on the Windows machine, though.

If this a Windows / Unix problem where line breaks are handled differently, what can I do to fix this? I want all those extra lines to be gone before the user actually opens the file as a spreadsheet.

On my windows machine

```<code>Created by: ""
Created on: ""

Name,Date,Score
Jack Sparrow,2017-07-03-14:48:58,80
Jack Sparrow,2017-07-03-14:49:33,100
</code>```

On my Mac and iPhone

```<code>Created by: ""

Created on: ""

Name,Date,Score

Jack Sparrow,2017-07-03-14:48:58,80

Jack Sparrow,2017-07-03-14:49:33,100
</code>```

答:
If you want to fix this quick on Mac/iOS client and you don't care about performance that much you could just reconstruct the file by deleting extra new lines. The next approach should work fine and relatively fast if you don't have files with a lot of lines (>500 as a wild guess).

Read file into string:

```<code>let fileStr = String.init(contentsOf: yourFileURL)
</code>```

Get line components:

```<code>let comps = fileStr.components(separatedBy: CharacterSet.newlines)
</code>```

components:separatedBy will give you empty strings for new lines. Filter out empty strings (in this example all of them, but you can do whatever you need):

```<code>let fiteredComps = comps.filter { !$0.isEmpty }
</code>```

Recompose you string with the necessary new line characters:

```<code>var recomposedString = ""
for str in filteredComps {
    recomposedString += str
    recomposedString += "\n" // or whatever character you need
}
</code>```

Or check out much shorter answer of the4kman :)

Body:
I have created a statistics controller for administrators to export back-end information from a database. The controller has several fields with UIPickers to filter data and a button to send a request to the server, where the API (written in C#) takes care of the export.

The data is currently being exported to a CSV and added back to my controller. The problem is that the attached file contains one extra line break after every line of data. The CSV looks perfect on the Windows machine, though.

If this a Windows / Unix problem where line breaks are handled differently, what can I do to fix this? I want all those extra lines to be gone before the user actually opens the file as a spreadsheet.

On my windows machine

Created by: ""
Created on: ""

Name,Date,Score
Jack Sparrow,2017-07-03-14:48:58,80
Jack Sparrow,2017-07-03-14:49:33,100

On my Mac and iPhone

Created by: ""

Created on: ""

Name,Date,Score

Jack Sparrow,2017-07-03-14:48:58,80

Jack Sparrow,2017-07-03-14:49:33,100

Body:
If you want to fix this quick on Mac/iOS client and you don't care about performance that much you could just reconstruct the file by deleting extra new lines. The next approach should work fine and relatively fast if you don't have files with a lot of lines (>500 as a wild guess).

Read file into string:

let fileStr = String.init(contentsOf: yourFileURL)

Get line components:

let comps = fileStr.components(separatedBy: CharacterSet.newlines)

components:separatedBy will give you empty strings for new lines. Filter out empty strings (in this example all of them, but you can do whatever you need):

let fiteredComps = comps.filter { !$0.isEmpty }

Recompose you string with the necessary new line characters:

var recomposedString = ""
for str in filteredComps {
    recomposedString += str
    recomposedString += "\n" // or whatever character you need
}

Or check out much shorter answer of the4kman :)


问:
restrict 1 word as case sensitive and other as case insensitive in python regex | (pipe)
I got the meaning of | (pipe special character) in regex, Python.
It matches either 1st or 2nd.

ex : a|b  Matches either a or b.

My question:
What if I want to match is a with case sensitive  and b with case insensitive in above example?

ex:

```<code>s = "Welcome to PuNe, Maharashtra"

result1 = re.search("punnee|MaHaRaShTrA",s)
result2 = re.search("pune|maharashtra",s)
result3 = re.search("PuNe|MaHaRaShTrA",s)
result4 = re.search("P|MaHaRaShTrA",s)
</code>```

I want to search Pune in the way I have written in above statement s i.e PuNe. But I have to search Maharashtra by ignoring case. How can I search 1 word with case sensitive and other with case insensitive? So that, result1, result2, result3, result4 will give not null value.

I tried:

```<code>result1 = re.search("pune|MaHaRaShTrA",s1, re.IGNORECASE)
</code>```

But this ignores the cases for both the words.

How can I restrict 1 word as case sensitive and other as case insensitive?

答:
You could generate the lower/upper case regex for the second word, and keep casing active:

```<code>my_regex = "PuNe|"+"".join("[{}{}]".format(x.upper(),x.lower()) for x in "MaHaRaShTrA")
</code>```

that generates: PuNe|[Mm][Aa][Hh][Aa][Rr][Aa][Ss][Hh][Tt][Rr][Aa]

and re.search(my_regex,s1) without any option does what you want.

Body:
I got the meaning of | (pipe special character) in regex, Python.
It matches either 1st or 2nd.

ex : a|b  Matches either a or b.

My question:
What if I want to match is a with case sensitive  and b with case insensitive in above example?

ex:

s = "Welcome to PuNe, Maharashtra"

result1 = re.search("punnee|MaHaRaShTrA",s)
result2 = re.search("pune|maharashtra",s)
result3 = re.search("PuNe|MaHaRaShTrA",s)
result4 = re.search("P|MaHaRaShTrA",s)

I want to search Pune in the way I have written in above statement s i.e PuNe. But I have to search Maharashtra by ignoring case. How can I search 1 word with case sensitive and other with case insensitive? So that, result1, result2, result3, result4 will give not null value.

I tried:

result1 = re.search("pune|MaHaRaShTrA",s1, re.IGNORECASE)

But this ignores the cases for both the words.

How can I restrict 1 word as case sensitive and other as case insensitive?

Body:
You could generate the lower/upper case regex for the second word, and keep casing active:

my_regex = "PuNe|"+"".join("[{}{}]".format(x.upper(),x.lower()) for x in "MaHaRaShTrA")

that generates: PuNe|[Mm][Aa][Hh][Aa][Rr][Aa][Ss][Hh][Tt][Rr][Aa]

and re.search(my_regex,s1) without any option does what you want.


问:
:app:transformClassWithDexFor Debug failed error in react native
Issues during running react native app.

It shows following error:

:app:transformClassWithDexFor Debug failed error in react native

Please give solution to fix it.
Thanks

答:
From your project directory

```<code>cd android
</code>```

from cmd as  admin run

```<code>gradlew clean
</code>```

then you can install app using react-native run-android

Body:
From your project directory

cd android

from cmd as  admin run

gradlew clean

then you can install app using react-native run-android


问:
Split html by element and class
I have a Javascript HTML string as follows,

```<code>var stringCheck = 'Test<a href="http://testdomain.com?data=new" target="_blank">partial string data</a> Test Data<span class="spanClass">XYZ</span>';
</code>```

Now would like to split this string such that, in one variable I do have value as

```<code>var split1 = 'Test<a href="http://testdomain.com?data=new" target="_blank">partial string data</a> Test Data';
</code>```

and second variable would be as follows,

```<code>var split2 = '<span class="spanClass">XYZ</span>';
</code>```

I would like to split the span element which has class of spanClass. Does anyone has idea how I can make it by use of RegEx or another way?

答:
To achieve this you can split by the space before the  using a regular expression, like this:

var stringCheck = 'Testpartial string data Test Data XYZ';

var arr = stringCheck.split(/\s(?=<span)/i);
console.log(arr);```

Title: Split html by element and class

Body:
I have a Javascript HTML string as follows,

var stringCheck = 'Testpartial string data Test DataXYZ';

Now would like to split this string such that, in one variable I do have value as

var split1 = 'Testpartial string data Test Data';

and second variable would be as follows,

var split2 = 'XYZ';

I would like to split the span element which has class of spanClass. Does anyone has idea how I can make it by use of RegEx or another way?

Body:
To achieve this you can split by the space before the <span> using a regular expression, like this:

var stringCheck = 'Test<a href="http://testdomain.com?data=new" target="_blank">partial string data</a> Test Data <span class="spanClass">XYZ</span>';

var arr = stringCheck.split(/\s(?=<span)/i);
console.log(arr);


问:
What should be the permissions for folders under html directory for web?
This is related to linux web directory structure and more specifically amazon EC2 server. The default directory is /var/www/html and I have put my website's folder into this directory. But before uploading them to server using FileZilla, I got this error:

Permission Denied.

To solve this I gave 777 permission to HTML folder and everything worked. But this isn't safe. I don't know what permission should I give to HTML folder and what permissions should for my custom web folder and files.

Here's my folder structure

/var/www/html/chat

```<code>node_modules
config
controllers
public
..css
..js
..images
..img
app.js
index.html
login.html
</code>```

This is a NodeJs web app. So what should be the permissions?

答:
Basically file permissions for /var/html/www would belong to root user.As you are uploading files from filezilla,you will treated as home user as ec2-user.So you are getting Permissions denied error.you can do two things

1.upload your files in your  user home directory i.e ec2-user.OR

2.add the ec2-user(as it is the default username for amazon AMI) to root group useful-link and upload to /var/html/www/ with drwxrwxr-x (775) permissions.

Body:
This is related to linux web directory structure and more specifically amazon EC2 server. The default directory is /var/www/html and I have put my website's folder into this directory. But before uploading them to server using FileZilla, I got this error:

Permission Denied.

To solve this I gave 777 permission to HTML folder and everything worked. But this isn't safe. I don't know what permission should I give to HTML folder and what permissions should for my custom web folder and files.

Here's my folder structure

/var/www/html/chat

node_modules
config
controllers
public
..css
..js
..images
..img
app.js
index.html
login.html

This is a NodeJs web app. So what should be the permissions?


问:
Is it possible to generate PDF using jQuery?
I am using Ajax functionality to retrieve my content and I need to export PDF on success of jQuery.ajax(). How can I do that?

答:
If at all possible, the server-side is a better choice for generating PDFs. It's probably going to be faster for most users and returning a file via standard HTTP request is much more robust than the current client-side options.

That said, this library will generate a PDF on the client-side: http://snapshotmedia.co.uk/blog/jspdf

In browsers that support data URIs, it can return the PDF directly.  In other browsers, you can couple it with a Flash component called Downloadify to accomplish the same.


问:
Laravel 5.1 group routes for specific domains and all subdomains
So I have a project with multiple domains pointing to it. Now I want to group routes by domains and subdomains.

For example I want to have separate routes for example.com and every subdomain of example.com

I do this right now like this:

```<code>$RoutesOnlyForExamp = function() {
  Route::get('/', ['as' => 'home', 'uses' => 'TestController@home']);
};

Route::group(['domain' => 'sub1.example.com'], $RoutesOnlyForExamp);
Route::group(['domain' => 'sub2.example.com'], $RoutesOnlyForExamp);
Route::group(['domain' => 'example.com'], $RoutesOnlyForExamp);
</code>```

The home() method would give me this:

```<code>return view('home')
</code>```

Now I have a weired problem. I have some links in my view which all lead into a

```<code>return view('RANDOM_VIEW');
</code>```

like the home() method.

The links in the view are generated like this:

```<code><a href="{{route('ROUTENAME')}}">LINKNAME</a>
</code>```

Now let's say I access the site via sub1.example.com. Now some of my links look right, like this:

```<code><a href="sub1.example.com/slug">Random Link 1</a>
</code>```

But some look like this, which is wrong because I am on sub1.example.com and not example.com:

```<code><a href="example.com/slug">Random Link 1</a>
</code>```

And I don't see any pattern when and why it takes the wrong domain. My goal is that if I access the site via sub1.example.com all links should take this and not just example.com.

I hope the problem is clear. Otherwise I can try it with more detail.

I appreciate any help and thank you in advance!

答:
You can accept the subdomain name like

```<code>Route::group(['domain' => '{subdomain}.example.com'], $RoutesOnlyForExamp);
</code>```

and have it available as a variable and route parameter.

When you want to generate a link to a subdomain route you can do route('ROUTENAME', [$subdomain]).

Your main website routes are going to work as expected if declared like this:

```<code>Route::group(['domain' => 'example.com'], $RoutesOnlyForExamp);
</code>```

Body:
So I have a project with multiple domains pointing to it. Now I want to group routes by domains and subdomains.

For example I want to have separate routes for example.com and every subdomain of example.com

I do this right now like this:

$RoutesOnlyForExamp = function() {
  Route::get('/', ['as' => 'home', 'uses' => 'TestController@home']);
};

Route::group(['domain' => 'sub1.example.com'], $RoutesOnlyForExamp);
Route::group(['domain' => 'sub2.example.com'], $RoutesOnlyForExamp);
Route::group(['domain' => 'example.com'], $RoutesOnlyForExamp);

The home() method would give me this:

return view('home')

Now I have a weired problem. I have some links in my view which all lead into a

return view('RANDOM_VIEW');

like the home() method.

The links in the view are generated like this:

LINKNAME

Now let's say I access the site via sub1.example.com. Now some of my links look right, like this:

Random Link 1

But some look like this, which is wrong because I am on sub1.example.com and not example.com:

Random Link 1

And I don't see any pattern when and why it takes the wrong domain. My goal is that if I access the site via sub1.example.com all links should take this and not just example.com.

I hope the problem is clear. Otherwise I can try it with more detail.

I appreciate any help and thank you in advance!

Body:
You can accept the subdomain name like

Route::group(['domain' => '{subdomain}.example.com'], $RoutesOnlyForExamp);

and have it available as a variable and route parameter.

When you want to generate a link to a subdomain route you can do route('ROUTENAME', [$subdomain]).

Your main website routes are going to work as expected if declared like this:

Route::group(['domain' => 'example.com'], $RoutesOnlyForExamp);


问:
Hide divs on click - multiple boxes
I have a bit long info submission form. I have an option that someone click "add another", there is a notification box display with text like "Success!" like that with close button. Please check this image.

Therefore I have three "add another" buttons and three success alerts. When someone click close, that alert message needs to be disappear.

The problem

I used javascript for that success box. It does these things.

Click "Add another" button, appears success box.
 Click close button on
  success box, box disappears.

Here is my code.

document.querySelector(".add-box").addEventListener("click", function() {
  document.querySelector(".add-box-wrap").style.display = "inline-block";
});

document.querySelector(".add-box1").addEventListener("click", function() {
  document.querySelector(".add-box-wrap1").style.display = "inline-block";
});

document.querySelector(".add-box2").addEventListener("click", function() {
  document.querySelector(".add-box-wrap2").style.display = "inline-block";
});

$(".claim-btn-close").click(function() {
  $(".add-box-wrap").hide();
});

$(".claim-btn-close1").click(function() {
  $(".add-box-wrap1").hide();
});

$(".claim-btn-close2").click(function() {
  $(".add-box-wrap2").hide();
});

function hide(target) {
  document.getElementsByClassName(target).style.display = 'none';
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--Success form-->
<div class="add-box-wrap">
  <div class="claim-btn-close" onclick="hide('.claim-btn-close')">
    <i class="fa fa-times" aria-hidden="true"></i>
  </div>
  Success!
</div>

<!--Add another button -->
<div class="col-lg-10 col-md-10 col-sm-12 no-padding">
  Add another<i class="fa fa-plus"></i>
</div></code>```

See.. there is a major problem with code repeating. (I didn't repeat html codes, just post here one example) I would like to know the best practice to achieve things like this.

答:
For displaying the notification box without repeating the code, one of the way is you could make use of data attributes. Change the data attribute for all the buttons and let the class .add-box be the same. like so:

```<code><div class="add-box-wrap1" style="display: none;">
  <div class="claim-btn-close">
    <i class="fa fa-times" aria-hidden="true"></i>
  </div>
  <a href="" class="btn btn-primary claim-btn">Success!</a>
</div>
<div class="add-box-wrap2" style="display: none;">
  <div class="claim-btn-close">
    <i class="fa fa-times" aria-hidden="true"></i>
  </div>
  <a href="" class="btn btn-primary claim-btn">Success!</a>
</div>

<!--Add another button -->
<div class="col-lg-10 col-md-10 col-sm-12 no-padding">
  <a class="add-box" data-target="1">Add another<i class="fa fa-plus"></i></a>
</div>

<!--Add another button -->
<div class="col-lg-10 col-md-10 col-sm-12 no-padding">
  <a class="add-box" data-target="2">Add another<i class="fa fa-plus"></i></a>
</div>
</code>```

And change your Jquery to just one function.

```<code>$(".add-box").click(function() {
  $(".add-box-wrap" + $(this).data('target')).show(); //.add-box-wrap1 or .add-box-wrap2
});
</code>```

Explanation of the above line: It just means we are getting the value of the "clicked" button's data-target value(which is 1 or 2) AND appending that value to the "add-box-wrap"(which will be add-box-wrap1 or add-box-wrap2) to search for that element to display it using .show().

Using show() or .css jquery functions is upto you. But I suggest not to mix both vanilla JS and JQuery codes(like in your question).

Closing

You can simply use closest or parent, like so:

```<code>$(".claim-btn-close").click(function(){
    $(this).parent().hide();
});
</code>```

$(".add-box").click(function() {
  $(".add-box-wrap" + $(this).data('target')).show();
});

$(".claim-btn-close").click(function(){
    $(this).parent().hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-box-wrap1" style="display: none;">
  <div class="claim-btn-close">
    <i class="fa fa-times" aria-hidden="true"></i>
  </div>
  Success!
</div>
<div class="add-box-wrap2" style="display: none;">
  <div class="claim-btn-close">
    <i class="fa fa-times" aria-hidden="true"></i>
  </div>
  Success!
</div>

<!--Add another button -->
<div class="col-lg-10 col-md-10 col-sm-12 no-padding">
  Add another<i class="fa fa-plus"></i>
</div>

<!--Add another button -->
<div class="col-lg-10 col-md-10 col-sm-12 no-padding">
  Add another<i class="fa fa-plus"></i>
</div></code>```

Update on another question(3 column):

Using bootstrap, you can wrap the add-box-wrap divs within a .row and give each of it a class like col-*-4(class="col-xs-4 col-md-4 col-lg-4") assuming you have 3 success buttons(12/3 = 4). So the first part of your html would become

```<code><div class="row">
  <div class="add-box-wrap1 col-md-4 col-lg-4" style="display: none;">
    <div class="claim-btn-close">
      <i class="fa fa-times" aria-hidden="true"></i>
    </div>
    <a href="" class="btn btn-primary claim-btn">Success!</a>
  </div>
  <div class="add-box-wrap2 col-md-4 col-lg-4" style="display: none;">
    <div class="claim-btn-close">
      <i class="fa fa-times" aria-hidden="true"></i>
    </div>
    <a href="" class="btn btn-primary claim-btn">Success!</a>
  </div>
  <div class="add-box-wrap3 col-md-4 col-lg-4" style="display: none;">
    <div class="claim-btn-close">
      <i class="fa fa-times" aria-hidden="true"></i>
    </div>
    <a href="" class="btn btn-primary claim-btn">Success!</a>
  </div>
</div>
</code>```

Title: Hide divs on click - multiple boxes

Body:
I have a bit long info submission form. I have an option that someone click "add another", there is a notification box display with text like "Success!" like that with close button. Please check this image.

Therefore I have three "add another" buttons and three success alerts. When someone click close, that alert message needs to be disappear.

The problem

I used javascript for that success box. It does these things.

Click "Add another" button, appears success box.
 Click close button on
  success box, box disappears.

Here is my code.

document.querySelector(".add-box").addEventListener("click", function() {
  document.querySelector(".add-box-wrap").style.display = "inline-block";
});

document.querySelector(".add-box1").addEventListener("click", function() {
  document.querySelector(".add-box-wrap1").style.display = "inline-block";
});

document.querySelector(".add-box2").addEventListener("click", function() {
  document.querySelector(".add-box-wrap2").style.display = "inline-block";
});

$(".claim-btn-close").click(function() {
  $(".add-box-wrap").hide();
});

$(".claim-btn-close1").click(function() {
  $(".add-box-wrap1").hide();
});

$(".claim-btn-close2").click(function() {
  $(".add-box-wrap2").hide();
});

function hide(target) {
  document.getElementsByClassName(target).style.display = 'none';
};

  Success!

  Add another

See.. there is a major problem with code repeating. (I didn't repeat html codes, just post here one example) I would like to know the best practice to achieve things like this.

Body:
For displaying the notification box without repeating the code, one of the way is you could make use of data attributes. Change the data attribute for all the buttons and let the class .add-box be the same. like so:

<div class="add-box-wrap1" style="display: none;">
  <div class="claim-btn-close">
    <i class="fa fa-times" aria-hidden="true"></i>
  </div>
  <a href="" class="btn btn-primary claim-btn">Success!</a>
</div>
<div class="add-box-wrap2" style="display: none;">
  <div class="claim-btn-close">
    <i class="fa fa-times" aria-hidden="true"></i>
  </div>
  <a href="" class="btn btn-primary claim-btn">Success!</a>
</div>

<!--Add another button -->
<div class="col-lg-10 col-md-10 col-sm-12 no-padding">
  <a class="add-box" data-target="1">Add another<i class="fa fa-plus"></i></a>
</div>

<!--Add another button -->
<div class="col-lg-10 col-md-10 col-sm-12 no-padding">
  <a class="add-box" data-target="2">Add another<i class="fa fa-plus"></i></a>
</div>

And change your Jquery to just one function.

$(".add-box").click(function() {
  $(".add-box-wrap" + $(this).data('target')).show(); //.add-box-wrap1 or .add-box-wrap2
});

Explanation of the above line: It just means we are getting the value of the "clicked" button's data-target value(which is 1 or 2) AND appending that value to the "add-box-wrap"(which will be add-box-wrap1 or add-box-wrap2) to search for that element to display it using .show().

Using show() or .css jquery functions is upto you. But I suggest not to mix both vanilla JS and JQuery codes(like in your question).

Closing

You can simply use closest or parent, like so:

$(".claim-btn-close").click(function(){
    $(this).parent().hide();
});

$(".add-box").click(function() {
  $(".add-box-wrap" + $(this).data('target')).show();
});

$(".claim-btn-close").click(function(){
    $(this).parent().hide();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-box-wrap1" style="display: none;">
  <div class="claim-btn-close">
    <i class="fa fa-times" aria-hidden="true"></i>
  </div>
  <a href="" class="btn btn-primary claim-btn">Success!</a>
</div>
<div class="add-box-wrap2" style="display: none;">
  <div class="claim-btn-close">
    <i class="fa fa-times" aria-hidden="true"></i>
  </div>
  <a href="" class="btn btn-primary claim-btn">Success!</a>
</div>

<!--Add another button -->
<div class="col-lg-10 col-md-10 col-sm-12 no-padding">
  <a class="add-box" data-target="1">Add another<i class="fa fa-plus"></i></a>
</div>

<!--Add another button -->
<div class="col-lg-10 col-md-10 col-sm-12 no-padding">
  <a class="add-box" data-target="2">Add another<i class="fa fa-plus"></i></a>
</div>

Update on another question(3 column):

Using bootstrap, you can wrap the add-box-wrap divs within a .row and give each of it a class like col-*-4(class="col-xs-4 col-md-4 col-lg-4") assuming you have 3 success buttons(12/3 = 4). So the first part of your html would become

<div class="row">
  <div class="add-box-wrap1 col-md-4 col-lg-4" style="display: none;">
    <div class="claim-btn-close">
      <i class="fa fa-times" aria-hidden="true"></i>
    </div>
    <a href="" class="btn btn-primary claim-btn">Success!</a>
  </div>
  <div class="add-box-wrap2 col-md-4 col-lg-4" style="display: none;">
    <div class="claim-btn-close">
      <i class="fa fa-times" aria-hidden="true"></i>
    </div>
    <a href="" class="btn btn-primary claim-btn">Success!</a>
  </div>
  <div class="add-box-wrap3 col-md-4 col-lg-4" style="display: none;">
    <div class="claim-btn-close">
      <i class="fa fa-times" aria-hidden="true"></i>
    </div>
    <a href="" class="btn btn-primary claim-btn">Success!</a>
  </div>
</div>


问:
rbenv can't change global ruby version
My Mac OS X has a default ruby.

```<code>$ ruby -v
ruby 2.0.0p451 (2014-02-24 revision 45167) [universal.x86_64-darwin13]
</code>```

I installed rbenv and ruby version 2.1.2.

```<code>$ rbenv versions
  system
* 2.1.2 (set by /Users/sdw/.rbenv/version)
</code>```

and I tried to set the global ruby version to 2.1.2, but nothing happened.

```<code>$ rbenv global 2.1.2
$ ruby -v
ruby 2.0.0p451 (2014-02-24 revision 45167) [universal.x86_64-darwin13]
</code>```

So I tried to do the same thing with command sudo, but the result is the same.

```<code>$ sudo rbenv global 2.1.2
$ ruby -v
ruby 2.0.0p451 (2014-02-24 revision 45167) [universal.x86_64-darwin13]
</code>```

How can I change my global ruby version to 2.1.2? I never installed rvm or other ruby version managing system.

答:
Uninstall ruby and then install agains:

```<code>brew uninstall -f ruby
brew install ruby
</code>```

Add this two line to you ~/.bash_profile

```<code>export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
</code>```

Reopen the console and that's it and run

```<code>ruby -v
</code>```

Title: rbenv can't change global ruby version

Body:
My Mac OS X has a default ruby.

$ ruby -v
ruby 2.0.0p451 (2014-02-24 revision 45167) [universal.x86_64-darwin13]

I installed rbenv and ruby version 2.1.2.

$ rbenv versions
  system
* 2.1.2 (set by /Users/sdw/.rbenv/version)

and I tried to set the global ruby version to 2.1.2, but nothing happened.

$ rbenv global 2.1.2
$ ruby -v
ruby 2.0.0p451 (2014-02-24 revision 45167) [universal.x86_64-darwin13]

So I tried to do the same thing with command sudo, but the result is the same.

$ sudo rbenv global 2.1.2
$ ruby -v
ruby 2.0.0p451 (2014-02-24 revision 45167) [universal.x86_64-darwin13]

How can I change my global ruby version to 2.1.2? I never installed rvm or other ruby version managing system.

Body:
Uninstall ruby and then install agains:

brew uninstall -f ruby
brew install ruby

Add this two line to you ~/.bash_profile

export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

Reopen the console and that's it and run

ruby -v