问:
Delete Query Inside While Loop
i'm trying to delete database record inside a while loop. I'm showing my user list in a table with while loop. I have a button, bootstrap modal opening a modal window. In that window i have submit to delete button. With while loop.
Problem is, i'm trying to delete this record, but its deleting random record. can you check is there a problem?

Thanks already.
here is my code:

```<code><table class="table table-hover">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Surname</th>
        <th>Email</th>
        <th>Password</th>
        <th>*</th>
      </tr>
    </thead>
    <tbody>

<?php

    $q = "SELECT * FROM users";
    $r = mysqli_query($dbc,$q);
    while($list = mysqli_fetch_assoc($r)){
        if(isset($_POST['del_submit'])){
            $q = "DELETE FROM users WHERE id = '$list[id]' ";
            $r = mysqli_query($dbc, $q);
                 header('Location: index.php?page=7');
            }

        echo '<tr>';
        echo '<td>'.$list['id'].'</td>';
        echo '<td>'.$list['name'].'</td>';
        echo '<td>'.$list['surname'].'</td>';
        echo '<td>'.$list['email'].'</td>';
        echo '<td>'.$list['password'].'</td>';
        echo '<td><button class="btn btn-danger btn-xs" data-toggle="modal" data-target=".delete'.$list['id'].'"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button> ';

        echo '</tr><form method="post" action="#">';
        echo '<div class="modal fade delete'.$list['id'].'">
              <div class="modal-dialog modal-sm" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title">Delete <strong class="text-primary">'.$list['name'].' ?</strong></h4>
                    </div>

                    <div class="modal-body">
                    <strong class="text-primary">'.$list['name'].' '.$list['surname'].'</strong><br>
                    Are you Sure?
                    </div>
                    <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

                    <button type="submit" name="del_submit" id="del_submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</button>
                    </div>
                </div>
              </div>
            </div></form>';

    }
?>

    </tbody>
</table>
</code>```

答:
Create a delete page and link to it.
first you need to add link to the same page with action and id parameters

```<code><?php
// replace
?>
<button type="submit" name="del_submit" id="del_submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</button>
<?php
// with this:
?>
<input type='hidden' name='id' value='<?= $list['id']; ?>'>
<input type='hidden' name='action' value='delete'>
<button class="btn btn-danger" type='submit'><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</button>
</code>```

add this to the top of your page

```<code><?php

if(isset($_POST['id'], $_POST['action']) && $_POST['action'] === 'delete')
{
   $id = $_POST['id'];
   $query = 'DELETE FROM `users` WHERE `id` = ?';
   $db = new Mysqli('localhost','user','password','database');
   $stmt   = $db->prepare($query);
   $stmt->bind_param('i',$id);
   $stmt->execute();
   $stmt->close();
   $db->close();
   echo 'Deleted! (if exists)';
}
</code>```

Title: Delete Query Inside While Loop

Body:
i'm trying to delete database record inside a while loop. I'm showing my user list in a table with while loop. I have a button, bootstrap modal opening a modal window. In that window i have submit to delete button. With while loop.
Problem is, i'm trying to delete this record, but its deleting random record. can you check is there a problem?

Thanks already.
here is my code:

        Id
        Name
        Surname
        Email
        Password
        *

<?php

    $q = "SELECT * FROM users";
    $r = mysqli_query($dbc,$q);
    while($list = mysqli_fetch_assoc($r)){
        if(isset($_POST['del_submit'])){
            $q = "DELETE FROM users WHERE id = '$list[id]' ";
            $r = mysqli_query($dbc, $q);
                 header('Location: index.php?page=7');
            }

        echo '
';
        echo ''.$list['id'].'	';
        echo ''.$list['name'].'	';
        echo ''.$list['surname'].'	';
        echo ''.$list['email'].'	';
        echo ''.$list['password'].'	';
        echo '<button class="btn btn-danger btn-xs" data-toggle="modal" data-target=".delete'.$list['id'].'"></button> ';

        echo '
<form method="post" action="#">';
        echo '

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Delete '.$list['name'].' ?

                    '.$list['name'].' '.$list['surname'].'

                    Are you Sure?

                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

                    <button type="submit" name="del_submit" id="del_submit" class="btn btn-danger"> Delete</button>

</form>';

    }
?>

Body:
Create a delete page and link to it.
first you need to add link to the same page with action and id parameters

<?php
// replace
?>
<button type="submit" name="del_submit" id="del_submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</button>
<?php
// with this:
?>
<input type='hidden' name='id' value='<?= $list['id']; ?>'>
<input type='hidden' name='action' value='delete'>
<button class="btn btn-danger" type='submit'><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</button>

add this to the top of your page

<?php

if(isset($_POST['id'], $_POST['action']) && $_POST['action'] === 'delete')
{
   $id = $_POST['id'];
   $query = 'DELETE FROM `users` WHERE `id` = ?';
   $db = new Mysqli('localhost','user','password','database');
   $stmt   = $db->prepare($query);
   $stmt->bind_param('i',$id);
   $stmt->execute();
   $stmt->close();
   $db->close();
   echo 'Deleted! (if exists)';
}

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Print one more parameter with va_args
I have a function which implements a custom variant of printf.
Does anyone have a clue how I can print out one more parameter with va_list? My format is like "%d some text %s". I need a, to be printed as first parameter.

```<code>void func (int a, char *fmt, ...) {
    va_list ap;
    va_start (ap, fmt);
    // vprintf(stdout, fmt, a, ap) //Can't do like this :(
    vfprintf(fmt, a, ap);          //Or like this :(
    va_end(ap);
}
</code>```

答:
If a is always printed the same way, it shouldn't be part of the format passed in.  You should instead print it separately.

In the example you gave, change your format string to "some text %s".  Then your function can do this:

```<code>void func (int a, char *fmt, ...) {
    va_list ap;

    // first print the function specific fields
    printf("%d ", a);

    // then the user's format
    va_start (ap, fmt);
    vprintf(fmt, ap);
    va_end(ap);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Print one more parameter with va_args

Body:
I have a function which implements a custom variant of printf.
Does anyone have a clue how I can print out one more parameter with va_list? My format is like "%d some text %s". I need a, to be printed as first parameter.

void func (int a, char *fmt, ...) {
    va_list ap;
    va_start (ap, fmt);
    // vprintf(stdout, fmt, a, ap) //Can't do like this :(
    vfprintf(fmt, a, ap);          //Or like this :(
    va_end(ap);
}

Body:
If a is always printed the same way, it shouldn't be part of the format passed in.  You should instead print it separately.

In the example you gave, change your format string to "some text %s".  Then your function can do this:

void func (int a, char *fmt, ...) {
    va_list ap;

    // first print the function specific fields
    printf("%d ", a);

    // then the user's format
    va_start (ap, fmt);
    vprintf(fmt, ap);
    va_end(ap);
}


问:
JavaScript not decoding parameter
So from the textarea I take the shortcode %91samurai id="19"%93 it should be [samurai id="19"]:

```<code>var not_decoded_content = jQuery('[data-module_type="et_pb_text_forms_00132547"]')
.find('#et_pb_et_pb_text_form_content').html();
</code>```

But when I try to decode the %91 and %93

```<code>self.content = decodeURI(not_decoded_content);
</code>```

I get the error:

Uncaught URIError: URI malformed

How can i solve this problem?

答:
The encodings are invalid. If you can't fix the whatever-system-produces-them to correctly produce %5B and %5D, then your only option is to do a replacement yourself: replace all %91 with character 91 which is '[', then replace all %93 with character 93 which is ']'.

Note that javascript String Replace as-is won't do "Replace all occurrences". If you need that, then create a loop (while it contains(...) do a replace), or search the internet for javascript replace all, you should find plenty results.

And a final note, I am used to using decodeURIComponent(...). If you can make the whatever-system-produces-them to correctly produce %5B and %5D, and you still get that error, then try using decodeURIComponent(...) instead of decodeURI(...).

Title: JavaScript not decoding parameter

Body:
So from the textarea I take the shortcode %91samurai id="19"%93 it should be [samurai id="19"]:

var not_decoded_content = jQuery('[data-module_type="et_pb_text_forms_00132547"]')
.find('#et_pb_et_pb_text_form_content').html();

But when I try to decode the %91 and %93

self.content = decodeURI(not_decoded_content);

I get the error:

Uncaught URIError: URI malformed

How can i solve this problem?


问:
How to convert my types to string in PowerShell
I have been able to create an array and store a list of fields, I am trying to convert this to a CSV file. However, I need all my outputs to be as a string. Currently I have text coming out as a string, however for example I need my note to come out as a string but it comes out as taxonomy value and not sure how to change this?

Below is my code I have just now:

```<code># Get the web
$web = Get-SPWeb "specified_website"

# Get the target list
$list = $web.Lists["List_name"]

# Items used to hold the data
$Items = $list.Items

$array = @()

# Get all the items in the list
foreach ($item in $Items) {
    $id = $item.id
    Write-Host "Processing item number $id" -ForegroundColor Green
    # every item has a Field e.g. my item has a title, etc.
    foreach ($field in $item.Fields) {
        # Get the type of the field
        Write-Host $field.Type

        # Print the field type out to a string
        switch ($field.Type) {
            "Text" { $msg = checkifTextisNull($item[$field.InternalName]) }
            "Note" {
                Write-Host $item[$field.InternalName] -ForegroundColor Cyan
            }
            "Lookup" { $item[$field.InternalName] -ForegroundColor Yellow }
            "URL" { Write-Host $item[$field.InternalName] -ForegroundColor Magenta }
            "Invalid" {
                #Write-Host $item[$field.InternalName] -ForegroundColor Cyan
            }
            "Guid" { Write-Host $item[$field.InternalName]-ForegroundColor Yellow }
            "Choice" { Write-Host $item[$field.InternalName] -ForegroundColor Cyan }
            "Boolean" {
                $msg = returnBooleanValue($item[$field.InternalName])
                Write-Host $msg -ForegroundColor DarkCyan
            }
            "Computed" { Write-Host $item[$field.InternalName] -ForegroundColor White }
            "Integer" {
                Write-Host $item[$field.InternalName]
            }
            "User" { Write-Host $item[$field.InternalName] -ForegroundColor DarkGreen }
            "DateTime" {
                Write-Host $item[$field.InternalName] -ForegroundColor DarkGreen
            }
            "Number" { Write-Host $item[$field.InternalName] -ForegroundColor Yellow }
            "Counter" { Write-Host $item[$field.InternalName] -ForegroundColor Green }
            "Multi-Choice" {
                Write-Host $item[$field.InternalName]
            }
            "Attachments" { Write-Host $item[$field.InternalName] -ForegroundColor Magenta }
            "ModStat" { Write-Host $item[$field.InternalName] -ForegroundColor DarkGreen }
            "File" { Write-Host $item[$field.InternalName] -ForegroundColor White }
        }
    }

    # Add the object with property to Items
    $array += $Items
}
</code>```

My output that I get is:

Note

Firm wide|0d3fbace-af9c-4f28-8be1-095e616893c0

And the Output I would expect is:

"FieldName", "DataType", "Value"

Site_type_0, Note ,      Firm Wide

When I Write out what the type of data is, I get taxonomy data, when I would want a string

答:
I found that using .TypeAsString helped me out a lot and for the TaxonomyFieldType and TaxonomyFieldTypeMulti Field types I done the following:

```<code>"TaxonomyFieldType"{
                $FieldValue = $item[$field.InternalName] -as [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue];
                $FieldValue = $FieldValue.Label;
                 $FieldValue
        }
        "TaxonomyFieldTypeMulti"{$FieldValueCollection = $item[$field.InternalName] -as [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValueCollection];

                foreach($Value in $FieldValueCollection)   {

                    if($Value.label -ne $null)
                            {
                            $label = $Value.label
                            $guid = $Value.TermGuid.ToString()
                            $FieldValue+="Label = $label Guid = $guid;"
                            }
                }
                Write-Host $Value.label
        }
</code>```

If there is anyone who knows a better way please let me know as I would be very interested to hear.

Body:
I have been able to create an array and store a list of fields, I am trying to convert this to a CSV file. However, I need all my outputs to be as a string. Currently I have text coming out as a string, however for example I need my note to come out as a string but it comes out as taxonomy value and not sure how to change this?

Below is my code I have just now:

# Get the web
$web = Get-SPWeb "specified_website"

# Get the target list
$list = $web.Lists["List_name"]

# Items used to hold the data
$Items = $list.Items

$array = @()

# Get all the items in the list
foreach ($item in $Items) {
    $id = $item.id
    Write-Host "Processing item number $id" -ForegroundColor Green
    # every item has a Field e.g. my item has a title, etc.
    foreach ($field in $item.Fields) {
        # Get the type of the field
        Write-Host $field.Type

        # Print the field type out to a string
        switch ($field.Type) {
            "Text" { $msg = checkifTextisNull($item[$field.InternalName]) }
            "Note" {
                Write-Host $item[$field.InternalName] -ForegroundColor Cyan
            }
            "Lookup" { $item[$field.InternalName] -ForegroundColor Yellow }
            "URL" { Write-Host $item[$field.InternalName] -ForegroundColor Magenta }
            "Invalid" {
                #Write-Host $item[$field.InternalName] -ForegroundColor Cyan
            }
            "Guid" { Write-Host $item[$field.InternalName]-ForegroundColor Yellow }
            "Choice" { Write-Host $item[$field.InternalName] -ForegroundColor Cyan }
            "Boolean" {
                $msg = returnBooleanValue($item[$field.InternalName])
                Write-Host $msg -ForegroundColor DarkCyan
            }
            "Computed" { Write-Host $item[$field.InternalName] -ForegroundColor White }
            "Integer" {
                Write-Host $item[$field.InternalName]
            }
            "User" { Write-Host $item[$field.InternalName] -ForegroundColor DarkGreen }
            "DateTime" {
                Write-Host $item[$field.InternalName] -ForegroundColor DarkGreen
            }
            "Number" { Write-Host $item[$field.InternalName] -ForegroundColor Yellow }
            "Counter" { Write-Host $item[$field.InternalName] -ForegroundColor Green }
            "Multi-Choice" {
                Write-Host $item[$field.InternalName]
            }
            "Attachments" { Write-Host $item[$field.InternalName] -ForegroundColor Magenta }
            "ModStat" { Write-Host $item[$field.InternalName] -ForegroundColor DarkGreen }
            "File" { Write-Host $item[$field.InternalName] -ForegroundColor White }
        }
    }

    # Add the object with property to Items
    $array += $Items
}

My output that I get is:

Note

Firm wide|0d3fbace-af9c-4f28-8be1-095e616893c0

And the Output I would expect is:

"FieldName", "DataType", "Value"

Site_type_0, Note ,      Firm Wide

When I Write out what the type of data is, I get taxonomy data, when I would want a string

Body:
I found that using .TypeAsString helped me out a lot and for the TaxonomyFieldType and TaxonomyFieldTypeMulti Field types I done the following:

"TaxonomyFieldType"{
                $FieldValue = $item[$field.InternalName] -as [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue];
                $FieldValue = $FieldValue.Label;
                 $FieldValue
        }
        "TaxonomyFieldTypeMulti"{$FieldValueCollection = $item[$field.InternalName] -as [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValueCollection];

                foreach($Value in $FieldValueCollection)   {

                    if($Value.label -ne $null)
                            {
                            $label = $Value.label
                            $guid = $Value.TermGuid.ToString()
                            $FieldValue+="Label = $label Guid = $guid;"
                            }
                }
                Write-Host $Value.label
        }

If there is anyone who knows a better way please let me know as I would be very interested to hear.


问:
wildfly 10 - javax.servlet.ServletContainerInitializer: Provider org.springframework.web.SpringServletContainerInitializer not a subtype
I am using Spring 4.3 and Servlet 3.1.
Deployment fails with error
 javax.servlet.ServletContainerInitializer: Provider org.springframework.web.SpringServletContainerInitializer not a subtype.
I know that it is some wrong class is loading

The Spring jars and Servlet 3.1 jars are configured as a module and mentioned in module.xml.

javax.servlet.ServletContainerInitializer is present in only one jar  jboss-servlet-api_3.1_spec-1.0.0.Final.jar that I have included in module.xml.

SpringServletContainerInitializer is needed for my application.
Let me know if you need me to post more details.
Any help is appreciated.

答:
I had the same problem and solved it by goig through my dependencies to see if anything crashed with my application-servers libraries.

Make sure your java-ee and java-ee-web dependencies are set to "provided" scope in your maven/gradle configuration.


问:
Managed Bootstrapper: Failed while prompting for source
I'm delivering 3 msi packages in my Managed Bootstrapper (MBA). User is given choice to select which packages they wants to install. All goes well. When the user tries to Modify the installation from Control Panel, selects new package from dialog and original source (MBA.exe) is missing, installation failed with following log:

```<code>[553C:0A88][2016-03-30T16:00:54]w341: Prompt for source of container: WixAttachedContainer, path: D:\work\MBA.Install.Bundle\bin\Debug\MBA.exe<br/>
[553C:0A88][2016-03-30T16:00:54]e054: Failed to resolve source for file: D:\work\MBA.Install.Bundle\bin\Debug\MBA.exe, error: 0x80070002.
[553C:0A88][2016-03-30T16:00:54]e000: Error 0x80070002: Failed while prompting for source (original path 'D:\work\MBA.Install.Bundle\bin\Debug\MBA.exe').
[553C:0A88][2016-03-30T16:00:54]e311: Failed to acquire container: WixAttachedContainer to working path: C:\Users\Me\AppData\Local\Temp\{1338381A-F85F-4B6D-83EA-A0A2D1A369C1}\10A35D6D6CAC04B3DC248033B1588CBD67AD698B, error: 0x80070002.
[553C:0A88][2016-03-30T16:00:54]i000: CachePackageComplete: Pkg_Id=EMS.Server Resulted=None
[553C:0A88][2016-03-30T16:00:54]i000: CacheComplete: Status=-2147024894
[553C:3C24][2016-03-30T16:00:54]e000: Error 0x80070002: Failed while caching, aborting execution.
</code>```

I've tried to capture this in ResolveSource event handler. e.LocalSource and e.DownloadSource are readonly properties. There is not criteria to download missing file, all needs to be present locally.

I read about the Propmpt to get the Source of original installer here:
https://blogs.msdn.microsoft.com/heaths/2007/10/25/resolvesource-requires-source/

but this is about msi installer, while in my MBA, this dialog is suppressed.

Questions:

How can I set the LocalSource manually (may be by taking input via dialog from user)?

Can I set WixAttachedContainer to some other working path at runtime but taking input from user?

Can we set Engine.SetLocalSource() at runtime?

Thanks a bunch...

答:
This can be bug in WiX toolset - see https://github.com/wixtoolset/issues/issues/5586

Override or hook on ResolveSource event.

Change LocalSource of the container using SetLocalSource()

Set Result of the event to Result.Retry

See following example:

    private void OnResolveSource(object sender, ResolveSourceEventArgs e)
    {
        var wixBundleOriginalSource = Application.Engine.StringVariables["WixBundleOriginalSource"];

        Application.Engine.Log(LogLevel.Verbose, $"Setting local source for {e.PackageOrContainerId} to '{wixBundleOriginalSource}' (WixBundleOriginalSource)");
        Application.Engine.SetLocalSource(e.PackageOrContainerId, e.PayloadId, wixBundleOriginalSource);

        Application.Engine.Log(LogLevel.Verbose, $"Retry to resolve source for {e.PackageOrContainerId}");
        e.Result = Result.Retry;
    }
```

Body:
I'm delivering 3 msi packages in my Managed Bootstrapper (MBA). User is given choice to select which packages they wants to install. All goes well. When the user tries to Modify the installation from Control Panel, selects new package from dialog and original source (MBA.exe) is missing, installation failed with following log:

[553C:0A88][2016-03-30T16:00:54]w341: Prompt for source of container: WixAttachedContainer, path: D:\work\MBA.Install.Bundle\bin\Debug\MBA.exe

[553C:0A88][2016-03-30T16:00:54]e054: Failed to resolve source for file: D:\work\MBA.Install.Bundle\bin\Debug\MBA.exe, error: 0x80070002.
[553C:0A88][2016-03-30T16:00:54]e000: Error 0x80070002: Failed while prompting for source (original path 'D:\work\MBA.Install.Bundle\bin\Debug\MBA.exe').
[553C:0A88][2016-03-30T16:00:54]e311: Failed to acquire container: WixAttachedContainer to working path: C:\Users\Me\AppData\Local\Temp\{1338381A-F85F-4B6D-83EA-A0A2D1A369C1}\10A35D6D6CAC04B3DC248033B1588CBD67AD698B, error: 0x80070002.
[553C:0A88][2016-03-30T16:00:54]i000: CachePackageComplete: Pkg_Id=EMS.Server Resulted=None
[553C:0A88][2016-03-30T16:00:54]i000: CacheComplete: Status=-2147024894
[553C:3C24][2016-03-30T16:00:54]e000: Error 0x80070002: Failed while caching, aborting execution.

I've tried to capture this in ResolveSource event handler. e.LocalSource and e.DownloadSource are readonly properties. There is not criteria to download missing file, all needs to be present locally.

I read about the Propmpt to get the Source of original installer here:
https://blogs.msdn.microsoft.com/heaths/2007/10/25/resolvesource-requires-source/

but this is about msi installer, while in my MBA, this dialog is suppressed.

Questions:

How can I set the LocalSource manually (may be by taking input via dialog from user)?

Can I set WixAttachedContainer to some other working path at runtime but taking input from user?

Can we set Engine.SetLocalSource() at runtime?

Thanks a bunch...


问:
Ruby equivalent operators at "OrElse" and "AndAlso" of Vb.net
There are operators in Ruby similar to "OrElse"and "AndAlso" in VB.NET?

For example in Ruby NoMethodError exception is raised when active_record is nil:

```<code>if active_record.nil? || active_record.errors.count == 0
     ...
end
</code>```

In VB.net i can do:

```<code> If active_record Is Nothing OrElse active_record.errors.count = 0
    ...
 End
</code>```

That does not generate an exception because it is only checked the first expression

答:
Ruby || is short circuit evaluation operator, so it should evaluate only first condition, therefore your if should not raise any exception.

I assume active_record.nil? returns boolean true.

ContentLicense: CC BY-SA 2.5

Body:
There are operators in Ruby similar to "OrElse"and "AndAlso" in VB.NET?

For example in Ruby NoMethodError exception is raised when active_record is nil:

if active_record.nil? || active_record.errors.count == 0
     ...
end

In VB.net i can do:

 If active_record Is Nothing OrElse active_record.errors.count = 0
    ...
 End

That does not generate an exception because it is only checked the first expression


问:
HMAC-SHA-256 in PHP
I have to build an authorization hash from this string:

```<code>kki98hkl-u5d0-w96i-62dp-xpmr6xlvfnjz:20151110171858:b2c13532-3416-47d9-8592-a541c208f755:hKSeRD98BHngrNa51Q2IgAXtoZ8oYebgY4vQHEYjlmzN9KSbAVTRvQkUPsjOGu4F
</code>```

This secret is used for a HMAC hash function:

```<code>LRH9CAkNs-zoU3hxHbrtY0CUUcmqzibPeN7x6-vwNWQ=
</code>```

The authorization hash I have to generate is this:

```<code>P-WgZ8CqV51aI-3TncZj5CpSZh98PjZTYxrvxkmQYmI=
</code>```

There are some things to take care of:

The signature have to be built with HMAC-SHA-256 as specified in RFC 2104.

The signature have to be encoded with Base64 URL-compatible as specified in RFC 4648 Section 5 (Safe alphabet).

There is also some pseudo-code given for the generation:

```<code>Signatur(Request) = new String(encodeBase64URLCompatible(HMAC-SHA-256(getBytes(Z, "UTF-8"), decodeBase64URLCompatible(getBytes(S, "UTF-8")))), "UTF-8")
</code>```

I tried various things in PHP but have not found the correct algorithm yet. This is the code I have now:

```<code>if(!function_exists('base64url_encode')){
    function base64url_encode($data) {
        $data = str_replace(array('+', '/'), array('-', '_'), base64_encode($data));
        return $data;
    }
}

$str = "kki98hkl-u5d0-w96i-62dp-xpmr6xlvfnjz:20151110171858:b2c13532-3416-47d9-8592-a541c208f755:hKSeRD98BHngrNa51Q2IgAXtoZ8oYebgY4vQHEYjlmzN9KSbAVTRvQkUPsjOGu4F";
$sec = "LRH9CAkNs-zoU3hxHbrtY0CUUcmqzibPeN7x6-vwNWQ=";
$signature = mhash(MHASH_SHA256, $str, $sec);
$signature = base64url_encode($signature);

if($signature != "P-WgZ8CqV51aI-3TncZj5CpSZh98PjZTYxrvxkmQYmI=")
    echo "wrong: $signature";
else
    echo "correct";
</code>```

It gives this signature:

```<code>K9lw3V-k5gOedmVwmO5vC7cOn82JSEXsNguozCAOU2c=
</code>```

As you can see, the length of 44 characters is correct. Please help me with finding the mistake, this simple problem takes me hours yet and there is no solution.

答:
Simply use hash_hmac() function available in PHP.

Example :

```<code>hash_hmac('sha256', $string, $secret);
</code>```

Doc here : http://php.net/manual/fr/function.hash-hmac.php

Title: HMAC-SHA-256 in PHP

Body:
I have to build an authorization hash from this string:

kki98hkl-u5d0-w96i-62dp-xpmr6xlvfnjz:20151110171858:b2c13532-3416-47d9-8592-a541c208f755:hKSeRD98BHngrNa51Q2IgAXtoZ8oYebgY4vQHEYjlmzN9KSbAVTRvQkUPsjOGu4F

This secret is used for a HMAC hash function:

LRH9CAkNs-zoU3hxHbrtY0CUUcmqzibPeN7x6-vwNWQ=

The authorization hash I have to generate is this:

P-WgZ8CqV51aI-3TncZj5CpSZh98PjZTYxrvxkmQYmI=

There are some things to take care of:

The signature have to be built with HMAC-SHA-256 as specified in RFC 2104.

The signature have to be encoded with Base64 URL-compatible as specified in RFC 4648 Section 5 (Safe alphabet).

There is also some pseudo-code given for the generation:

Signatur(Request) = new String(encodeBase64URLCompatible(HMAC-SHA-256(getBytes(Z, "UTF-8"), decodeBase64URLCompatible(getBytes(S, "UTF-8")))), "UTF-8")

I tried various things in PHP but have not found the correct algorithm yet. This is the code I have now:

if(!function_exists('base64url_encode')){
    function base64url_encode($data) {
        $data = str_replace(array('+', '/'), array('-', '_'), base64_encode($data));
        return $data;
    }
}

$str = "kki98hkl-u5d0-w96i-62dp-xpmr6xlvfnjz:20151110171858:b2c13532-3416-47d9-8592-a541c208f755:hKSeRD98BHngrNa51Q2IgAXtoZ8oYebgY4vQHEYjlmzN9KSbAVTRvQkUPsjOGu4F";
$sec = "LRH9CAkNs-zoU3hxHbrtY0CUUcmqzibPeN7x6-vwNWQ=";
$signature = mhash(MHASH_SHA256, $str, $sec);
$signature = base64url_encode($signature);

if($signature != "P-WgZ8CqV51aI-3TncZj5CpSZh98PjZTYxrvxkmQYmI=")
    echo "wrong: $signature";
else
    echo "correct";

It gives this signature:

K9lw3V-k5gOedmVwmO5vC7cOn82JSEXsNguozCAOU2c=

As you can see, the length of 44 characters is correct. Please help me with finding the mistake, this simple problem takes me hours yet and there is no solution.

Body:
Simply use hash_hmac() function available in PHP.

Example :

hash_hmac('sha256', $string, $secret);

Doc here : http://php.net/manual/fr/function.hash-hmac.php


问:
pandas plot line segments for each row
I have dataframes with columns containing x,y coordinates for multiple points. One row can consist of several points.
I'm trying to find out an easy way to be able to plot lines between each point generating a curve for each row of data.

Here is a simplified example where two lines are represented by two points each.

```<code>line1 = {'p1_x':1, 'p1_y':10, 'p2_x':2, 'p2_y':11 }
line2 = {'p1_x':2, 'p1_y':9, 'p2_x':3, 'p2_y':12 }
df = pd.DataFrame([line1,line2])

df.plot(y=['p1_y','p2_y'], x=['p1_x','p2_x'])
</code>```

when trying to plot them I expect line 1 to start where x=1 and line 2 to start where x=2.
Instead, the x axis contains two value-pairs (1,2) and (2,3) and both lines have the same start and end-point in x-axis.

How do I get around this problem?

Edit:
If using matplotlib, the following hardcoded values generates the plot i'm interested in
    plt.plot([[1,2],[2,3]],[[10,9],[11,12]])

答:
I generaly don't use the pandas plotting because I think it is rather limited, if using matplotlib is not an issue, the following code works:

```<code>from matplotlib import pyplot as plt
plt.plot(df.p1_x,df.p1_y)
plt.plot(df.p2_x,df.p2_y)
plt.plot()
</code>```

if you got lots of lines to plot, you can use a for loop.

Title: pandas plot line segments for each row

Body:
I have dataframes with columns containing x,y coordinates for multiple points. One row can consist of several points.
I'm trying to find out an easy way to be able to plot lines between each point generating a curve for each row of data.

Here is a simplified example where two lines are represented by two points each.

line1 = {'p1_x':1, 'p1_y':10, 'p2_x':2, 'p2_y':11 }
line2 = {'p1_x':2, 'p1_y':9, 'p2_x':3, 'p2_y':12 }
df = pd.DataFrame([line1,line2])

df.plot(y=['p1_y','p2_y'], x=['p1_x','p2_x'])

when trying to plot them I expect line 1 to start where x=1 and line 2 to start where x=2.
Instead, the x axis contains two value-pairs (1,2) and (2,3) and both lines have the same start and end-point in x-axis.

How do I get around this problem?

Edit:
If using matplotlib, the following hardcoded values generates the plot i'm interested in
    plt.plot([[1,2],[2,3]],[[10,9],[11,12]])

Body:
I generaly don't use the pandas plotting because I think it is rather limited, if using matplotlib is not an issue, the following code works:

from matplotlib import pyplot as plt
plt.plot(df.p1_x,df.p1_y)
plt.plot(df.p2_x,df.p2_y)
plt.plot()

if you got lots of lines to plot, you can use a for loop.


问:
no member function declared in class 'MainWindow'
I'm trying to make a fake FBI program for a prank, but it's not as easy as I expected it to be.
This is my code.

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->trackConnButton->setEnabled(false);
}

void MainWindow::on_confirmButton_clicked() {
    if (ui->usernameText == "name" && ui->passwordText == "password") {
        ui->resullabel->setText("Password accepted.");
        ui->trackConnButton->setEnabled(true);
    } else {
        ui->resullabel->setText("Password denied.");
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}
</code>```

I get this error:

```<code>D:\Qt-Projekte\test3\mainwindow.cpp:12: Fehler: no 'void MainWindow::on_confirmButton_clicked()' member function declared in class 'MainWindow'
 void MainWindow::on_confirmButton_clicked() {
                                           ^
</code>```

My question is now: how to fix it?
Thanks in advance.

my mainwindow.h:

```<code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H
</code>```

答:
All member functions of a class must contain a "declaration" and a "definition".

For example:

```<code>struct Foo {
    // Declarations
    void foo() const;
    int bar(int x);
};

// Definitions
void Foo::foo() const {
    std::cout << "foo" << std::endl;
}
int Foo::bar(int x) {
    return x + 1;
}
</code>```

(Note that if you define a function inline in a class, it counts as both definition and declaration):

```<code>struct Foo {
    // Declaration AND definition
    void foo() const {
        std::cout << "foo inline" << std::endl;
    }
};
</code>```

So in your case, you must declare the on_confirmButton_clicked function inside the definition of class MainWindow.

Body:
I'm trying to make a fake FBI program for a prank, but it's not as easy as I expected it to be.
This is my code.

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->trackConnButton->setEnabled(false);
}

void MainWindow::on_confirmButton_clicked() {
    if (ui->usernameText == "name" && ui->passwordText == "password") {
        ui->resullabel->setText("Password accepted.");
        ui->trackConnButton->setEnabled(true);
    } else {
        ui->resullabel->setText("Password denied.");
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

I get this error:

D:\Qt-Projekte\test3\mainwindow.cpp:12: Fehler: no 'void MainWindow::on_confirmButton_clicked()' member function declared in class 'MainWindow'
 void MainWindow::on_confirmButton_clicked() {
                                           ^

My question is now: how to fix it?
Thanks in advance.

my mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

Body:
All member functions of a class must contain a "declaration" and a "definition".

For example:

struct Foo {
    // Declarations
    void foo() const;
    int bar(int x);
};

// Definitions
void Foo::foo() const {
    std::cout << "foo" << std::endl;
}
int Foo::bar(int x) {
    return x + 1;
}

(Note that if you define a function inline in a class, it counts as both definition and declaration):

struct Foo {
    // Declaration AND definition
    void foo() const {
        std::cout << "foo inline" << std::endl;
    }
};

So in your case, you must declare the on_confirmButton_clicked function inside the definition of class MainWindow.


问:
react router basic example gives error Cannot resolve module 'history/lib/createBrowserHistory'
following react training documentation to learn basics of react-router but it failed on the very first example. below is my package.json info

```<code>    "dependencies": {
        "history": "^4.7.2",
        "react": "^0.14.7",
        "react-dom": "^0.14.7",
        "react-router": "^2.0.0"
    },
</code>```

and this is  relevant code in index.js file

```<code>    import { Router, Route, hashHistory } from 'react-router'

    render((
      <Router history={hashHistory}>
        <Route path="/" component={App}/>
      </Router>
    ), document.getElementById('app'))
</code>```

npm start outputs webpack: Compiled successfully.

but in broswer page opens with some random junk in URL http://localhost:8080/#/?_k=hrfoj1 and display nothing on browser

after searching the issue, came with other solution suggested that React Router is built on history.

so tried this

```<code>    import { Router, Route, IndexRoute} from 'react-router'

    import createBrowserHistory from 'history/lib/createBrowserHistory'
    const appHistory = createBrowserHistory()

    render((<Router history={appHistory} > ...</Router>),  document.getElementById('app'));
</code>```

but when run npm start  gives the error

Module not found: Error: Cannot resolve module
  'history/lib/createBrowserHistory' in
  /opt/react-router-tutorial/lessons/01-setting-up

so Please tell me what is the right solution

答:
^4.7.2 version of 'history' have changed source route, maybe you can try:</p>

```<code>import createBrowserHistory from 'history/es/createBrowserHistory';

const appHistory = createBrowserHistory()
</code>```

Body:
following react training documentation to learn basics of react-router but it failed on the very first example. below is my package.json info

    "dependencies": {
        "history": "^4.7.2",
        "react": "^0.14.7",
        "react-dom": "^0.14.7",
        "react-router": "^2.0.0"
    },

and this is  relevant code in index.js file

    import { Router, Route, hashHistory } from 'react-router'

    render((
      <Router history={hashHistory}>
        <Route path="/" component={App}/>
      </Router>
    ), document.getElementById('app'))

npm start outputs webpack: Compiled successfully.

but in broswer page opens with some random junk in URL http://localhost:8080/#/?_k=hrfoj1 and display nothing on browser

after searching the issue, came with other solution suggested that React Router is built on history.

so tried this

    import { Router, Route, IndexRoute} from 'react-router'

    import createBrowserHistory from 'history/lib/createBrowserHistory'
    const appHistory = createBrowserHistory()

    render((<Router history={appHistory} > ...</Router>),  document.getElementById('app'));

but when run npm start  gives the error

Module not found: Error: Cannot resolve module
  'history/lib/createBrowserHistory' in
  /opt/react-router-tutorial/lessons/01-setting-up

so Please tell me what is the right solution

Body:
^4.7.2 version of 'history' have changed source route, maybe you can try:

import createBrowserHistory from 'history/es/createBrowserHistory';

const appHistory = createBrowserHistory()


问:
Primary receiver refunds a chained payment from their PayPal account; what happens?
I'm developing a PayPal chained payment app where

Primary receiver = the service provider, gets 90% of payment

Secondary receiver = marketplace, gets 10% of payment

It's all working in the Sandbox environment, but there's a snag - when the primary receiver logs into their PayPal account, and manually refunds a payment they received, the secondary receiver doesn't appear to return their 10% automatically.

E.g.:

Primary receiver was paid $100, passed $10 automatically to
secondary receiver.

Primary receiver decides to refund using PayPal
account interface.

Refund for $100 issued; but secondary receiver
keeps their $10. Primary receiver now out of pocket by $10.

I would like it so that the secondary receiver automatically refunds their portion of a payment if the primary receiver issues a refund.

From reading the documentation from the Refund API (https://developer.paypal.com/docs/classic/api/adaptive-payments/Refund_API_Operation/), I thought this was the default behaviour, no matter if the refund was initiated through an API call or manually through the PayPal account interface.

Do I have this wrong, or is it just a bug with the Sandbox environment?

Would be useful to have this cleared up, as couldn't find any existing threads on the matter.

Update

PayPal Technical Support have told me the following:

Thank you for contacting Merchant Technical Services.
  From my understanding you would like to have when a primary receiver perform a refund, the secondary receiver will automatically issued a refund.
  If you would like all the receiver to refund the amount, you have to pass the paykey. May I know how the payment was made? If it is using Pay API operation, you have to use Refund API in order to refund the transaction. The refund can't be done by using PayPal account.

答:
Use the payKey of the original transaction in the refund API, it will solve your problem.
And in case if you wish to partially refund the amount, specify the amount to be deducted from primary and secondary receivers in the "receiverList" field.
For more, refer: https://developer.paypal.com/docs/classic/api/adaptive-payments/Refund_API_Operation/#table-3-additional-fields-for-refunds-of-specific-amounts-to-specific-receivers</p>


问:
ExpressJS - Wrong domain name in request headers
I have multiple domains pointing to same server. when i'm try to print the host name using req.headers['theHost'] it shows the other domain name instead of one to which request is sent. Example if i request a.com then in the headers it is showing b.com(other domain pointing to same server).

答: In order to get the hostname of an incoming request you can use req.get('Host'); (Express v4 way to get headers from a request - header field is case insensitive).


问:
Problems sending json from postman
I have a model with a List<string> Parameters {get; set;} property, so when I send from postman a json like this

```<code>{
    ...,
    "Parameters" :
    [
        ["FirstParam"],
        ["SecondParam"]
    ],
    ...
}
</code>```

I receive null in my controller method, I mean the requestModel is null

```<code>public JsonResult GetBalances([FromBody]RequestModel requestModel)
{
    ...
}
</code>```

I know that "Parameters" is the problem because when I send without it, I receive the model normally.

How can I receive a list of parameters(string) from a json format?

PD. It works when I create a model like

```<code>public class RequestModel
{
    ...
    public List<Parameters> Parameters {get;set;}
}

public class Parameters
{
    public string Name {get;set;}
}
</code>```

And the json

```<code>{
    ...,
    "Parameters" : [
        {"Name": "FirstParameter"},
        {"Name":"SecondParameter"}
    ]
    ...
}
</code>```

But I wonder if it is possible get it without create a class. Thanks in advance.

答:
I found the problem, the json format was wrong. My final json:

```<code>{
    ...,
    "Parameters" :
    [
        "FirstParam",
        "SecondParam"
    ],
    ...
}
</code>```

I think I was sending a list of arrays of strings (or something like that). Now I can use List<string> as a property in my model.

Title: Problems sending json from postman

Body:
I have a model with a List<string> Parameters {get; set;} property, so when I send from postman a json like this

{
    ...,
    "Parameters" :
    [
        ["FirstParam"],
        ["SecondParam"]
    ],
    ...
}

I receive null in my controller method, I mean the requestModel is null

public JsonResult GetBalances([FromBody]RequestModel requestModel)
{
    ...
}

I know that "Parameters" is the problem because when I send without it, I receive the model normally.

How can I receive a list of parameters(string) from a json format?

PD. It works when I create a model like

public class RequestModel
{
    ...
    public List<Parameters> Parameters {get;set;}
}

public class Parameters
{
    public string Name {get;set;}
}

And the json

{
    ...,
    "Parameters" : [
        {"Name": "FirstParameter"},
        {"Name":"SecondParameter"}
    ]
    ...
}

But I wonder if it is possible get it without create a class. Thanks in advance.

Body:
I found the problem, the json format was wrong. My final json:

{
    ...,
    "Parameters" :
    [
        "FirstParam",
        "SecondParam"
    ],
    ...
}

I think I was sending a list of arrays of strings (or something like that). Now I can use List<string> as a property in my model.


问:
How can I translate printf("%c",M); from C to Java for my DES implementation?
I'm a German student and for computer classes I need to implement the DES-encryption in Java (by myself, not by using the Java-API) and explain it in detail. I didn't find any Java-code-examples using google, however I did find an easy implementation in C. (I do not know C, I know a little C++, but not that well, pointer still get me now and then.)

So I tried simply converting the code from C to Java, which did work out about halfway, however I'm having a problem with the last part, especially with the example using:

```<code>printf("%c",M);
</code>```

Which, from what Google told me, seems to be converting numbers(Integer) to ASCII-Characters, but I'm not really sure. My Code seems to be working until that last part, so I would be thankful for anyone that can give me fix/hint.

My Code:

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

public class DES {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Scanner eingabe = new Scanner(System.in);

        int p, q, key2, fn, encryption_key, temp1 , temp2 ,
            t, s =0 , privatekey1=1, b=0 , passwort_s=0, klartext;
        int[] Cipher = new int [100];
        String passwort;

        System.out.println("Enter the value of p and q");

        p = eingabe.nextInt();
        q = eingabe.nextInt();

        System.out.println(p);
        System.out.println(q);

        key2= p*q;

        fn=(p-1)*(q-1);
        System.out.println("Enter Enryption key e: ");
        encryption_key = eingabe.nextInt();

        do {

            s=(privatekey1*encryption_key)%fn;
            privatekey1++;

        } while (s!=1);

        privatekey1=privatekey1-1;

        System.out.println("Public Key : "+ encryption_key + ","+ key2 );
        System.out.println("Private Key: "+ privatekey1 + "," +key2 );
        System.out.println("Enter Message: ");
        passwort= eingabe.next();
        for ( temp2 = 0; temp2 < passwort.length(); temp2++)
        {
            t = passwort.charAt(temp2);
            passwort_s=1;
            for(temp1 =0 ; temp1< encryption_key ; temp1++){
                passwort_s= passwort_s*t%key2;
            }
            passwort_s= passwort_s%key2;
            System.out.println(passwort_s);
        }

        System.out.println("Enter cipher Text: ");
        for(temp1=0;temp1< passwort.length(); temp1++ )
        {
            Cipher[temp1]= eingabe.nextInt();
        }

        System.out.println("Plainttext: ");
        for(temp2 =0; temp2 < passwort.length(); temp2++);
        {
            klartext=1;

            for(temp1 =0; temp1 < privatekey1; temp1 ++){
                klartext=klartext*Cipher[temp2]%key2;
            }
            klartext=klartext%key2;
            System.out.println(klartext);
        }
    }
}
</code>```

How can I convert the

```<code>printf("%c",M);
</code>```

to Java, and is this then a full DES implementation?

答:
Or, more concisely:

```<code>output.print((char)M);
</code>```

This assumes M is a numeric value representing an ASCII character from 0-127 (or an ISO 8859-1 character from 0-255, or a Unicode character from 0-65535).

It also assumes output is a PrintWriter or PrintStream, one of which is System.out (a FileOutputStream is easily wrapped by a PrintOutputStream, or PrintWriter(new OutputStreamWriter)).

Body:
I'm a German student and for computer classes I need to implement the DES-encryption in Java (by myself, not by using the Java-API) and explain it in detail. I didn't find any Java-code-examples using google, however I did find an easy implementation in C. (I do not know C, I know a little C++, but not that well, pointer still get me now and then.)

So I tried simply converting the code from C to Java, which did work out about halfway, however I'm having a problem with the last part, especially with the example using:

printf("%c",M);

Which, from what Google told me, seems to be converting numbers(Integer) to ASCII-Characters, but I'm not really sure. My Code seems to be working until that last part, so I would be thankful for anyone that can give me fix/hint.

My Code:

import java.util.Scanner;

public class DES {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Scanner eingabe = new Scanner(System.in);

        int p, q, key2, fn, encryption_key, temp1 , temp2 ,
            t, s =0 , privatekey1=1, b=0 , passwort_s=0, klartext;
        int[] Cipher = new int [100];
        String passwort;

        System.out.println("Enter the value of p and q");

        p = eingabe.nextInt();
        q = eingabe.nextInt();

        System.out.println(p);
        System.out.println(q);

        key2= p*q;

        fn=(p-1)*(q-1);
        System.out.println("Enter Enryption key e: ");
        encryption_key = eingabe.nextInt();

        do {

            s=(privatekey1*encryption_key)%fn;
            privatekey1++;

        } while (s!=1);

        privatekey1=privatekey1-1;

        System.out.println("Public Key : "+ encryption_key + ","+ key2 );
        System.out.println("Private Key: "+ privatekey1 + "," +key2 );
        System.out.println("Enter Message: ");
        passwort= eingabe.next();
        for ( temp2 = 0; temp2 < passwort.length(); temp2++)
        {
            t = passwort.charAt(temp2);
            passwort_s=1;
            for(temp1 =0 ; temp1< encryption_key ; temp1++){
                passwort_s= passwort_s*t%key2;
            }
            passwort_s= passwort_s%key2;
            System.out.println(passwort_s);
        }

        System.out.println("Enter cipher Text: ");
        for(temp1=0;temp1< passwort.length(); temp1++ )
        {
            Cipher[temp1]= eingabe.nextInt();
        }

        System.out.println("Plainttext: ");
        for(temp2 =0; temp2 < passwort.length(); temp2++);
        {
            klartext=1;

            for(temp1 =0; temp1 < privatekey1; temp1 ++){
                klartext=klartext*Cipher[temp2]%key2;
            }
            klartext=klartext%key2;
            System.out.println(klartext);
        }
    }
}

How can I convert the

printf("%c",M);

to Java, and is this then a full DES implementation?

LastEditorDisplayName: John Nolan

Body:
Or, more concisely:

output.print((char)M);

This assumes M is a numeric value representing an ASCII character from 0-127 (or an ISO 8859-1 character from 0-255, or a Unicode character from 0-65535).

It also assumes output is a PrintWriter or PrintStream, one of which is System.out (a FileOutputStream is easily wrapped by a PrintOutputStream, or PrintWriter(new OutputStreamWriter)).

OwnerDisplayName: Software Monkey


问:
Textblob word tokenization into array
```<code>from textblob import TextBlob
import nltk
array=("i have a bunch of grapes","i like to eat apple","this is a laptop")
array2=[]

for i in array:

    c=TextBlob(i)
    array2.append(c.words)

print array2
</code>```

the result printed out will be:

[WordList(['i', 'have', 'a', 'bunch', 'of', 'grapes']), WordList(['i', 'like', 'to', 'eat', 'apple']), WordList(['this', 'is', 'a', 'laptop'])]

how can i extract from the WordList so that my array2 will be printed as:

[['i', 'have', 'a', 'bunch', 'of', 'grapes'],['i', 'like', 'to', 'eat', 'apple'],["this is a laptop"]]

Title: Textblob word tokenization into array

Body:
from textblob import TextBlob
import nltk
array=("i have a bunch of grapes","i like to eat apple","this is a laptop")
array2=[]

for i in array:

    c=TextBlob(i)
    array2.append(c.words)

print array2

the result printed out will be:

[WordList(['i', 'have', 'a', 'bunch', 'of', 'grapes']), WordList(['i', 'like', 'to', 'eat', 'apple']), WordList(['this', 'is', 'a', 'laptop'])]

how can i extract from the WordList so that my array2 will be printed as:

[['i', 'have', 'a', 'bunch', 'of', 'grapes'],['i', 'like', 'to', 'eat', 'apple'],["this is a laptop"]]


问:
Python: Best way to reference file one level up in directory?
I'm a Python newbie and I'm running into a problem that I feel like should have a relatively straight forward answer that I can't quite figure out.

I need to do it this way for an assignment as our teacher wants our GitHub folder to contain all the code in one folder and all of the images in another folder.

Since I will be in the Code folder when running the Python file, is there a way I can reference the Image Folder? Locally, I know I can just put the full path, but because this will be done through command line for GitHub, I wasn't sure what the full path even looked like to reference that folder.

```<code>+ Main GitHub Directory
    + Code Folder
       -My Python File
    + Image Folder
       -Images I want to use
</code>```

This is just a sample program of what I would like to do:

```<code>from PIL import Image
image = Image.open('WeatherIcons/Code32.PNG')
image.show()
</code>```

This will work if 'WeatherIcons' is a subfolder of the Code Folder, but not when it is at the same level. Any creative solutions to get around this?

Thank you!

答:
Use the path:</p>

```<code>../Image_Folder/Code32.png
</code>```

Body:
I'm a Python newbie and I'm running into a problem that I feel like should have a relatively straight forward answer that I can't quite figure out.

I need to do it this way for an assignment as our teacher wants our GitHub folder to contain all the code in one folder and all of the images in another folder.

Since I will be in the Code folder when running the Python file, is there a way I can reference the Image Folder? Locally, I know I can just put the full path, but because this will be done through command line for GitHub, I wasn't sure what the full path even looked like to reference that folder.

+ Main GitHub Directory
    + Code Folder
       -My Python File
    + Image Folder
       -Images I want to use

This is just a sample program of what I would like to do:

from PIL import Image
image = Image.open('WeatherIcons/Code32.PNG')
image.show()

This will work if 'WeatherIcons' is a subfolder of the Code Folder, but not when it is at the same level. Any creative solutions to get around this?

Thank you!

Body:
Use the path:

../Image_Folder/Code32.png


问:
Binary compatibility in 2015 visual studio
One of the legacy application which build in 2010 visual studio(native application) need to be upgraded its one of the DLL which build in visual studio 15, is this possible?</p>

答:
If the interface uses types from the C++ Standard Library, such as std::string, it's unlikely to work. These types generally come from the C++ runtime, and the two versions have different runtime libraries.

If the interface uses LPCSTR, the implementation can use any string library internally (standard, Qt, etc)


问:
How to import Dictionary text file and check for word matches?
I generate a random string of 500 characters and want to check for words.

```<code>bliduuwfhbgphwhsyzjnlfyizbjfeeepsbpgplpbhaegyepqcjhhotovnzdtlracxrwggbcmjiglasjvmscvxwazmutqiwppzcjhijjbguxfnduuphhsoffaqwtmhmensqmyicnciaoczumjzyaaowbtwjqlpxuuqknxqvmnueknqcbvkkmildyvosczlbnlgumohosemnfkmndtiubfkminlriytmbtrzhwqmovrivxxojbpirqahatmydqgulammsnfgcvgfncqkpxhgikulsjynjrjypxwvlkvwvigvjvuydbjfizmbfbtjprxkmiqpfuyebllzezbxozkiidpplvqkqlgdlvjbfeticedwomxgawuphocisaejeonqehoipzsjgbfdatbzykkurrwwtajeajeornrhyoqadljfjyizzfluetynlrpoqojxxqmmbuaktjqghqmusjfvxkkyoewgyckpbmismwyfebaucsfueuwgio
</code>```

I import a Dictionary Words txt file and check the string to see if it contains each word. If a match is found, it's added to a list.

I read using Dictionary<> is faster than Array for a words list.

When I use that method, I can see the cpu working the foreach loop in the debugger, and my loop counter goes up, about 10,000+ times in 10 seconds, but the loop continues on forever and does not return any results.

When I use Array for Dictionary, the program works, but slower at around 500 times in 10 seconds.

Not Working

Using Dictionary<>

```<code>// Random Message
public string message = Random(500);

// Dictionary Words Reference
public Dictionary<string, string> dictionary = new Dictionary<string, string>();

// Matches Found
public static List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // Import Dictionary File
    dictionary = File
                    .ReadLines(@"C:\dictionary.txt")
                    .Select((v, i) => new { Index = i, Value = v })
                    .GroupBy(p => p.Index / 2)
                    .ToDictionary(g => g.First().Value, g => g.Last().Value);

    // If Message Contains word, add to Matches List
    foreach (KeyValuePair<string, string> entry in dictionary)
    {
        if (message.Contains(entry.Value))
        {
            matches.Add(entry.Value);
        }
    }
}
</code>```

Working

Using Array

```<code>// Random Message
public string message = Random(500);

// Dictionary Words Reference
public string[] dictionary = File.ReadAllLines(@"C:\dictionary.txt");

// Matches Found
public List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // If Message Contains word, add to Matches List
    foreach (var entry in dictionary)
    {
        if (message.Contains(entry))
        {
            matches.Add(entry);
        }
    }
}
</code>```

答:
Using a Dictionary in this scenario doesn't make much sense. A Dictionary is, essentially, a list of variables that stores both the variable name and the variable value.

I could have the following:

```<code>int age = 21;
int money = 21343;
int distance = 10;
int year = 2017;
</code>```

And convert it to a Dictionary instead, using the following:

```<code>Dictionary<string, int> numbers = new Dictionary<string, int>()
{
    { "age", 21 },
    { "money", 21343},
    { "distance", 10 },
    { "year", 2017 }
};
</code>```

And then I can access a value in the dictionary using its key (the first value). So, for example, if I want to know what "age" is, I would use:

```<code>Console.Log(numbers["age"]);
</code>```

This is only a single example of the power of dictionaries - there is a LOT more that they can do, and they can make your life a lot easier. In this scenario, however, they aren't going to do what you're expecting them to do. I would suggest just using the Array, or a List.

Body:
I generate a random string of 500 characters and want to check for words.

bliduuwfhbgphwhsyzjnlfyizbjfeeepsbpgplpbhaegyepqcjhhotovnzdtlracxrwggbcmjiglasjvmscvxwazmutqiwppzcjhijjbguxfnduuphhsoffaqwtmhmensqmyicnciaoczumjzyaaowbtwjqlpxuuqknxqvmnueknqcbvkkmildyvosczlbnlgumohosemnfkmndtiubfkminlriytmbtrzhwqmovrivxxojbpirqahatmydqgulammsnfgcvgfncqkpxhgikulsjynjrjypxwvlkvwvigvjvuydbjfizmbfbtjprxkmiqpfuyebllzezbxozkiidpplvqkqlgdlvjbfeticedwomxgawuphocisaejeonqehoipzsjgbfdatbzykkurrwwtajeajeornrhyoqadljfjyizzfluetynlrpoqojxxqmmbuaktjqghqmusjfvxkkyoewgyckpbmismwyfebaucsfueuwgio

I import a Dictionary Words txt file and check the string to see if it contains each word. If a match is found, it's added to a list.

I read using Dictionary<> is faster than Array for a words list.

When I use that method, I can see the cpu working the foreach loop in the debugger, and my loop counter goes up, about 10,000+ times in 10 seconds, but the loop continues on forever and does not return any results.

When I use Array for Dictionary, the program works, but slower at around 500 times in 10 seconds.

Not Working

Using Dictionary<>

// Random Message
public string message = Random(500);

// Dictionary Words Reference
public Dictionary<string, string> dictionary = new Dictionary<string, string>();

// Matches Found
public static List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // Import Dictionary File
    dictionary = File
                    .ReadLines(@"C:\dictionary.txt")
                    .Select((v, i) => new { Index = i, Value = v })
                    .GroupBy(p => p.Index / 2)
                    .ToDictionary(g => g.First().Value, g => g.Last().Value);

    // If Message Contains word, add to Matches List
    foreach (KeyValuePair<string, string> entry in dictionary)
    {
        if (message.Contains(entry.Value))
        {
            matches.Add(entry.Value);
        }
    }
}

Working

Using Array

// Random Message
public string message = Random(500);

// Dictionary Words Reference
public string[] dictionary = File.ReadAllLines(@"C:\dictionary.txt");

// Matches Found
public List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // If Message Contains word, add to Matches List
    foreach (var entry in dictionary)
    {
        if (message.Contains(entry))
        {
            matches.Add(entry);
        }
    }
}

Body:
Using a Dictionary in this scenario doesn't make much sense. A Dictionary is, essentially, a list of variables that stores both the variable name and the variable value.

I could have the following:

int age = 21;
int money = 21343;
int distance = 10;
int year = 2017;

And convert it to a Dictionary instead, using the following:

Dictionary<string, int> numbers = new Dictionary<string, int>()
{
    { "age", 21 },
    { "money", 21343},
    { "distance", 10 },
    { "year", 2017 }
};

And then I can access a value in the dictionary using its key (the first value). So, for example, if I want to know what "age" is, I would use:

Console.Log(numbers["age"]);

This is only a single example of the power of dictionaries - there is a LOT more that they can do, and they can make your life a lot easier. In this scenario, however, they aren't going to do what you're expecting them to do. I would suggest just using the Array, or a List.


问:
Display two objects using OpenGL. Textures not behaving as expected

Hi, I am trying to display two objects using OpenGL viz., 1) a rotating cube with a mix of two textures (a wooden crate pattern and a smiley) in the foreground and 2) rectangular plate with just one texture (dark grey wood) as a background. When I comment out the part of the code governing the display of rectangular plate, the rotating cube displays both the textures (wooden crate and smiley). Otherwise, the cube displays only the wooden crate texture and the dark grey wood texture is also displayed on the rectangular plate, i.e. the smiley texture disappears from the rotating cube. Please find the images 1) http://oi68.tinypic.com/2la4r3c.jpg (with the rectangular plate portion of code commented) and 2) http://i67.tinypic.com/9u9rpf.jpg (without the rectangular plate portion of code commented). The relavant portion of the code is pasted below

```<code>// Rotating Cube ===================================================
// Texture of wooden crate
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glUniform1i(glGetUniformLocation(ourShader_box.Program, "ourTexture1"), 0);

// Texture of a smiley
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
glUniform1i(glGetUniformLocation(ourShader_box.Program, "ourTexture2"), 1);

// lets use the box shader for the cube
ourShader_box.Use();

// transformations for the rotating cube ---------------------------------
glm::mat4 model_box, model1, model2;
glm::mat4 view_box;
glm::mat4 perspective;

perspective = glm::perspective(45.0f, (GLfloat)width_screen/(GLfloat)height_screen, 0.1f, 200.0f);

model1 = glm::rotate(model_box, (GLfloat)glfwGetTime()*1.0f, glm::vec3(0.5f, 1.0f, 0.0f));
model2 = glm::rotate(model_box, (GLfloat)glfwGetTime()*1.0f, glm::vec3(0.0f, 1.0f, 0.5f));
model_box = model1 * model2;

view_box= glm::translate(view_box, glm::vec3(1.0f, 0.0f, -3.0f));

GLint modelLoc_box = glGetUniformLocation(ourShader_box.Program, "model");
GLint viewLoc_box = glGetUniformLocation(ourShader_box.Program, "view");
GLint projLoc_box = glGetUniformLocation(ourShader_box.Program, "perspective");

glUniformMatrix4fv(modelLoc_box, 1, GL_FALSE, glm::value_ptr(model_box));
glUniformMatrix4fv(viewLoc_box, 1, GL_FALSE, glm::value_ptr(view_box));
glUniformMatrix4fv(projLoc_box, 1, GL_FALSE, glm::value_ptr(perspective));
// --------------------------------------------------------------------

// Draw calls
glBindVertexArray(VAO_box);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);

// Rectangular Plate =====================================================
// Background Shader
ourShader_bg.Use();

// Texture of dark grey wood
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, texture_wood);
glUniform1i(glGetUniformLocation(ourShader_bg.Program, "ourTexture3"), 2);

// Transformations -------------------------------------------
glm::mat4 model_bg;
glm::mat4 view_bg;

GLint modelLoc_bg = glGetUniformLocation(ourShader_bg.Program, "model");
GLint viewLoc_bg= glGetUniformLocation(ourShader_bg.Program, "view");
GLint projLoc_bg = glGetUniformLocation(ourShader_bg.Program, "perspective");

glUniformMatrix4fv(modelLoc_bg, 1, GL_FALSE, glm::value_ptr(model_bg));
glUniformMatrix4fv(viewLoc_bg, 1, GL_FALSE, glm::value_ptr(view_bg));
glUniformMatrix4fv(projLoc_bg, 1, GL_FALSE, glm::value_ptr(perspective));
// -----------------------------------------------------------

// Draw calls
glBindVertexArray(VAO_bg);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
// =================================================================
</code>```

I have a two questions regarding this code.

Why is the smiley disappearing?

Is this how multiple objects are supposed to be rendered? I know OpenGL does not care about objects, it only cares about vertices, but in this case these are separate, disjoint objects. So, should I be organizing them as two VBO's bound to a single VAO or as separate VBO's each bound to two VAO's for each object? Or is the case such that, either way is fine - depends on coder's choice and elegance of code?

答:
You are using the same shader, same matrices and you have the same geometry type for the two objects (triangles), so why set the shader twice ?
Did you try to;

Set shader

Bind buffer #1

Bind texture #1

Draw object #1

Bind buffer #2

Bind texture #2

Draw object #2

Body:
Hi, I am trying to display two objects using OpenGL viz., 1) a rotating cube with a mix of two textures (a wooden crate pattern and a smiley) in the foreground and 2) rectangular plate with just one texture (dark grey wood) as a background. When I comment out the part of the code governing the display of rectangular plate, the rotating cube displays both the textures (wooden crate and smiley). Otherwise, the cube displays only the wooden crate texture and the dark grey wood texture is also displayed on the rectangular plate, i.e. the smiley texture disappears from the rotating cube. Please find the images 1) http://oi68.tinypic.com/2la4r3c.jpg (with the rectangular plate portion of code commented) and 2) http://i67.tinypic.com/9u9rpf.jpg (without the rectangular plate portion of code commented). The relavant portion of the code is pasted below

// Rotating Cube ===================================================
// Texture of wooden crate
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glUniform1i(glGetUniformLocation(ourShader_box.Program, "ourTexture1"), 0);

// Texture of a smiley
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
glUniform1i(glGetUniformLocation(ourShader_box.Program, "ourTexture2"), 1);

// lets use the box shader for the cube
ourShader_box.Use();

// transformations for the rotating cube ---------------------------------
glm::mat4 model_box, model1, model2;
glm::mat4 view_box;
glm::mat4 perspective;

perspective = glm::perspective(45.0f, (GLfloat)width_screen/(GLfloat)height_screen, 0.1f, 200.0f);

model1 = glm::rotate(model_box, (GLfloat)glfwGetTime()*1.0f, glm::vec3(0.5f, 1.0f, 0.0f));
model2 = glm::rotate(model_box, (GLfloat)glfwGetTime()*1.0f, glm::vec3(0.0f, 1.0f, 0.5f));
model_box = model1 * model2;

view_box= glm::translate(view_box, glm::vec3(1.0f, 0.0f, -3.0f));

GLint modelLoc_box = glGetUniformLocation(ourShader_box.Program, "model");
GLint viewLoc_box = glGetUniformLocation(ourShader_box.Program, "view");
GLint projLoc_box = glGetUniformLocation(ourShader_box.Program, "perspective");

glUniformMatrix4fv(modelLoc_box, 1, GL_FALSE, glm::value_ptr(model_box));
glUniformMatrix4fv(viewLoc_box, 1, GL_FALSE, glm::value_ptr(view_box));
glUniformMatrix4fv(projLoc_box, 1, GL_FALSE, glm::value_ptr(perspective));
// --------------------------------------------------------------------

// Draw calls
glBindVertexArray(VAO_box);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);

// Rectangular Plate =====================================================
// Background Shader
ourShader_bg.Use();

// Texture of dark grey wood
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, texture_wood);
glUniform1i(glGetUniformLocation(ourShader_bg.Program, "ourTexture3"), 2);

// Transformations -------------------------------------------
glm::mat4 model_bg;
glm::mat4 view_bg;

GLint modelLoc_bg = glGetUniformLocation(ourShader_bg.Program, "model");
GLint viewLoc_bg= glGetUniformLocation(ourShader_bg.Program, "view");
GLint projLoc_bg = glGetUniformLocation(ourShader_bg.Program, "perspective");

glUniformMatrix4fv(modelLoc_bg, 1, GL_FALSE, glm::value_ptr(model_bg));
glUniformMatrix4fv(viewLoc_bg, 1, GL_FALSE, glm::value_ptr(view_bg));
glUniformMatrix4fv(projLoc_bg, 1, GL_FALSE, glm::value_ptr(perspective));
// -----------------------------------------------------------

// Draw calls
glBindVertexArray(VAO_bg);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
// =================================================================

I have a two questions regarding this code.

Why is the smiley disappearing?

Is this how multiple objects are supposed to be rendered? I know OpenGL does not care about objects, it only cares about vertices, but in this case these are separate, disjoint objects. So, should I be organizing them as two VBO's bound to a single VAO or as separate VBO's each bound to two VAO's for each object? Or is the case such that, either way is fine - depends on coder's choice and elegance of code?


问:
JavaScript not decoding parameter
So from the textarea I take the shortcode %91samurai id="19"%93 it should be [samurai id="19"]:

```<code>var not_decoded_content = jQuery('[data-module_type="et_pb_text_forms_00132547"]')
.find('#et_pb_et_pb_text_form_content').html();
</code>```

But when I try to decode the %91 and %93

```<code>self.content = decodeURI(not_decoded_content);
</code>```

I get the error:

Uncaught URIError: URI malformed

How can i solve this problem?

答:
I know this is not the solution you want to see, but can you try using "%E2%80%98" for %91 and "%E2%80%9C" for %93 ?

The %91 and %93 are part of control characters which html does not like to decode (for reasons beyond me). Simply put, they're not your ordinary ASCII characters for HTML to play around with.

Title: JavaScript not decoding parameter

Body:
So from the textarea I take the shortcode %91samurai id="19"%93 it should be [samurai id="19"]:

var not_decoded_content = jQuery('[data-module_type="et_pb_text_forms_00132547"]')
.find('#et_pb_et_pb_text_form_content').html();

But when I try to decode the %91 and %93

self.content = decodeURI(not_decoded_content);

I get the error:

Uncaught URIError: URI malformed

How can i solve this problem?


问:
Matplotlib, avoid update mouse cursor when draw
When a plot is updated with the set_data and draw method, the mouse cursor change few milliseconds from an arrow to a circle. Is it possible to avoid this? Because I update my plot 10 times per second so it is very ugly to see my mouse cursor change so quickly.

I am using Python 3.6, PyQt5, and matplotlib 2.1. Thank you in advance ;)

答:
This is a new "feature" of matplotlib 2.1.

The what's new page says

Busy Cursor

The interactive GUI backends will now change the cursor to busy when Matplotlib is rendering the canvas.

There is also this issue about the undesired behaviour.


问:
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other.

Here is the result I would like

Here is what I am getting (fail)

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
  padding-top: 25px;
  padding-bottom: 95px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="primary-content">
  <p class="intro">
  Austin, Texas is not only the capital.<br>It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.
  </p>
  <div id="container2">
    <div id="container1">
      <div id="About">
        <h2>About</h2>
        <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum.
        </p>
      <!-- Column one end -->
      </div>
      <div id="Capitalbuilding">
      <!-- Column two start -->
        <img src="https://image.ibb.co/e90Vhw/419796506_db7f02aedd_b.jpg" alt="picture of the Capital Building">
      <!-- Column two end -->
      </div>
    </div>
  </div>
</div><!-- End .primary-content --></code>```

答:
You could use flexbox here to get started.

Add...

```<code>#container1 {
  display: flex;
}
</code>```

Guide to flexbox here.

fiddle

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
  padding-top: 25px;
  padding-bottom: 95px;
}

#container1 {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="primary-content">
  <p class="intro">
    Austin, Texas is not only the capital.
    <br>It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.
  </p>
  <div id="container2">
    <div id="container1">
      <div id="About">
        <h2>About</h2>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus.
          Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam
          scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum. .
        </p>
        <!-- Column one end -->
      </div>
      <div id="Capitalbuilding">
        <!-- Column two start -->
        <img src="https://image.ibb.co/e90Vhw/419796506_db7f02aedd_b.jpg" alt="picture of the Capital Building">
        <!-- Column two end -->
      </div>
    </div>
  </div>

</div>
<!-- End .primary-content --></code>```

Body:
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other.

Here is the result I would like

Here is what I am getting (fail)

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
  padding-top: 25px;
  padding-bottom: 95px;
}

  Austin, Texas is not only the capital.
It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.

About

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum.

Body:
You could use flexbox here to get started.

Add...

#container1 {
  display: flex;
}

Guide to flexbox here.

fiddle

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
  padding-top: 25px;
  padding-bottom: 95px;
}

#container1 {
  display: flex;
}

<div class="primary-content">
  <p class="intro">
    Austin, Texas is not only the capital.
    <br>It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.
  </p>
  <div id="container2">
    <div id="container1">
      <div id="About">
        <h2>About</h2>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus.
          Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam
          scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum. .
        </p>
        <!-- Column one end -->
      </div>
      <div id="Capitalbuilding">
        <!-- Column two start -->
        <img src="https://image.ibb.co/e90Vhw/419796506_db7f02aedd_b.jpg" alt="picture of the Capital Building">
        <!-- Column two end -->
      </div>
    </div>
  </div>

</div>
<!-- End .primary-content -->


问:
How do I know when an AVPlayer video has ended?
Scenario: iOS device automatically plays a video via AVPlayer upon entering an AVPlayerViewController.

How do I detect when the AVPlayer has finished?

答:
Just in case it helps someone.
And I know its in Obj-C, but I had to add this to some old code ;)</p>

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

    NSString *stringVideoName = @"myVideo.mp4";
    NSString *stringVideoPath = [[NSBundle mainBundle] pathForResource:stringVideoName ofType:nil];

    NSURL *urlVideoFile = [NSURL fileURLWithPath:stringVideoPath];

    _playerViewController = [[AVPlayerViewController alloc] init];
    _playerViewController.player = [AVPlayer playerWithURL:urlVideoFile];
    _playerViewController.view.frame = self.videoView.bounds;
    _playerViewController.showsPlaybackControls = YES;

    // Identify when the player time position jumps.
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(playerItemTimeJumped:) name:AVPlayerItemTimeJumpedNotification object:_playerViewController.player.currentItem];

    [self.videoView addSubview:_playerViewController.view];
    self.videoView.autoresizesSubviews = YES;
}

- (void)playerItemTimeJumped:(NSNotification*)notification {
    AVPlayerItem *playerItem = notification.object;

    if (playerItem.status == AVPlayerItemStatusReadyToPlay) {
        [NSNotificationCenter.defaultCenter removeObserver:self name:AVPlayerItemTimeJumpedNotification object:notification.object];
// The video play button has been pressed only once. Tell someone about it.
        }
    }
</code>```

Body:
Just in case it helps someone.
And I know its in Obj-C, but I had to add this to some old code ;)

- (void)setupVideo {

    NSString *stringVideoName = @"myVideo.mp4";
    NSString *stringVideoPath = [[NSBundle mainBundle] pathForResource:stringVideoName ofType:nil];

    NSURL *urlVideoFile = [NSURL fileURLWithPath:stringVideoPath];

    _playerViewController = [[AVPlayerViewController alloc] init];
    _playerViewController.player = [AVPlayer playerWithURL:urlVideoFile];
    _playerViewController.view.frame = self.videoView.bounds;
    _playerViewController.showsPlaybackControls = YES;

    // Identify when the player time position jumps.
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(playerItemTimeJumped:) name:AVPlayerItemTimeJumpedNotification object:_playerViewController.player.currentItem];

    [self.videoView addSubview:_playerViewController.view];
    self.videoView.autoresizesSubviews = YES;
}

- (void)playerItemTimeJumped:(NSNotification*)notification {
    AVPlayerItem *playerItem = notification.object;

    if (playerItem.status == AVPlayerItemStatusReadyToPlay) {
        [NSNotificationCenter.defaultCenter removeObserver:self name:AVPlayerItemTimeJumpedNotification object:notification.object];
// The video play button has been pressed only once. Tell someone about it.
        }
    }


问:
Spring boot deployment
I am developing a spring boot rest API for mobile application (without view or JSP pages) , I am deploying the API on a windows server (dedicated) , I installed the tomcat server and MySQL server on the server , when I am trying to access the application from the server localhost everything is ok , ex:  localhost:8080/api/users, but when I am trying to access it from another pc using my server IP  I get cannot reach ex:  162.144.188.112:8080/api/users
the same thing happens when I want to access MySQL server using server IP.

so I do not  know is there any issue in my server , or I just miss something in the  configuration for MySQL and tomcat server ?

答:
Try to figure out if your server is accepting the connections. It seem's that your server port is not listening or is blocked.
if you use linux enter systemctl status httpd
and see the status of your server
Also note that spring boot has embeded tomcat so you don't need to install tomcap manualy. </p>

Title: Spring boot deployment


问:
How to compare array of dates (Strings) with single date in swift 3
I have array of dates (strings) which are coming from local data base like following.

```<code>datesFromDBArray:["04/12/2017 07:10:41", "04/12/2017 07:12:17", "04/12/2017 07:13:54", "04/12/2017 07:17:45", "04/12/2017 07:18:56", "05/12/2017"]
</code>```

Here, same date can have multiple times.

Also from same data base, I am getting some other data called actions.

```<code>ActionsDBArray:["1", "6", "1", "1", "1", "2", "2", "2", "4", "1", "5", "2", "3"]
</code>```

these above two data getting from local database. And both arrays number of count is equal.

Now, I am getting number of dates from server response. That is like

```<code>TotalDaysServerArray:["22/11/2017 11:59:59", "23/11/2017 11:59:58", "24/11/2017 11:59:57"]
</code>```

Here, I am showing TotalDaysServerArray data in table view.

So, here, If user pressed on first cell like 22/11/2017 11:59:59, I need to check this date (not time, only same date) is existed in datesFromDBArray, if existed, then need to check how many indexes its existed, and need to fetch ActionsDBArray same indexes data.

So, I need to get the list of ActionsDBArray indexes and need to show the list of that in some other place.

I have tried some logic which was not worked, so, I am posting query here.

Can anyone suggest me, how to achieve this?

答:
It's child's play , Don't know where you stuck in logic

Note: I have added First object manually in  04/12/2017 07:10:41 to test the logic

```<code>var datesFromDBArray = ["04/12/2017 07:10:41", "04/12/2017 07:12:17", "04/12/2017 07:13:54", "04/12/2017 07:17:45", "04/12/2017 07:18:56", "05/12/2017"]
var ActionsDBArray = ["1", "6", "1", "1", "1", "2", "2", "2", "4", "1", "5", "2", "3"]
var TotalDaysServerArray = ["04/12/2017 11:59:59","22/11/2017 11:59:59", "23/11/2017 11:59:58", "24/11/2017 11:59:57"]

let findingValue =  TotalDaysServerArray.first!

print(findingValue)

let index = datesFromDBArray.index { (string) -> Bool in
    string.components(separatedBy: " ").first == findingValue.components(separatedBy: " ").first
}
print(index)

if let i = index {
    print("Your Object in ActionsDBArray \(ActionsDBArray[i])")
 }
</code>```

Output :

04/12/2017 11:59:59

Optional(0)

Your Object in ActionsDBArray 1

Hope it is helpful to you

Body:
I have array of dates (strings) which are coming from local data base like following.

datesFromDBArray:["04/12/2017 07:10:41", "04/12/2017 07:12:17", "04/12/2017 07:13:54", "04/12/2017 07:17:45", "04/12/2017 07:18:56", "05/12/2017"]

Here, same date can have multiple times.

Also from same data base, I am getting some other data called actions.

ActionsDBArray:["1", "6", "1", "1", "1", "2", "2", "2", "4", "1", "5", "2", "3"]

these above two data getting from local database. And both arrays number of count is equal.

Now, I am getting number of dates from server response. That is like

TotalDaysServerArray:["22/11/2017 11:59:59", "23/11/2017 11:59:58", "24/11/2017 11:59:57"]

Here, I am showing TotalDaysServerArray data in table view.

So, here, If user pressed on first cell like 22/11/2017 11:59:59, I need to check this date (not time, only same date) is existed in datesFromDBArray, if existed, then need to check how many indexes its existed, and need to fetch ActionsDBArray same indexes data.

So, I need to get the list of ActionsDBArray indexes and need to show the list of that in some other place.

I have tried some logic which was not worked, so, I am posting query here.

Can anyone suggest me, how to achieve this?

Body:
It's child's play , Don't know where you stuck in logic

Note: I have added First object manually in  04/12/2017 07:10:41 to test the logic

var datesFromDBArray = ["04/12/2017 07:10:41", "04/12/2017 07:12:17", "04/12/2017 07:13:54", "04/12/2017 07:17:45", "04/12/2017 07:18:56", "05/12/2017"]
var ActionsDBArray = ["1", "6", "1", "1", "1", "2", "2", "2", "4", "1", "5", "2", "3"]
var TotalDaysServerArray = ["04/12/2017 11:59:59","22/11/2017 11:59:59", "23/11/2017 11:59:58", "24/11/2017 11:59:57"]

let findingValue =  TotalDaysServerArray.first!

print(findingValue)

let index = datesFromDBArray.index { (string) -> Bool in
    string.components(separatedBy: " ").first == findingValue.components(separatedBy: " ").first
}
print(index)

if let i = index {
    print("Your Object in ActionsDBArray \(ActionsDBArray[i])")
 }

Output :

04/12/2017 11:59:59

Optional(0)

Your Object in ActionsDBArray 1

Hope it is helpful to you


问:
Is there any way to hide AWS lambda code?
I want to publish my application and provide lambdas to other so that I want that on exporting the lambda package no one can get the lambda code.</p>

答:
Ideal way is to use API gateway and use it as trigger for your Lambda and share that endpoint to the users.

However if you don't want that you should probably consider cross account access with cross account role (give permission to execute just the Lamnda you want to expose & setup trust relationship) . Let them assume this role and call this lambda.


问:
Could not establish Memcached connection
I'm trying to create a connection from my PHP application to Memcache, however I keep getting the error 'Could not establish Memcached connection'.

Here's my package version information

```<code>Laravel Version: 5.0.32
PHP Version:5.4.39-0+deb7u2
Database Driver & Version:mysql Ver 14.14 Distrib 5.5.31
Server&Version :Debian:7.1.
-memcached:1.4.13-0.2
-php5-memcached:2.0.1-6
</code>```

I have ensured that memcached is running, as executing service memcached status yields "memcached is running".

I have two servers where my project is deployed:

ubuntu, with memcached:2.1.0 installed

debian, with memcached:2.0.1 installed

Is there a version conflict?

答:
i solved the problem with
sudo apt-get install memcached
sudo service memcached status
sudo service memcached start

Body:
I'm trying to create a connection from my PHP application to Memcache, however I keep getting the error 'Could not establish Memcached connection'.

Here's my package version information

Laravel Version: 5.0.32
PHP Version:5.4.39-0+deb7u2
Database Driver & Version:mysql Ver 14.14 Distrib 5.5.31
Server&Version :Debian:7.1.
-memcached:1.4.13-0.2
-php5-memcached:2.0.1-6

I have ensured that memcached is running, as executing service memcached status yields "memcached is running".

I have two servers where my project is deployed:

ubuntu, with memcached:2.1.0 installed

debian, with memcached:2.0.1 installed

Is there a version conflict?


问:
DoCmd.PrintOut does only Print one copy
I saw that there is a similar question as mine but the workaround that is given there is not a possible way for me.
I have to print up to 1000 or more.

```<code> DoCmd.OpenReport Report, acViewReport 'Open report
 DoCmd.PrintOut , , , acHigh, copys' Print report
</code>```

(As copys I have specified the amount of copys.)

Did I do something wrong?

Is there an other way to print the Report out?

Thanks for any help.

complete Code:

```<code>Private Sub cmd_openreport_Click()

'Set Variables
Dim Report
Dim Etikette
Dim Copyes As String
Dim SQLString
Dim SQLString2

DoCmd.SetWarnings False 'Turns Off Warnings

Etikette = comb_etiketten_auswahl 'Etikette Equals the             comb_etiketten_auswahl value
Report = comb_etiketten_layout 'Report equals the value in the dropdown list
Copyes = Forms!frm_Hauptmenu!comb_etiketten_auswahl.Column(1)

'If The Etiketten Dropdown is empty message to client
If Etikette <> "" Then

'Do Nothing/Continue

Else
MsgBox "Bitte wählen Sie einen Datensatz aus"
Exit Sub

End If

'If The Report Dropdown is empty message to client
If Report <> "" Then

'Do Nothing (because dropdown is mot empty)

Else
MsgBox "Bitte wählen Sie ein Etikettenlayout aus"
Exit Sub

End If

MsgBox anzahl
'If Amount of copies is less than 1 message to client
If anzahl > 0 Then

On Error GoTo Error_MayCauseAnError
    DoCmd.OpenReport Report, acViewReport 'Open report
    DoCmd.PrintOut , , , , Copyes
    DoCmd.Close Report ' Close the Report
</code>```

EDIT :

This question is Irelevant and does not have a purpose anymore!
it was an internal script mistake!

答:
I don't think I understand why you have "Copies" right after "PrintOut". All you want is to print a certain number of copies, right? You can simply put

```<code>DoCmd.PrintOut , , , , copys 'Print report
</code>```

Alternatively, you should also be able to just write

```<code>DoCmd.PrintOut Copies:=copys 'Print report
</code>```

You don't need to write acHigh as that is the default value

Title: DoCmd.PrintOut does only Print one copy

Body:
I saw that there is a similar question as mine but the workaround that is given there is not a possible way for me.
I have to print up to 1000 or more.

 DoCmd.OpenReport Report, acViewReport 'Open report
 DoCmd.PrintOut , , , acHigh, copys' Print report

(As copys I have specified the amount of copys.)

Did I do something wrong?

Is there an other way to print the Report out?

Thanks for any help.

complete Code:

Private Sub cmd_openreport_Click()

'Set Variables
Dim Report
Dim Etikette
Dim Copyes As String
Dim SQLString
Dim SQLString2

DoCmd.SetWarnings False 'Turns Off Warnings

Etikette = comb_etiketten_auswahl 'Etikette Equals the             comb_etiketten_auswahl value
Report = comb_etiketten_layout 'Report equals the value in the dropdown list
Copyes = Forms!frm_Hauptmenu!comb_etiketten_auswahl.Column(1)

'If The Etiketten Dropdown is empty message to client
If Etikette <> "" Then

'Do Nothing/Continue

Else
MsgBox "Bitte wählen Sie einen Datensatz aus"
Exit Sub

End If

'If The Report Dropdown is empty message to client
If Report <> "" Then

'Do Nothing (because dropdown is mot empty)

Else
MsgBox "Bitte wählen Sie ein Etikettenlayout aus"
Exit Sub

End If

MsgBox anzahl
'If Amount of copies is less than 1 message to client
If anzahl > 0 Then

On Error GoTo Error_MayCauseAnError
    DoCmd.OpenReport Report, acViewReport 'Open report
    DoCmd.PrintOut , , , , Copyes
    DoCmd.Close Report ' Close the Report

EDIT :

This question is Irelevant and does not have a purpose anymore!
it was an internal script mistake!

Body:
I don't think I understand why you have "Copies" right after "PrintOut". All you want is to print a certain number of copies, right? You can simply put

DoCmd.PrintOut , , , , copys 'Print report

Alternatively, you should also be able to just write

DoCmd.PrintOut Copies:=copys 'Print report

You don't need to write acHigh as that is the default value


问:
Passing a string variable between two functions in Python
I am having trouble passing a variable from one function to another:

```<code>def name():

    first_name=input("What is your name? ")

    if len(first_name)==0:
            print("\nYou did not enter a name!")
            return name()

    else:
            print("\nHello %s." % first_name)
            return surname()

def surname():

    last_name=input("\nCan you tell my your last name please?")

    if len(last_name)==0:
            print("\nYou did not enter a last name!")
            return surname()
    else:

            print("Nice to meet you %s %s." % (first_name,last_name))
</code>```

I want the last command to print the inputed first_name from def name() and last name from def surname()

I always get the error that first_name is not defined and I do not know how to import it from the first function. The error I get is:

```<code>    print("Nice to meet you %s %s." % (first_name,last_name))
NameError: name 'first_name' is not defined
</code>```

What am I doing wrong?

答:
You need to pass the information in the function call:</p>

```<code>def name():

    first_name = input("What is your name? ")

    if len(first_name) == 0:
        print("\nYou did not enter a name!")
        return name()

    else:
        print("\nHello %s." % first_name)
        surname(first_name)  # pass first_name on to the surname function

def surname(first_name): #first_name arrives here ready to be used in this function

    last_name = input("\nCan you tell my your last name please?")

    if len(last_name) == 0:
        print("\nYou did not enter a last name!")
        surname(first_name)
    else:
        print("Nice to meet you %s %s." % (first_name,last_name))

name()
</code>```

Body:
I am having trouble passing a variable from one function to another:

def name():

    first_name=input("What is your name? ")

    if len(first_name)==0:
            print("\nYou did not enter a name!")
            return name()

    else:
            print("\nHello %s." % first_name)
            return surname()

def surname():

    last_name=input("\nCan you tell my your last name please?")

    if len(last_name)==0:
            print("\nYou did not enter a last name!")
            return surname()
    else:

            print("Nice to meet you %s %s." % (first_name,last_name))

I want the last command to print the inputed first_name from def name() and last name from def surname()

I always get the error that first_name is not defined and I do not know how to import it from the first function. The error I get is:

    print("Nice to meet you %s %s." % (first_name,last_name))
NameError: name 'first_name' is not defined

What am I doing wrong?

Body:
You need to pass the information in the function call:

def name():

    first_name = input("What is your name? ")

    if len(first_name) == 0:
        print("\nYou did not enter a name!")
        return name()

    else:
        print("\nHello %s." % first_name)
        surname(first_name)  # pass first_name on to the surname function

def surname(first_name): #first_name arrives here ready to be used in this function

    last_name = input("\nCan you tell my your last name please?")

    if len(last_name) == 0:
        print("\nYou did not enter a last name!")
        surname(first_name)
    else:
        print("Nice to meet you %s %s." % (first_name,last_name))

name()