问:
How do you make an Ajax call to Google Drive API?
My code can get an auth2.0 token...but the examples I've found don't show the final piece of taking a GET, provided here, and turning it into a working request.

Here is the specific URL from that link:

```<code>GET https://www.googleapis.com/drive/v3/files/fileId
</code>```

Here is my AJAX call with the attempt at getting the token (that works) into a hardcoded fileId that I know my Google account has access to.

```<code>$.ajax({
  type: "GET",
  beforeSend: function(request) {
    request.setRequestHeader("Authorization", "Bearer" + token);
  },
  // url: "https://www.googleapis.com/drive/v2/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI/permissions",
  url: "https://www.googleapis.com/drive/v3/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI",
  dataType: 'application/json',
  processData: true,
  success: function(msg) {
    console.log('Got File Metadata: ' + msg) + console.log(msg);
  },
  error: function (jqXHR, textStatus, errorThrown) {
    console.log('Error: ' + errorThrown + ' / ' + textStatus) + console.log(jqXHR);
  }
});
</code>```

I don't understand how to include the token and the pages and pages of Google documentation do not include any examples of going this route.

I get "invalid credential" errors in the server response.

I don't want to use GAPI because I ran into invalid cookie issues running locally and my code is in a Chrome Extension and it isn't clear whether that approach will work there.

Thank you for any help or direction.

答:
In your code, this line:

```<code>request.setRequestHeader("Authorization", "Bearer" + token);
</code>```

You should have a space after Bearer

```<code>request.setRequestHeader("Authorization", "Bearer " + token);
</code>```

Body:
My code can get an auth2.0 token...but the examples I've found don't show the final piece of taking a GET, provided here, and turning it into a working request.

Here is the specific URL from that link:

GET https://www.googleapis.com/drive/v3/files/fileId

Here is my AJAX call with the attempt at getting the token (that works) into a hardcoded fileId that I know my Google account has access to.

$.ajax({
  type: "GET",
  beforeSend: function(request) {
    request.setRequestHeader("Authorization", "Bearer" + token);
  },
  // url: "https://www.googleapis.com/drive/v2/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI/permissions",
  url: "https://www.googleapis.com/drive/v3/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI",
  dataType: 'application/json',
  processData: true,
  success: function(msg) {
    console.log('Got File Metadata: ' + msg) + console.log(msg);
  },
  error: function (jqXHR, textStatus, errorThrown) {
    console.log('Error: ' + errorThrown + ' / ' + textStatus) + console.log(jqXHR);
  }
});

I don't understand how to include the token and the pages and pages of Google documentation do not include any examples of going this route.

I get "invalid credential" errors in the server response.

I don't want to use GAPI because I ran into invalid cookie issues running locally and my code is in a Chrome Extension and it isn't clear whether that approach will work there.

Thank you for any help or direction.

Body:
In your code, this line:

request.setRequestHeader("Authorization", "Bearer" + token);

You should have a space after Bearer

request.setRequestHeader("Authorization", "Bearer " + token);


来源: stackexchange

问:
Microsoft.NETCore.App 2.0.3
I updated an asp.net core 2 app with updated nuget packages.  Boom, my web app nolonger compiles.  I get the error shown below.  I tried to go in and manually change the versions by editing the csproj, but I seemed to be causing more harm than good.  Anyone have an idea how to resolve this?

Severity    Code    Description Project File    Line    Suppression State
Error   NU1605  Detected package downgrade: Microsoft.NETCore.App from 2.0.3 to 2.0.0. Reference the package directly from the project to select a different version.
 BWD.ASPNET.Core -> Microsoft.EntityFrameworkCore.Tools.DotNet 2.0.1 -> Microsoft.NETCore.App (>= 2.0.3)
 BWD.ASPNET.Core -> Microsoft.NETCore.App (>= 2.0.0)    BWD.ASPNET.Core E:\BWDCore\BWD.ASPNET.Core\BWD.ASPNET.Core\BWD.ASPNET.Core.csproj   1

答:
I think Microsoft.EntityFrameworkCore.Tools.DotNet Version="2.0.1" has a dependency issue. It says it requires Microsoft.NETCore.App (>= 2.0.3).

We went back to Microsoft.EntityFrameworkCore.Tools.DotNet Version="2.0.0", and it all just worked.

ContentLicense: CC BY-SA 3.0

Title: Microsoft.NETCore.App 2.0.3


问:
How to Get Groups of Files from GetFiles()
I have to process files everyday.  The files are named like so:

```<code> fg1a.mmddyyyy
 fg1b.mmddyyyy
 fg1c.mmddyyyy

 fg2a.mmddyyyy
 fg2b.mmddyyyy
 fg2c.mmddyyyy
 fg2d.mmddyyyy
</code>```

If the entire file group is there for a particular date, I can process it.  If it isn't there, I should not process it.  I may have several partial file groups that run over several days.  So when I have fg1a.12062017, fg1b.12062017 and fg1c.12062017, I can process that group (fg1) only.

Here is my code so far.  It doesn't work because I can't figure out how to get only the full groups to add to the the processing file list.

```<code>        fileList = Directory.GetFiles(@"c:\temp\");

        string[] fileGroup1 = { "FG1A", "FG1B", "FG1C" }; // THIS IS A FULL GROUP
        string[] fileGroup2 = { "FG2A", "FG2B", "FG2C", "FG2D" };

        List<string> fileDates = new List<string>();
        List<string> procFileList;

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        bool allFiles = true;
        foreach (string fg in fileGroup1)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }

                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }

            }

        }

        foreach (string fg in fileGroup2)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }
                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }
            }

        }
</code>```

Any help or advice would be greatly appreciated.

答:
First, create an array of the groups to make processing easier:

```<code>var fileGroups = new[] {
        new[] { "FG1A", "FG1B", "FG1C" },
        new[] { "FG2A", "FG2B", "FG2C", "FG2D" }
    };
</code>```

Then you can convert the array into a Dictionary to map each name back to its group:

```<code>var fileGroupMap = fileGroups.SelectMany(g => g.Select(f => new { key = f, group = g })).ToDictionary(g => g.key, g => g.group);
</code>```

Then, preprocess the files you get from the directory:

```<code>var fileList = from fname in Directory.GetFiles(...)
               select new {
                   fname,
                   fdate = Path.GetExtension(fname),
                   ffilename = Path.GetFileNameWithoutExtension(fname).ToUpper()
               };
</code>```

Now you can take your fileList and group by date and group, and then filter to just completed groups:

```<code>var profFileList = (from file in fileList
                    group file by new { file.fdate, fgroup = fileGroupMap[file.ffilename] } into fng
                    where fng.Key.fgroup.All(f => fng.Select(fn => fn.ffilename).Contains(f))
                    from fn in fng
                    select fn.fname).ToList();
</code>```

Since you didn't preserve the groups, I flattened the groups at the end of the query into just a list of files to be processed. If you needed, you could keep them in groups and process the groups instead.

Note: If a file exists that belongs to no group, you will get an error from the lookup in fileGroupMap. If that is a possiblity you can filter the fileList to just known names as follows:

```<code>var fileList = from fname in GetFiles
               let ffilename = Path.GetFileNameWithoutExtension(fname).ToUpper()
               where fileGroupMap.Keys.Contains(ffilename)
               select new {
                   fname,
                   fdate = Path.GetExtension(fname),
                   ffilename
               };
</code>```

Also note that having a name in multiple groups will cause an error in the creation of fileGroupMap. If that is a possibility, the queries would become more complex and have to be written differently.

Body:
I have to process files everyday.  The files are named like so:

 fg1a.mmddyyyy
 fg1b.mmddyyyy
 fg1c.mmddyyyy

 fg2a.mmddyyyy
 fg2b.mmddyyyy
 fg2c.mmddyyyy
 fg2d.mmddyyyy

If the entire file group is there for a particular date, I can process it.  If it isn't there, I should not process it.  I may have several partial file groups that run over several days.  So when I have fg1a.12062017, fg1b.12062017 and fg1c.12062017, I can process that group (fg1) only.

Here is my code so far.  It doesn't work because I can't figure out how to get only the full groups to add to the the processing file list.

        fileList = Directory.GetFiles(@"c:\temp\");

        string[] fileGroup1 = { "FG1A", "FG1B", "FG1C" }; // THIS IS A FULL GROUP
        string[] fileGroup2 = { "FG2A", "FG2B", "FG2C", "FG2D" };

        List<string> fileDates = new List<string>();
        List<string> procFileList;

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        bool allFiles = true;
        foreach (string fg in fileGroup1)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }

                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }

            }

        }

        foreach (string fg in fileGroup2)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }
                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }
            }

        }

Any help or advice would be greatly appreciated.

Body:
First, create an array of the groups to make processing easier:

var fileGroups = new[] {
        new[] { "FG1A", "FG1B", "FG1C" },
        new[] { "FG2A", "FG2B", "FG2C", "FG2D" }
    };

Then you can convert the array into a Dictionary to map each name back to its group:

var fileGroupMap = fileGroups.SelectMany(g => g.Select(f => new { key = f, group = g })).ToDictionary(g => g.key, g => g.group);

Then, preprocess the files you get from the directory:

var fileList = from fname in Directory.GetFiles(...)
               select new {
                   fname,
                   fdate = Path.GetExtension(fname),
                   ffilename = Path.GetFileNameWithoutExtension(fname).ToUpper()
               };

Now you can take your fileList and group by date and group, and then filter to just completed groups:

var profFileList = (from file in fileList
                    group file by new { file.fdate, fgroup = fileGroupMap[file.ffilename] } into fng
                    where fng.Key.fgroup.All(f => fng.Select(fn => fn.ffilename).Contains(f))
                    from fn in fng
                    select fn.fname).ToList();

Since you didn't preserve the groups, I flattened the groups at the end of the query into just a list of files to be processed. If you needed, you could keep them in groups and process the groups instead.

Note: If a file exists that belongs to no group, you will get an error from the lookup in fileGroupMap. If that is a possiblity you can filter the fileList to just known names as follows:

var fileList = from fname in GetFiles
               let ffilename = Path.GetFileNameWithoutExtension(fname).ToUpper()
               where fileGroupMap.Keys.Contains(ffilename)
               select new {
                   fname,
                   fdate = Path.GetExtension(fname),
                   ffilename
               };

Also note that having a name in multiple groups will cause an error in the creation of fileGroupMap. If that is a possibility, the queries would become more complex and have to be written differently.


问:
Exception calling LoadPropertiesForItems in Exchange Web Services

Exception calling "LoadPropertiesForItems" with "2" argument(s):
  "Value cannot be null. Parameter name: items" At line:20 char:1
  + $response = $service.LoadPropertiesForItems($results, [Microsoft.Exch ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : ArgumentNullException

I run the script below and get this error. Only thing I changed in the script is mailbox Identity in line 11. I don't know much about EWS. Can anyone help?

```<code>add-pssnapin Microsoft.Exchange.Management.PowerShell.snapin

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1)
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind
$service.AutodiscoverUrl($aceuser.mail.ToString())

$MailboxName = get-mailbox -Identity w2kadmin@GoodSam.Org

$folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName.PrimarySmtpAddress.ToString())
$rootfolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $folderidcnt)

$offset = 0;
$view = new-object Microsoft.Exchange.WebServices.Data.ItemView(10000, $offset)

$response = $service.LoadPropertiesForItems($results, [Microsoft.Exchange.WebServices.Data.PropertySet]::FirstClassProperties)

foreach ($mail in $results){

if ($mail.ToString() -eq "Microsoft.Exchange.WebServices.Data.EmailMessage") {
    $mailSubject = $mail.Subject
    $mailProps = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent)
    $mail.Load($mailProps)
    #TODO: clean up $mailSubject so it's filesystem friendly
    $fStream = New-Object System.IO.FileStream("C:\Temp\$mailSubject.eml", [System.IO.FileMode]::Create)
    $fStream.Write($mail.MimeContent.Content, 0, $mail.MimeContent.Content.Length)
    $fStream.Close()
}
}
</code>```

Thank you Glen. I have 3 emails the mailbox I try to export. Your script exports first email and throws this:
New-Object : Exception calling ".ctor" with "2" argument(s): "Illegal characters in path."
At line:26 char:28
+ ...  $fStream = New-Object System.IO.FileStream("C:\Temp\$mailSubject.eml ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Exception calling "Write" with "3" argument(s): "Cannot access a closed file."
At line:27 char:17
+ ...             $fStream.Write($mail.MimeContent.Content, 0, $mail.MimeCo ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ObjectDisposedException

New-Object : Exception calling ".ctor" with "2" argument(s): "The given path's format is not supported."
At line:26 char:28
+ ...  $fStream = New-Object System.IO.FileStream("C:\Temp\$mailSubject.eml ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Exception calling "Write" with "3" argument(s): "Cannot access a closed file."
At line:27 char:17
+ ...             $fStream.Write($mail.MimeContent.Content, 0, $mail.MimeCo ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ObjectDisposedException

答:
Your missing a FindItems Call all you don't need to use LoadProperitesFromItems because you making a call to load the MimeContent in your iteration. A basic fix would be

```<code>    $dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
    [void][Reflection.Assembly]::LoadFile($dllpath)
    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1)
    $windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
    $aceuser = [ADSI]$sidbind
    $service.AutodiscoverUrl($aceuser.mail.ToString())

    $MailboxName = get-mailbox -Identity w2kadmin@GoodSam.Org

    $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName.PrimarySmtpAddress.ToString())
    $rootfolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $folderidcnt)

    $offset = 0;
    $view = new-object Microsoft.Exchange.WebServices.Data.ItemView(1000, $offset)
    $results = $null
    do{
        $results = $rootfolder.FindItems($view)
        foreach ($mail in $results.Items){
            if ($mail -is [Microsoft.Exchange.WebServices.Data.EmailMessage])
            {
                $mailSubject = $mail.Subject
                $mailProps = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent)
                $mail.Load($mailProps)
                #TODO: clean up $mailSubject so it's filesystem friendly
                $fStream = New-Object System.IO.FileStream("C:\Temp\$mailSubject.eml", [System.IO.FileMode]::Create)
                $fStream.Write($mail.MimeContent.Content, 0, $mail.MimeContent.Content.Length)
                $fStream.Close()
            }
        }
        $view.Offset += $result.Items.Count
    }while($results.MoreAvailable -eq $true)
</code>```

This code will pretty much page through every item in the Inbox and download each message as an EML file.

Body:
Exception calling "LoadPropertiesForItems" with "2" argument(s):
  "Value cannot be null. Parameter name: items" At line:20 char:1
  + $response = $service.LoadPropertiesForItems($results, [Microsoft.Exch ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : ArgumentNullException

I run the script below and get this error. Only thing I changed in the script is mailbox Identity in line 11. I don't know much about EWS. Can anyone help?

add-pssnapin Microsoft.Exchange.Management.PowerShell.snapin

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1)
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind
$service.AutodiscoverUrl($aceuser.mail.ToString())

$MailboxName = get-mailbox -Identity w2kadmin@GoodSam.Org

$folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName.PrimarySmtpAddress.ToString())
$rootfolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $folderidcnt)

$offset = 0;
$view = new-object Microsoft.Exchange.WebServices.Data.ItemView(10000, $offset)

$response = $service.LoadPropertiesForItems($results, [Microsoft.Exchange.WebServices.Data.PropertySet]::FirstClassProperties)

foreach ($mail in $results){

if ($mail.ToString() -eq "Microsoft.Exchange.WebServices.Data.EmailMessage") {
    $mailSubject = $mail.Subject
    $mailProps = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent)
    $mail.Load($mailProps)
    #TODO: clean up $mailSubject so it's filesystem friendly
    $fStream = New-Object System.IO.FileStream("C:\Temp\$mailSubject.eml", [System.IO.FileMode]::Create)
    $fStream.Write($mail.MimeContent.Content, 0, $mail.MimeContent.Content.Length)
    $fStream.Close()
}
}

Thank you Glen. I have 3 emails the mailbox I try to export. Your script exports first email and throws this:
New-Object : Exception calling ".ctor" with "2" argument(s): "Illegal characters in path."
At line:26 char:28
+ ...  $fStream = New-Object System.IO.FileStream("C:\Temp\$mailSubject.eml ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Exception calling "Write" with "3" argument(s): "Cannot access a closed file."
At line:27 char:17
+ ...             $fStream.Write($mail.MimeContent.Content, 0, $mail.MimeCo ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ObjectDisposedException

New-Object : Exception calling ".ctor" with "2" argument(s): "The given path's format is not supported."
At line:26 char:28
+ ...  $fStream = New-Object System.IO.FileStream("C:\Temp\$mailSubject.eml ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Exception calling "Write" with "3" argument(s): "Cannot access a closed file."
At line:27 char:17
+ ...             $fStream.Write($mail.MimeContent.Content, 0, $mail.MimeCo ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ObjectDisposedException

Body:
Your missing a FindItems Call all you don't need to use LoadProperitesFromItems because you making a call to load the MimeContent in your iteration. A basic fix would be

    $dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
    [void][Reflection.Assembly]::LoadFile($dllpath)
    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1)
    $windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
    $aceuser = [ADSI]$sidbind
    $service.AutodiscoverUrl($aceuser.mail.ToString())

    $MailboxName = get-mailbox -Identity w2kadmin@GoodSam.Org

    $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName.PrimarySmtpAddress.ToString())
    $rootfolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $folderidcnt)

    $offset = 0;
    $view = new-object Microsoft.Exchange.WebServices.Data.ItemView(1000, $offset)
    $results = $null
    do{
        $results = $rootfolder.FindItems($view)
        foreach ($mail in $results.Items){
            if ($mail -is [Microsoft.Exchange.WebServices.Data.EmailMessage])
            {
                $mailSubject = $mail.Subject
                $mailProps = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent)
                $mail.Load($mailProps)
                #TODO: clean up $mailSubject so it's filesystem friendly
                $fStream = New-Object System.IO.FileStream("C:\Temp\$mailSubject.eml", [System.IO.FileMode]::Create)
                $fStream.Write($mail.MimeContent.Content, 0, $mail.MimeContent.Content.Length)
                $fStream.Close()
            }
        }
        $view.Offset += $result.Items.Count
    }while($results.MoreAvailable -eq $true)

This code will pretty much page through every item in the Inbox and download each message as an EML file.


问:
Matrix containing integers instead of doubles in Matlab
I have a large vector containing integers (length: 230 400, int8) which I rearrange into a 3-dimensional matrix (rows: 240, cols: 320, depth: 3). When this has been done the new matrix contains doubles instead of ints (according to Matlab Workspace).

The whole operation takes 0.3 seconds, which is to long for my purposes.

Is Matlab converting the ints in the array to doubles before putting them in the matrix?
Can this be avoided to speed it up?

Some code:

```<code>   tic;
   A=zeros(240,320,3);
   %A is matrix, B is vector.

   for i=1:240
       for j=1:320
           A(i,j,:)=B(1+(j-1)*3+(i-1)*320*3:3+(j-1)*3+(i-1)*320*3);
       end
   end

   toc;
</code>```

Thanks!

答:
Just use reshape on B. This is faster and will preserve the class of B.</p>

```<code>A = reshape(B,[3,320,240]); %# makes a 3-by-320-by-240 array and distributes elements of B
A = permute(A,[3 2 1]);     %# turns A into a 240-by-320-by-3 array
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a large vector containing integers (length: 230 400, int8) which I rearrange into a 3-dimensional matrix (rows: 240, cols: 320, depth: 3). When this has been done the new matrix contains doubles instead of ints (according to Matlab Workspace).

The whole operation takes 0.3 seconds, which is to long for my purposes.

Is Matlab converting the ints in the array to doubles before putting them in the matrix?
Can this be avoided to speed it up?

Some code:

   tic;
   A=zeros(240,320,3);
   %A is matrix, B is vector.

   for i=1:240
       for j=1:320
           A(i,j,:)=B(1+(j-1)*3+(i-1)*320*3:3+(j-1)*3+(i-1)*320*3);
       end
   end

   toc;

Thanks!

Body:
Just use reshape on B. This is faster and will preserve the class of B.

A = reshape(B,[3,320,240]); %# makes a 3-by-320-by-240 array and distributes elements of B
A = permute(A,[3 2 1]);     %# turns A into a 240-by-320-by-3 array


问:
What does the enteredPassword = passwordEntry.get() command do?
What does the    enteredPassword = passwordEntry.get()    command do in this context:

```<code>import Tkinter as tk
window = tk.Tk()

def checkPassword():
    password = "Oranges"
    enteredPassword = passwordEntry.get()
    if password == enteredPassword:
        confirmLabel.config(text="Correct")
    else:
        confirmLabel.config(text="Incorrect")

passwordLabel = tk.Label(window, text="Password:")
passwordEntry = tk.Entry(window, show="*")

button = tk.Button(window, text="Enter", command=checkPassword)
confirmLabel = tk.Label(window)

passwordLabel.pack()
passwordEntry.pack()
button.pack()
confirmLabel.pack()

window.mainloop()
</code>```

Thank you!

答:
passwordEntry is a Tkinter.Entry object. The documentation states:

.get()

Returns the entry's current text as a string.

Body:
What does the    enteredPassword = passwordEntry.get()    command do in this context:

import Tkinter as tk
window = tk.Tk()

def checkPassword():
    password = "Oranges"
    enteredPassword = passwordEntry.get()
    if password == enteredPassword:
        confirmLabel.config(text="Correct")
    else:
        confirmLabel.config(text="Incorrect")

passwordLabel = tk.Label(window, text="Password:")
passwordEntry = tk.Entry(window, show="*")

button = tk.Button(window, text="Enter", command=checkPassword)
confirmLabel = tk.Label(window)

passwordLabel.pack()
passwordEntry.pack()
button.pack()
confirmLabel.pack()

window.mainloop()

Thank you!


问:
An hello world app ,but cause err "image not found"
Just a Hello world app.
I create a view-based appllication named it Hello World.
then save ,build and
I double click the app under products.
cause the error:

```<code>Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000002, 0x0000000000000000
Crashed Thread:  0
Dyld Error Message:
  Library not loaded: /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics
  Referenced from: /Users/myname/Documents/Control Fun/build/Debug-iphonesimulator/Control Fun.app/Control Fun
  Reason: image not found
</code>```

I googled and tyied many ideas.Unluckily I can't slove it.
Thanks in advance!

答:
You can't run iOS apps directly on Mac OS X. You either have to run a build compiled for the simulator within the iOS Simulator, or a build for the device directly on your iPhone, iPod touch or iPad.

When you double-click the item in Xcode's Products group, you're essentially trying to launch the app directly. Just hit "Build and Run" instead and it should launch in the iOS Simulator or on an attached device, depending on your settings.

Btw: if this really is an iOS related question, you should remove or replace the "cocoa" tag from your OP. Cocoa is Mac, Cocoa Touch is iOS.

Body:
Just a Hello world app.
I create a view-based appllication named it Hello World.
then save ,build and
I double click the app under products.
cause the error:

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000002, 0x0000000000000000
Crashed Thread:  0
Dyld Error Message:
  Library not loaded: /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics
  Referenced from: /Users/myname/Documents/Control Fun/build/Debug-iphonesimulator/Control Fun.app/Control Fun
  Reason: image not found

I googled and tyied many ideas.Unluckily I can't slove it.
Thanks in advance!


问:
Integrating IoT device with Google Home
I am currently working on a IoT device to control lights. This device is implemented using FreeRTOS.

I am little confused how to provide Google Home integration with this device, could someone shed some light on this.

答:
You can use the Smart Home API. The Google Assistant works with a webhook, sending commands to SYNC, QUERY, and EXECUTE on that URL. You will then need to send these commands to your device.

Setup happens through the Google Assistant app, where users must link with your OAuth server.

Here is a sample project for Smart Home, using virtual devices.

Title: Integrating IoT device with Google Home


问:
Socket.io opening multiple connections with React-Native
I built a server with an API. It uses Axios for the un-logged calls and Socket.io for the logged calls.
Then I have a website connected to it. And that works perfectly.
But I have also an application built in react-native which has a strange behavior: it opens connections on every emit without closing them previous connections. As you can see below, I console.log the websocket.engine.clientsCount on the server. Every time I emit from the phone-application it opens a new connection, finding the server with an increasing number of it.

On server, I user following versions:

```<code>"connect-mongo": "^1.3.2",
"express": "^4.14.1",
"express-session": "^1.12.1",
"jwt-simple": "^0.5.1",
"mongodb": "^2.2.30",
"mongoose": "^4.11.5",
"passport": "^0.3.2",
"passport-jwt": "^2.2.1",
"passport-local": "^1.0.0",
"socket.io": "^1.7.3",
"socketio-jwt": "^4.5.0"
</code>```

Here the code of the API. I removed some code for clarity.

```<code>const passport = require('passport');
const express = require('express');
const session = require('express-session');
const http = require('http');
const morgan = require('morgan');
const mongoose = require('mongoose');
const socketio = require('socket.io');
const bodyParser = require('body-parser');
const socketioJwt   = require("socketio-jwt"); // da commentare
const Users = require('../models/users');

const passportService = require('./services/passport');

const requireAuth = passport.authenticate('jwt', {session: false});
const requireLogin = passport.authenticate('local', {session: false});
const config = require('./config');

const app = express();
const socketRouter = require('./services/socketRouter');
const MongoStore = require('connect-mongo')(session);

const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost/blablabla';
mongoose.connect(mongoUri);
...
const server = http.Server(app);
const websocket = socketio(server);

// add authorization for jwt-passport when first connection -> https://github.com/auth0/socketio-jwt
websocket.use(socketioJwt.authorize({
  secret: config.secret,
  handshake: true
}));

const sessionMiddleware = session({
  store: new MongoStore({ // use MongoDb to store session (re-using previous connection)
    mongooseConnection: mongoose.connection,
    ttl: (1 * 60 * 60)
  }),
  secret: config.secretSession,
  httpOnly: true,
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 86400000 }
});
app.use(sessionMiddleware);
...
websocket.on('connection', (socket) => {
    Users.findById(socket.decoded_token.sub, function(err, user) {
        if (err) { console.log('the user wasn\'t find in database', err); }
        if (user) {
            socket.join(user._id);
            console.log('Clients connected: ', websocket.engine.clientsCount);

            // ------ PROTECTED EVENTS ------ //
            ...
            // ------------------------------ //

        }

        socket.on('disconnect', ()=> {
          socket.leave(user._id);
          onsole.log('user disconnected');
        });
    });
});
...
</code>```

I won't put the initialisation of the website because it works good.

On mobile application, I user following versions:

```<code>"react-native": "^0.41.0",
"react-native-keychain": "^1.1.0",
"socket.io-client": "^1.7.3",
"socketio-jwt": "^4.5.0"
</code>```

Here is the innitialisation of the react-native application.

```<code>import * as Keychain from 'react-native-keychain';
import { BASIC_WS_URL } from '../api';

const io = require('socket.io-client/dist/socket.io');
const socketEvents = require('./events');

exports = module.exports = (store) => {
  Keychain.getGenericPassword().then((credentials) => {
    if (credentials && credentials !== false) {
      const { password } = credentials;
      const websocket = io(BASIC_WS_URL, {
        jsonp: false,
        transports: ['websocket'], // you need to explicitly tell it to use websockets
        query: {
          token: password
        }
      });

      websocket.connect();
      websocket.on('connect', (socket) => {
        console.log('Connected');
      });

      websocket.on('reconnect', (socket) => {
        console.log('Re-connected');
      });

      websocket.on('disconnect', (socket) => {
        console.log('Disconnected');
      });
      // all the events to listen
      socketEvents(websocket, store);
    }
  });
};
</code>```

What al I doing wrong?

答: You shouldn't put your socket.io instance inside react native component. Instead put them inside your index file. So it won't be triggered during the react lifecycle event</p>

Body:
I built a server with an API. It uses Axios for the un-logged calls and Socket.io for the logged calls.
Then I have a website connected to it. And that works perfectly.
But I have also an application built in react-native which has a strange behavior: it opens connections on every emit without closing them previous connections. As you can see below, I console.log the websocket.engine.clientsCount on the server. Every time I emit from the phone-application it opens a new connection, finding the server with an increasing number of it.

On server, I user following versions:

"connect-mongo": "^1.3.2",
"express": "^4.14.1",
"express-session": "^1.12.1",
"jwt-simple": "^0.5.1",
"mongodb": "^2.2.30",
"mongoose": "^4.11.5",
"passport": "^0.3.2",
"passport-jwt": "^2.2.1",
"passport-local": "^1.0.0",
"socket.io": "^1.7.3",
"socketio-jwt": "^4.5.0"

Here the code of the API. I removed some code for clarity.

const passport = require('passport');
const express = require('express');
const session = require('express-session');
const http = require('http');
const morgan = require('morgan');
const mongoose = require('mongoose');
const socketio = require('socket.io');
const bodyParser = require('body-parser');
const socketioJwt   = require("socketio-jwt"); // da commentare
const Users = require('../models/users');

const passportService = require('./services/passport');

const requireAuth = passport.authenticate('jwt', {session: false});
const requireLogin = passport.authenticate('local', {session: false});
const config = require('./config');

const app = express();
const socketRouter = require('./services/socketRouter');
const MongoStore = require('connect-mongo')(session);

const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost/blablabla';
mongoose.connect(mongoUri);
...
const server = http.Server(app);
const websocket = socketio(server);

// add authorization for jwt-passport when first connection -> https://github.com/auth0/socketio-jwt
websocket.use(socketioJwt.authorize({
  secret: config.secret,
  handshake: true
}));

const sessionMiddleware = session({
  store: new MongoStore({ // use MongoDb to store session (re-using previous connection)
    mongooseConnection: mongoose.connection,
    ttl: (1 * 60 * 60)
  }),
  secret: config.secretSession,
  httpOnly: true,
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 86400000 }
});
app.use(sessionMiddleware);
...
websocket.on('connection', (socket) => {
    Users.findById(socket.decoded_token.sub, function(err, user) {
        if (err) { console.log('the user wasn\'t find in database', err); }
        if (user) {
            socket.join(user._id);
            console.log('Clients connected: ', websocket.engine.clientsCount);

            // ------ PROTECTED EVENTS ------ //
            ...
            // ------------------------------ //

        }

        socket.on('disconnect', ()=> {
          socket.leave(user._id);
          onsole.log('user disconnected');
        });
    });
});
...

I won't put the initialisation of the website because it works good.

On mobile application, I user following versions:

"react-native": "^0.41.0",
"react-native-keychain": "^1.1.0",
"socket.io-client": "^1.7.3",
"socketio-jwt": "^4.5.0"

Here is the innitialisation of the react-native application.

import * as Keychain from 'react-native-keychain';
import { BASIC_WS_URL } from '../api';

const io = require('socket.io-client/dist/socket.io');
const socketEvents = require('./events');

exports = module.exports = (store) => {
  Keychain.getGenericPassword().then((credentials) => {
    if (credentials && credentials !== false) {
      const { password } = credentials;
      const websocket = io(BASIC_WS_URL, {
        jsonp: false,
        transports: ['websocket'], // you need to explicitly tell it to use websockets
        query: {
          token: password
        }
      });

      websocket.connect();
      websocket.on('connect', (socket) => {
        console.log('Connected');
      });

      websocket.on('reconnect', (socket) => {
        console.log('Re-connected');
      });

      websocket.on('disconnect', (socket) => {
        console.log('Disconnected');
      });
      // all the events to listen
      socketEvents(websocket, store);
    }
  });
};

What al I doing wrong?


问:
Output listbox to multiple cells to use for autofilter array
So I have a multiselect listbox that users choose regions they want to filter in a dataset.

I currently output those selections into a single cell using this sub:

```<code>Dim listItems As String, i As Long
With RegionListBox
    For i = 0 To .ListCount - 1
        If .Selected(i) Then listItems = listItems & .List(i) & ", "
    Next i
End With

Range("AA1") = Left(listItems, Len(listItems) - 2)
</code>```

At the end of the macro users run to update their workbook, I want to apply a filter using the values that I have output from the listbox. Currently this is how I do it:

```<code>Worksheets("4. Booking Summary").Range("$A$1:$G$1000" _
).AutoFilter Field:=4, Criteria1:=(Range("$AA$1").Value),` Operator:=xlFilterValues
</code>```

Unfortunately this doesn't work, as if users have selected multiple choices, the output in AA1 will be formatted like "text, text, text". When it tries to apply this filter, it applies a text filter with that full string. For it to have the desired function it would need to filter using an array with each selected item.

I'm a bit stuck on how to achieve this. My thought was I need to output each listbox selection to a single cell, then set the autofilter criteria to an array referencing those cells. I'm just not sure how to do this. Happy for any suggestions.

答:
You can use Split() to create an array:</p>

```<code>Criteria1:=Split(Range("$AA$1").Value,", ")
</code>```

Body:
So I have a multiselect listbox that users choose regions they want to filter in a dataset.

I currently output those selections into a single cell using this sub:

Dim listItems As String, i As Long
With RegionListBox
    For i = 0 To .ListCount - 1
        If .Selected(i) Then listItems = listItems & .List(i) & ", "
    Next i
End With

Range("AA1") = Left(listItems, Len(listItems) - 2)

At the end of the macro users run to update their workbook, I want to apply a filter using the values that I have output from the listbox. Currently this is how I do it:

Worksheets("4. Booking Summary").Range("$A$1:$G$1000" _
).AutoFilter Field:=4, Criteria1:=(Range("$AA$1").Value),` Operator:=xlFilterValues

Unfortunately this doesn't work, as if users have selected multiple choices, the output in AA1 will be formatted like "text, text, text". When it tries to apply this filter, it applies a text filter with that full string. For it to have the desired function it would need to filter using an array with each selected item.

I'm a bit stuck on how to achieve this. My thought was I need to output each listbox selection to a single cell, then set the autofilter criteria to an array referencing those cells. I'm just not sure how to do this. Happy for any suggestions.

Body:
You can use Split() to create an array:

Criteria1:=Split(Range("$AA$1").Value,", ")


问:
How do I setup my scraper to run multiple spiders using a script or exe?
I'm into my 3rd scrapy project and I'm getting a little bolder.
I want to give this program to non-technical users so either cmd line or preferably .exe

First off, I started using Crawler.Process, using the documentation I came up with this:

```<code>process = CrawlerProcess()
process.crawl(FirstSpider)
process.crawl(SecondSpider)
process.crawl(ThirdSpider)
process.crawl(LastSpider)
process.start()
</code>```

Each spider is in its own .py file so I've imported each one into one spider and put this block of code at the bottom, if there's a better way I'm all ears.

I tried running this as is, in the command dialogue and it returns an error saying the scraper.list doesn't exist when I try to import the other spiders.

I can run each scraper from within the file using the VS code terminal using typical scrapy crawl xyz... so how do we wrap it up for end users?

Thanks in advance.

答:
Thanks Furas, I apologize for the omission, I ended up solving my own problem. The script was too deep in the file structure and I had to move it further up. It was unable to read the Scraper.items folder contents because it wasn't traveling up then back down the file path.

I've almost wrapped up this project but I'm having trouble with the exporter, I've posted that question here:
Using Scrapy JsonItemsLinesExporter, returns no value

Body:
I'm into my 3rd scrapy project and I'm getting a little bolder.
I want to give this program to non-technical users so either cmd line or preferably .exe

First off, I started using Crawler.Process, using the documentation I came up with this:

process = CrawlerProcess()
process.crawl(FirstSpider)
process.crawl(SecondSpider)
process.crawl(ThirdSpider)
process.crawl(LastSpider)
process.start()

Each spider is in its own .py file so I've imported each one into one spider and put this block of code at the bottom, if there's a better way I'm all ears.

I tried running this as is, in the command dialogue and it returns an error saying the scraper.list doesn't exist when I try to import the other spiders.

I can run each scraper from within the file using the VS code terminal using typical scrapy crawl xyz... so how do we wrap it up for end users?

Thanks in advance.


问:
Will the application review the auto renewable subscription?
I'm developing an application that looks like a dialogue with another person. Some dialog branches are paid and are available only when the subscription is activated. When user click on this thread, we ask that him purchase it. When a person activates a subscription, he also has access to some paid video, audio, and a restriction on viewing the news section. We would like to use the Autorenewable subscription with a plan for a month. But will our application go through the review? maybe there are still some approaches to enable the user to activate auto-subscriptions to our application.
Thank you in advance for your cooperation</p>

答:
Yes, this should be an ok use of IAP, however reviewers can act randomly so you may get a different result.

I would make sure that when a user encounters a path that is premium, you don't just initiate an in-app-purchase but you present the user with a "paywall", a screen that says the content is for purchase and show them the price and allow them to purchase. If you are too aggressive, Apple may reject your application.


问:
Declaring ImageGallery properties from within an ImageObject: Can you nest an itemtype from its parent with a different itemtype?
I’m new to Microdata and using Schema.org properties and have a question regarding the scope of itemscope.

I’m creating an itemtype="http://schema.org/ImageGallery" in the  tag. Two of its properties are mainContentOfPage and primaryImageOfPage.

However when I use them nested inside of an ImageObject declaration, Google says:

ImageObject is not a known valid target type for the mainContentOfPage  & primaryImageOfPage property.

Does each element NOT inherit the itemscope from its parent? Which seems to be the case, as I’m getting the above validation error from the Google testing tool.

Unfortunately the ImageObject doesn’t seem to use most of the ImageGallery properties.

Any pointers on what I’m doing wrong would be greatly appreciated.

{Caption}

{Caption}

```

答:
itemprop applies to its nearest parent itemscope.

You can’t use properties of types that are applied to parent itemscopes, you can only use the properties of the type that is applied to the nearest parent itemscope.

```

<p>In your example, there are two separate issues with the use of Schema.org.</p>

<h3>Schema.org: Range (values of a property)</h3>

<p>Each Schema.org property has one or more <em>expected types</em>. For the <code>mainContentOfPage</code> property, the expected type is <code>WebPageElement</code>.</p>

<p>In your example, you are adding <code>mainContentOfPage</code> to the <code>ImageGallery</code> (which is fine), and you provide an <code>ImageObject</code> value for <code>mainContentOfPage</code> (which is not fine). <code>WebPageElement</code> is not a parent type of <code>ImageObject</code>, so <code>ImageObject</code> is not an expected value. It’s technically/formally allowed, but Google’s SDTT typically recognizes the stated expected types and gives errors when using something else.</p>

<p>If you want to convey that the images are part of the image gallery, you could use Schema.org’s <code>hasPart</code> property:</p>

<pre class="lang-html prettyprint-override"><code><main itemscope itemtype="http://schema.org/ImageGallery">

  <article itemprop="hasPart" itemscope itemtype="http://schema.org/ImageObject"></article>

</main>
</code>```

(alternative to hasPart: adding a list that contains all images (mainEntity ItemList))

Schema.org: Domain (properties of a type)

Each Schema.org property has one or more types to which it can be added. For the primaryImageOfPage property, the type is WebPage.

In your example, you are adding the primaryImageOfPage property to an ImageObject, but WebPage is not a parent type of ImageObject.

ImageGallery can have the primaryImageOfPage property, because ImageGallery is a more specific WebPage. So if you want to convey that one of the images in the gallery is the primary image, you could use:

```

Body:
itemprop applies to its nearest parent itemscope.

You can’t use properties of types that are applied to parent itemscopes, you can only use the properties of the type that is applied to the nearest parent itemscope.

<div itemscope itemtype="http://schema.org/Person">
  <!-- you can only use 'Person' properties here -->

  <div itemprop="owns" itemscope itemtype="http://schema.org/Product">
    <!-- you can only use 'Product' properties here,
         not 'Person' properties -->

    <div itemprop="manufacturer" itemscope itemtype="http://schema.org/Organization">
      <!-- you can only use 'Organization' properties here,
           not 'Person'/'Product' properties -->
    </div>

  </div>

</div>

In your example, there are two separate issues with the use of Schema.org.

Schema.org: Range (values of a property)

Each Schema.org property has one or more expected types. For the mainContentOfPage property, the expected type is WebPageElement.

In your example, you are adding mainContentOfPage to the ImageGallery (which is fine), and you provide an ImageObject value for mainContentOfPage (which is not fine). WebPageElement is not a parent type of ImageObject, so ImageObject is not an expected value. It’s technically/formally allowed, but Google’s SDTT typically recognizes the stated expected types and gives errors when using something else.

If you want to convey that the images are part of the image gallery, you could use Schema.org’s hasPart property:

<main itemscope itemtype="http://schema.org/ImageGallery">

  <article itemprop="hasPart" itemscope itemtype="http://schema.org/ImageObject"></article>

</main>

(alternative to hasPart: adding a list that contains all images (mainEntity ItemList))

Schema.org: Domain (properties of a type)

Each Schema.org property has one or more types to which it can be added. For the primaryImageOfPage property, the type is WebPage.

In your example, you are adding the primaryImageOfPage property to an ImageObject, but WebPage is not a parent type of ImageObject.

ImageGallery can have the primaryImageOfPage property, because ImageGallery is a more specific WebPage. So if you want to convey that one of the images in the gallery is the primary image, you could use:

<main itemscope itemtype="http://schema.org/ImageGallery">

  <article itemprop="hasPart primaryImageOfPage" itemscope itemtype="http://schema.org/ImageObject"></article>

  <article itemprop="hasPart" itemscope itemtype="http://schema.org/ImageObject"></article>

</main>


问:
SQL Casting Assistance
```<code>INSERT INTO PRODUCTDIM (PROD_SKU, PROD_DESCRIPTION, PROD_TYPE, LGPRODUCT.BRAND_ID, BRAND_NAME, BRAND_TYPE)
    SELECT PROD_SKU, PROD_DESCRIPT, PROD_TYPE, lgproduct.BRAND_ID, BRAND_NAME, BRAND_TYPE
    FROM LGPRODUCT INNER JOIN LGBRAND ON lgproduct.brand_id = lgbrand.brand_id
</code>```

I am getting this error:

Conversion failed when converting the varchar value '1010-MIW' to data type int.

Need help

答: One of the fields in LGPRODUCT contains that string value, 1010-MIW, but that field in the [PRODUCTIM] table is an INTEGER, so it will only accept an integer number. You just need to compare the columns in each table to determine where the disconnect is.</p>

Title: SQL Casting Assistance

Body:
INSERT INTO PRODUCTDIM (PROD_SKU, PROD_DESCRIPTION, PROD_TYPE, LGPRODUCT.BRAND_ID, BRAND_NAME, BRAND_TYPE)
    SELECT PROD_SKU, PROD_DESCRIPT, PROD_TYPE, lgproduct.BRAND_ID, BRAND_NAME, BRAND_TYPE
    FROM LGPRODUCT INNER JOIN LGBRAND ON lgproduct.brand_id = lgbrand.brand_id

I am getting this error:

Conversion failed when converting the varchar value '1010-MIW' to data type int.

Need help


问:
How can I initialize and use 64-bit integer in Python3
The problem requires me to use 64-bit integer.
How can I initialize and implement that in python3?</p>

答:
Frankly, sometimes it is bad to use unlimited integers in Python. Best alternative is to use NumPy fixed length types if you really need exactly 32bit or 64bit ops.</p>

```<code>import numpy as np

v = np.uint64(99)
q = np.uint64(12) * v + np.uint64(77)

print(q)
print(type(q))
</code>```

Body:
Frankly, sometimes it is bad to use unlimited integers in Python. Best alternative is to use NumPy fixed length types if you really need exactly 32bit or 64bit ops.

import numpy as np

v = np.uint64(99)
q = np.uint64(12) * v + np.uint64(77)

print(q)
print(type(q))


问:
How to block a specific line of code from an iFrame?
Is there a way to block a particular line of code from being executed within a third-party website, appearing within an iFrame?

I have an embedded widget which is loading JQuery within the iFrame.  I don't need the extra network request, because my site is already loading JQuery.

If I can block only one line of code (in this case, line 77) then I can prevent JQuery from being loaded again.

I imagine this action would take place prior to the iFrame being rendered.

答:
The same-origin policy prevents you from touching any part of an iframe for a third-party website, so there's nothing you can directly do to prevent that request from being sent out. Even if you could, the iframe and your website have no shared state, so the other website will most likely break because it has no way to access your instance of jQuery. Think of what would happen if you loaded the third-party website in a new tab but blocked the request.

There are, however, a few things you can do to ensure the browser uses a cached copy of the library, which doesn't actually send a request anywhere:

If the external library is being loaded from a CDN, there's a good chance some other website has requested that same URL, so that user's browser has a cached copy of it.

Since you yourself use jQuery, you could use the other website's same version of jQuery. That way, a user's browser will have a cached copy of the file already from the CDN and no second request will be made.

Otherwise, if the website is using an old version of jQuery that you cannot yourself use or if it is being self-hosted without a CDN, there's nothing else you can do.


问:
Can Android route using both 3G and Wifi depending of name resolution failure?
I'm keeping my Samsung tablet always connected to a 360 camera (Ricoh Theta S with OSC API), trying to send 360 images to a custom server autonomously over 3G thanks to a homemade Android app, with no human supervision.

OSC specifications mention that the camera acts as a Wifi access point and devices connect to its ESSID on a local 192.168.0.* network to take pictures. After capturing the picture, Android prioritizes the Wifi in order to reach the server, and asks the camera's DNS to resolve example.com, which inevitably fails.

I must manually disconnect the Wifi interface from the camera to let Android establish the 3G connection and in the end send the iamges on example.com, which requires a manual operation that I don't want.

Problem is that Android's routing behaviour looks binary: 100% Wifi or 100% 3G. While I feel that I need a custom routing table, that would be somehting like :

192.168.0.* over Wifi
*.*.*.* over 3G

Samsung tablets have an Intelligent network features that can proactively switch between 3G and Wifi when connection is weak, but that does not fix the problem because I assume they make decisions according to the quality of the physical connection. So it does not switch to 3G even if example.com fails to resolve.

What's the next solution to make this autonomous? Disabling and enabling Wifi from the code does not ensure Android will reconnect to the right camera's ESSID afterwards, plus the camera goes to standby after a few minutes of Wifi disconnection.

Does rooting the tablet to modify the way Android prioritizes Wifi or 3G look feasible?

答:
First of all, let me answer your last question.

Yes, rooting should solve you problem. Any it's the only possible way to use Wi-Fi and cellular networks simultaneously.

To enable simultaneous connections on rooted device, execute:

```<code>pkill dhcpcd
svc wifi disable
svc data enable
netcfg wlan0 up
cd /data/misc/wifi/.
wpa_supplicant -B -Dnl80211 -iwlan0 -c/data/misc/wifi/wpa_supplicant.conf
dhcpcd wlan0
</code>```

and define desired routes:

```<code>ip route add x.x.x.x via x.x.x.y
</code>```

Body:
First of all, let me answer your last question.

Yes, rooting should solve you problem. Any it's the only possible way to use Wi-Fi and cellular networks simultaneously.

To enable simultaneous connections on rooted device, execute:

pkill dhcpcd
svc wifi disable
svc data enable
netcfg wlan0 up
cd /data/misc/wifi/.
wpa_supplicant -B -Dnl80211 -iwlan0 -c/data/misc/wifi/wpa_supplicant.conf
dhcpcd wlan0

and define desired routes:

ip route add x.x.x.x via x.x.x.y


问:
I'm having trouble running this program
```<code># Tipper Program
# User enters the bill total and the program computes two amounts,
# a 15 percent tip and a 20 percent tip

print("\t\t\t **  **  **  **  **  **  **  **  **  **")

print("\n\t\t\t\t    Tip Calculator")

print("\n\t\t\t **  **  **  **  **  **  **  **  **  **")

bill = input("\nPlease enter your restaurant's bill total: ")

tip_15 = bill * 0.15

tip_20 = bill * 0.20

float(print("\n\nA 15% tip for this bill comes out to ", tip_15))
float(print("\nA 20% tip for this bill comes out to ", tip_20))

input("\n\nPress the enter key to exit.")
</code>```

The app keeps closing after I enter the number for the bill total. Any recommendations to solve this issue?

答:
When you ask the user for input you need to cast this value to a float before you multiply it by 0.15 and 0.20

```<code>bill = float(input("\nPlease enter your restaurant's bill total: "))
</code>```

and also your last 2 lines should not be cast to a float

```<code>print("\n\nA 15% tip for this bill comes out to: ", tip_15)
print("\nA 20% tip for this bill comes out to: ", tip_20)
</code>```

Title: I'm having trouble running this program

Body:
# Tipper Program
# User enters the bill total and the program computes two amounts,
# a 15 percent tip and a 20 percent tip

print("\t\t\t **  **  **  **  **  **  **  **  **  **")

print("\n\t\t\t\t    Tip Calculator")

print("\n\t\t\t **  **  **  **  **  **  **  **  **  **")

bill = input("\nPlease enter your restaurant's bill total: ")

tip_15 = bill * 0.15

tip_20 = bill * 0.20

float(print("\n\nA 15% tip for this bill comes out to ", tip_15))
float(print("\nA 20% tip for this bill comes out to ", tip_20))

input("\n\nPress the enter key to exit.")

The app keeps closing after I enter the number for the bill total. Any recommendations to solve this issue?

Body:
When you ask the user for input you need to cast this value to a float before you multiply it by 0.15 and 0.20

bill = float(input("\nPlease enter your restaurant's bill total: "))

and also your last 2 lines should not be cast to a float

print("\n\nA 15% tip for this bill comes out to: ", tip_15)
print("\nA 20% tip for this bill comes out to: ", tip_20)


问:
How can I display acf metadata array in revolution slider
i'm trying to build a movie slider for a Cinema tv screen.
I started to build custom Fields using acf advanced custom fields in wordpress.

Everything is working except displaying acf metadata with more options.
The revolution slider and the grid now displays it like the word (array)
image displaying array
this is what I use to display custom fileds in the sliders

**in cornerstone**
{{acf:field_name}}

**in sidebar**
 [acf field="field_name"]

**in the grid**
#meta:field_name#

**in revolution slider**
{{meta:field_name}}

**in template**
*// simple*
<?php the_field('field_name'); ?>

*// multiple options*
<?php
 // vars
          $values = get_field('field_name');

          // check
          if( $values ): ?>

                 <?php foreach( $values as $value ): ?>

<?php echo $value; ?>

                  <?php endforeach; ?>

          <?php endif; ?>```

How can I make this work so it displays more options, like on the template page

Can somebody please help me

答:
Problem is that when using the {{meta:somemetatag}} filter with rev slider, it bypasses the acf helper functions, such as get_field(), that handle the heavy lifting involved when navigating the various types of objects and arrays when using the more complex ACF fields.  So the trick to getting those values to display properly in your rev slider is to use the native ACF shortcodes in combination with the revslider {{id}} filter.

For example, if you're attempting to display the return values from an acf select field in a post based Revolution Slider you could try the following:

[acf field="my_acf_field_name" post_id="{{id}}"]

This will output the my_acf_field_name ACF field for the current post being rendered by Revolution Slider.

Body:
i'm trying to build a movie slider for a Cinema tv screen.
I started to build custom Fields using acf advanced custom fields in wordpress.

Everything is working except displaying acf metadata with more options.
The revolution slider and the grid now displays it like the word (array)
image displaying array
this is what I use to display custom fileds in the sliders

**in cornerstone**
{{acf:field_name}}

**in sidebar**
 [acf field="field_name"]

**in the grid**
#meta:field_name#

**in revolution slider**
{{meta:field_name}}

**in template**
*// simple*
<?php the_field('field_name'); ?>

*// multiple options*
<?php
 // vars
          $values = get_field('field_name');

          // check
          if( $values ): ?>

                 <?php foreach( $values as $value ): ?>

<?php echo $value; ?>

                  <?php endforeach; ?>

          <?php endif; ?>

How can I make this work so it displays more options, like on the template page

Can somebody please help me


问:
Generate XML output to a fitting format to match my XSLT
Hey, I am writing a quiz application with Java Servlets. My quiz data is written into XML files, i.e.: <quiz><question><ask>...</ask><answer>...</answer>...</question></quiz>.

I want to display every question and their answers on a single page. For that reason, I cannot simply transform the XML to my XSLT as it would display only the first question or all questions. My guess is, I should load the XML data in order to create my own Java classes, i.e.: class Question, class Quiz, etc and generate from them a XML format which fits my XSLT displaying only one question at a time.

Is this approach the right way and if so, how is this realized?

If not, how is it done probably?

答:
I cannot simply transform the XML to my XSLT as it would display only the first question or all questions.

You are wrong. If you write your XSLT using templates and the correct XPath, a transform could output all of the questions that exist in one XML file, however many.

You can also use XPath to select specific question nodes, depending on attribute values (for example).

If you have the following template and use the right XPath to select all questions in an apply-templates, this template will be applied to each question, not just the first:

```<code><xsl:template match="question">

</xsl:template>
</code>```

Body:
I cannot simply transform the XML to my XSLT as it would display only the first question or all questions.

You are wrong. If you write your XSLT using templates and the correct XPath, a transform could output all of the questions that exist in one XML file, however many.

You can also use XPath to select specific question nodes, depending on attribute values (for example).

If you have the following template and use the right XPath to select all questions in an apply-templates, this template will be applied to each question, not just the first:

<xsl:template match="question">

</xsl:template>


问:
Remove app from whitelist in android marshmallow
I didn't find useful info how to programically or using device's settings remove specific app from white-listed.

In android 6.0 was introduced doze-mode and while-listed, the last term allows ignore partially doze-mode.

To put app in white-listed apps need to perform code:

```<code>Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
</code>```

I tried next actions to remove the app from white-listed, which it has  just been put, but nothing help me:

clear data application in settings

remove application and
install again

To check current list of while-listed appы there is posibility using dumpsys

```<code> adb shell dumpsys deviceidle
</code>```

Real help is changing package name of app.
I have an opinion that if application was put to white-listed so it cannot be never removed from there.

Phone MeizuU680h. In another devices haven't tests.

答:
you could add or remove from whitelist typing this on ADB shell

dumpsys deviceidle whitelist +YOUR.PACKAGE

dumpsys deviceidle whitelist -YOUR.PACKAGE

in my case I need to reboot and I don´t need Root access

Body:
I didn't find useful info how to programically or using device's settings remove specific app from white-listed.

In android 6.0 was introduced doze-mode and while-listed, the last term allows ignore partially doze-mode.

To put app in white-listed apps need to perform code:

Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);

I tried next actions to remove the app from white-listed, which it has  just been put, but nothing help me:

clear data application in settings

remove application and
install again

To check current list of while-listed appы there is posibility using dumpsys

 adb shell dumpsys deviceidle

Real help is changing package name of app.
I have an opinion that if application was put to white-listed so it cannot be never removed from there.

Phone MeizuU680h. In another devices haven't tests.


问:
Allow only one Google Form submission per user
I have a survey that expects no repeat responses. There does not appear to be any way to set this in the Google Forms controls, so I need to write a script. How do I ensure that I allow only one Google Form submission per unique username?

Consider a survey with a simple choice. If one submits "Choice A" and later repeats the survey to submit "Choice B", I'd like to disregard the latter submission; the choice that was just sent (B) would be deleted from the Google Sheet.

答:
Google Forms now have an option to limit one answer by user but they should have a Google account. You cand set this programatically setLimitOneResponsePerUser(Boolean)
 and to check this with hasLimitOneResponsePerUser().</p>


问:
bootstrap is enqueued but normalize.less doesn't show up
Putting the finishing touches up on this website but having a problem getting the normalize.less page to work. I hooked the bootstrap 3.3.7 cdn into the function.php file. I know bootstrap is loaded because the navbar and contact form depend on the bootstrap grid and they're in the right place.
The problem is perfectly demonstrated by the buttons (or lack there of). Message me is supposed to be outlined by a grey box shadow. The button also is not supposed to have any text decoration.

the website is www.mustafasprojects.com

if you open the source code you can see there is in fact a stylesheet and that the normalize.less file is loaded but not recognized.

答:
On chrome, inspect page, go to the network tab, Click the css filter then refresh.

I think you have something wrong with your path to normalize.css or your HTTP server rules. If I try to go to http://www.mustafasprojects.com/wp-content/themes/html5blank-stable/normalize.css?ver=1.0 - it doesn't bypass wordpress and tries to go a page.

Edit:
amnmustafa15 had style wrapped in a media query so that the styling wouldn't be applied using a standard browser window width.


问:
Finding nearby points using dictionaries
I am trying to find the nearest points in a dictionary to every other point. In this dict, the keys are point coordinates, which look like this

```<code>print d1
{(1, 1): 0, (2, 1): 1, (3, 1): 2, (10, 41):3}
</code>```

The output here should be another dictionary with the keys as each position and the values being a list of nearby points. A nearby point is defined as being +/- 1 away from any other point (if there are no nearby points, then something like "nan" can be set as a value).

For example, the output here should look like this:

```<code>{(1, 1): [(2,1)], (2, 1): [(1,1), (3,1)], (3, 1): [(2,1)], (10, 41): nan}
</code>```

答:
You can use list comprehension to iterate over the keys and values of the original dictionary and search for similar keys in the dictionary. Lasting, simple filtering will create "nan" if no result is found for any key:

```<code>d = {(1, 1): 0, (2, 1): 1, (3, 1): 2, (10, 41):3}
new_d = {a:[c for c, b in d.items() if any(abs(i-a[0]) == 1 or abs(i-a[-1])==1 for i in c) and c != a] for a, h in d.items()}
final_d = {a:"nan" if not b else b for a, b in new_d.items()}
</code>```

Alternative solution with math.hypot():

```<code>import math
new_d = {a:[c for c, b in d.items() if math.hypot(a[0]-c[0], a[1]-c[1])<= 1 and c != a] for a, h in d.items()}
final_d = {a:"nan" if not b else b for a, b in new_d.items()}
</code>```

Output:

```<code>{(3, 1): [(2, 1)], (10, 41): 'nan', (1, 1): [(2, 1)], (2, 1): [(3, 1), (1, 1)]}
</code>```

Body:
I am trying to find the nearest points in a dictionary to every other point. In this dict, the keys are point coordinates, which look like this

print d1
{(1, 1): 0, (2, 1): 1, (3, 1): 2, (10, 41):3}

The output here should be another dictionary with the keys as each position and the values being a list of nearby points. A nearby point is defined as being +/- 1 away from any other point (if there are no nearby points, then something like "nan" can be set as a value).

For example, the output here should look like this:

{(1, 1): [(2,1)], (2, 1): [(1,1), (3,1)], (3, 1): [(2,1)], (10, 41): nan}

Body:
You can use list comprehension to iterate over the keys and values of the original dictionary and search for similar keys in the dictionary. Lasting, simple filtering will create "nan" if no result is found for any key:

d = {(1, 1): 0, (2, 1): 1, (3, 1): 2, (10, 41):3}
new_d = {a:[c for c, b in d.items() if any(abs(i-a[0]) == 1 or abs(i-a[-1])==1 for i in c) and c != a] for a, h in d.items()}
final_d = {a:"nan" if not b else b for a, b in new_d.items()}

Alternative solution with math.hypot():

import math
new_d = {a:[c for c, b in d.items() if math.hypot(a[0]-c[0], a[1]-c[1])<= 1 and c != a] for a, h in d.items()}
final_d = {a:"nan" if not b else b for a, b in new_d.items()}

Output:

{(3, 1): [(2, 1)], (10, 41): 'nan', (1, 1): [(2, 1)], (2, 1): [(3, 1), (1, 1)]}


问:
React Native Gifted Chat - message no showing
I using this module for simple chatting React Native Gifted Chat, and I try the example to send some message. But nothing is showing up in the screen (no bubble no text), I console.log(this.state.messages); inside the render function, array of message is there.

Example I used:

```<code>import { GiftedChat } from 'react-native-gifted-chat';

class Example extends React.Component {

  state = {
    messages: [],
  };

  componentWillMount() {
    this.setState({
      messages: [
        {
          _id: 1,
          text: 'Hello developer',
          createdAt: new Date(),
          user: {
            _id: 2,
            name: 'React Native',
            avatar: 'https://facebook.github.io/react/img/logo_og.png',
          },
        },
      ],
    });
  }

  onSend(messages = []) {
    this.setState((previousState) => ({
      messages: GiftedChat.append(previousState.messages, messages),
    }));
  }

  render() {
    return (
      <GiftedChat
        messages={this.state.messages}
        onSend={(messages) => this.onSend(messages)}
        user={{
          _id: 1,
        }}
      />
    );
  }

}
</code>```

答:
Maybe you  need first import React and Component module:

```<code>import React, { Component } from "react"
</code>```

React Native Gifted Chat have nice working example with sending message:

https://github.com/FaridSafi/react-native-gifted-chat/tree/master/example

Body:
I using this module for simple chatting React Native Gifted Chat, and I try the example to send some message. But nothing is showing up in the screen (no bubble no text), I console.log(this.state.messages); inside the render function, array of message is there.

Example I used:

import { GiftedChat } from 'react-native-gifted-chat';

class Example extends React.Component {

  state = {
    messages: [],
  };

  componentWillMount() {
    this.setState({
      messages: [
        {
          _id: 1,
          text: 'Hello developer',
          createdAt: new Date(),
          user: {
            _id: 2,
            name: 'React Native',
            avatar: 'https://facebook.github.io/react/img/logo_og.png',
          },
        },
      ],
    });
  }

  onSend(messages = []) {
    this.setState((previousState) => ({
      messages: GiftedChat.append(previousState.messages, messages),
    }));
  }

  render() {
    return (
      <GiftedChat
        messages={this.state.messages}
        onSend={(messages) => this.onSend(messages)}
        user={{
          _id: 1,
        }}
      />
    );
  }

}

Body:
Maybe you  need first import React and Component module:

import React, { Component } from "react"

React Native Gifted Chat have nice working example with sending message:

https://github.com/FaridSafi/react-native-gifted-chat/tree/master/example


问:
RXJS. Lazy observable
I'm playing around with rxjs trying to understand one concept: reactive programming supposed to be lazy. If no one subscriber is attached to an observable, it shouldn't produce values. Here is my example:

const Rx = require('rxjs')

const state = new Rx.Subject()

const changeStateLazy = (args) =>
    Rx.Observable.of(args)
        // some logic, e.g. REST requests
        .do(val => state.next('new state'))

changeStateLazy(42)

const stateListener = state.subscribe(
    val => console.log('state.next: ', val),
    err => console.log('state.error: ', err),
    () => console.log('state.complete'))
```

How to make the observable (which in function changeStateLazy) lazy, i.e. run some logic... and change the state only if a listener is attached to state subject (in my case it's stateListener)?

答:
Not exactly sure what you want to achieve, but if you want to output the LAST value when an observer is subscribed, try "AsyncSubject".

```<code>const state = new Rx.AsyncSubject();
</code>```

For AsyncSubject to work, it needs to call the complete method.

```<code>const changeState = () =>
    Rx.Observable.of(1)
       .subscribe(val => {
          state.next('new state');
          state.complete();
        });
</code>```

You may want to use "BehaviorSubject", "BehaviorSubject", etc. if you want it to behave differently.

Title: RXJS. Lazy observable

Body:
I'm playing around with rxjs trying to understand one concept: reactive programming supposed to be lazy. If no one subscriber is attached to an observable, it shouldn't produce values. Here is my example:

const Rx = require('rxjs')

const state = new Rx.Subject()

const changeStateLazy = (args) =>
    Rx.Observable.of(args)
        // some logic, e.g. REST requests
        .do(val => state.next('new state'))

changeStateLazy(42)

const stateListener = state.subscribe(
    val => console.log('state.next: ', val),
    err => console.log('state.error: ', err),
    () => console.log('state.complete'))

How to make the observable (which in function changeStateLazy) lazy, i.e. run some logic... and change the state only if a listener is attached to state subject (in my case it's stateListener)?

Body:
Not exactly sure what you want to achieve, but if you want to output the LAST value when an observer is subscribed, try "AsyncSubject".

const state = new Rx.AsyncSubject();

For AsyncSubject to work, it needs to call the complete method.

const changeState = () =>
    Rx.Observable.of(1)
       .subscribe(val => {
          state.next('new state');
          state.complete();
        });

You may want to use "BehaviorSubject", "BehaviorSubject", etc. if you want it to behave differently.


问:
HTML/CSS/Javascript: Open/Close Menu when Clicking Button
I've got a hamburger icon for my page that should open/close a dropdown menu when clicked on. I pulled the code for the hamburger icon from Jonathan Suh's github page and am trying to implement a open/close dropdown menu with it (here's the page for your reference https://github.com/jonsuh/hamburgers).

The problem is that when I click on it, the dropdown menu will appear, but when I click on it again it won't disappear. I've tried a few things, such as setting a boolean variable to false and making it true when clicked on, but the code doesn't execute the way I imagine it would. Here's the Code:

//declarations
var hamburger = document.querySelector(".hamburger");

function dropDown() {
  document.querySelector(".dropdown-content").style.display = "block";

}

hamburger.addEventListener("click", function() {
  hamburger.classList.toggle("is-active");
  dropDown();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.show {
  display: block;
}

/*!
 * Hamburgers
 * @description Tasty CSS-animated hamburgers
 * @author Jonathan Suh @jonsuh
 * @site https://jonsuh.com/hamburgers
 * @link https://github.com/jonsuh/hamburgers
 */

.hamburger {
  padding: 15px 15px;
  display: inline-block;
  cursor: pointer;
  transition-property: opacity, filter;
  transition-duration: 0.15s;
  transition-timing-function: linear;
  font: inherit;
  color: inherit;
  text-transform: none;
  background-color: transparent;
  border: 0;
  margin: 0;
  overflow: visible;
}

.hamburger:hover {
  opacity: 0.7;
}

.hamburger-box {
  width: 40px;
  height: 24px;
  display: inline-block;
  position: relative;
}

.hamburger-inner {
  display: block;
  top: 50%;
  margin-top: -2px;
}

.hamburger-inner,
.hamburger-inner::before,
.hamburger-inner::after {
  width: 40px;
  height: 4px;
  background-color: #000;
  border-radius: 4px;
  position: absolute;
  transition-property: transform;
  transition-duration: 0.15s;
  transition-timing-function: ease;
}

.hamburger-inner::before,
.hamburger-inner::after {
  content: "";
  display: block;
}

.hamburger-inner::before {
  top: -10px;
}

.hamburger-inner::after {
  bottom: -10px;
}

/*
   * Spring
   */

.hamburger--spring .hamburger-inner {
  top: 2px;
  transition: background-color 0s 0.13s linear;
}

.hamburger--spring .hamburger-inner::before {
  top: 10px;
  transition: top 0.1s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring .hamburger-inner::after {
  top: 20px;
  transition: top 0.2s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring.is-active .hamburger-inner {
  transition-delay: 0.22s;
  background-color: transparent;
}

.hamburger--spring.is-active .hamburger-inner::before {
  top: 0;
  transition: top 0.1s 0.15s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(45deg);
}

.hamburger--spring.is-active .hamburger-inner::after {
  top: 0;
  transition: top 0.2s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(-45deg);
}</code>```

    <button onclick="dropDown()" class="hamburger hamburger--spring" type="button">

            Home
            Work
            Resume
            Life

    </button>

```

While I know there is probably a solution you can use in jQuery, I have no experience with that. So please, keep it in JavaScript. I am completely new to it, but have a basic understanding of how it works.

答:
Try to do some css like the one in my website

I use the code to monitor the attribute. You can use JS to change the attribute of the dropdown-content element.

So, put the following into your CSS

```<code>.dropdown-content[show='true']{
    position: absolute;
    margin-top: 50px;
    display: block;
 }
</code>```

Then change your JavaScript function to this:

```<code>function dropDown(){
    var drop=document.getElementById("myDropdown");
    if(drop.getAttribute("show")=="true"){
        drop.setAttribute("show","false");
    }else{
        drop.setAttribute("show","true");
    }
}
</code>```

For security, I suggest you to add show="false" to your dropdown-content element. You can also refer my website code to understand them more.

Body:
I've got a hamburger icon for my page that should open/close a dropdown menu when clicked on. I pulled the code for the hamburger icon from Jonathan Suh's github page and am trying to implement a open/close dropdown menu with it (here's the page for your reference https://github.com/jonsuh/hamburgers).

The problem is that when I click on it, the dropdown menu will appear, but when I click on it again it won't disappear. I've tried a few things, such as setting a boolean variable to false and making it true when clicked on, but the code doesn't execute the way I imagine it would. Here's the Code:

//declarations
var hamburger = document.querySelector(".hamburger");

function dropDown() {
  document.querySelector(".dropdown-content").style.display = "block";

}

hamburger.addEventListener("click", function() {
  hamburger.classList.toggle("is-active");
  dropDown();
});

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.show {
  display: block;
}

/*!
 * Hamburgers
 * @description Tasty CSS-animated hamburgers
 * @author Jonathan Suh @jonsuh
 * @site https://jonsuh.com/hamburgers
 * @link https://github.com/jonsuh/hamburgers
 */

.hamburger {
  padding: 15px 15px;
  display: inline-block;
  cursor: pointer;
  transition-property: opacity, filter;
  transition-duration: 0.15s;
  transition-timing-function: linear;
  font: inherit;
  color: inherit;
  text-transform: none;
  background-color: transparent;
  border: 0;
  margin: 0;
  overflow: visible;
}

.hamburger:hover {
  opacity: 0.7;
}

.hamburger-box {
  width: 40px;
  height: 24px;
  display: inline-block;
  position: relative;
}

.hamburger-inner {
  display: block;
  top: 50%;
  margin-top: -2px;
}

.hamburger-inner,
.hamburger-inner::before,
.hamburger-inner::after {
  width: 40px;
  height: 4px;
  background-color: #000;
  border-radius: 4px;
  position: absolute;
  transition-property: transform;
  transition-duration: 0.15s;
  transition-timing-function: ease;
}

.hamburger-inner::before,
.hamburger-inner::after {
  content: "";
  display: block;
}

.hamburger-inner::before {
  top: -10px;
}

.hamburger-inner::after {
  bottom: -10px;
}

/*
   * Spring
   */

.hamburger--spring .hamburger-inner {
  top: 2px;
  transition: background-color 0s 0.13s linear;
}

.hamburger--spring .hamburger-inner::before {
  top: 10px;
  transition: top 0.1s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring .hamburger-inner::after {
  top: 20px;
  transition: top 0.2s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring.is-active .hamburger-inner {
  transition-delay: 0.22s;
  background-color: transparent;
}

.hamburger--spring.is-active .hamburger-inner::before {
  top: 0;
  transition: top 0.1s 0.15s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(45deg);
}

.hamburger--spring.is-active .hamburger-inner::after {
  top: 0;
  transition: top 0.2s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(-45deg);
}

    <button onclick="dropDown()" class="hamburger hamburger--spring" type="button">

            Home
            Work
            Resume
            Life

    </button>

While I know there is probably a solution you can use in jQuery, I have no experience with that. So please, keep it in JavaScript. I am completely new to it, but have a basic understanding of how it works.

Body:
Try to do some css like the one in my website

I use the code to monitor the attribute. You can use JS to change the attribute of the dropdown-content element.

So, put the following into your CSS

.dropdown-content[show='true']{
    position: absolute;
    margin-top: 50px;
    display: block;
 }

Then change your JavaScript function to this:

function dropDown(){
    var drop=document.getElementById("myDropdown");
    if(drop.getAttribute("show")=="true"){
        drop.setAttribute("show","false");
    }else{
        drop.setAttribute("show","true");
    }
}

For security, I suggest you to add show="false" to your dropdown-content element. You can also refer my website code to understand them more.


问:
How to start browser and load url in symbian S60 Qt app?
I just want my app to start a browser and load an URL. I am using this code that compiles and runs on simulator, but nothing happens.

```<code>#include <QtGui>
#include <QDesktopServices>
#include <QUrl>

 int main(int argc, char *argv[])
 {
   QApplication app(argc, argv);

   QDesktopServices::openUrl(QUrl("http://www.google.com"));
   return app.exec();
  }
</code>```

Is it possible that there is something missing in my simulator( e.g browser), because i can't move through menus or do anything else (no menu at all). I have only installed Nokia Qt SDK (read this tutorial http://wiki.forum.nokia.com/index.php/Using_Qt_Creator_With_Symbian).

Thank you.

答: The simulator isn't an emulator - it doesn't emulate the entire OS, so you can't use it test code like this that launches the platform browser, and running the simulator won't give you a home-screen with menus and applications. </p>

Body:
I just want my app to start a browser and load an URL. I am using this code that compiles and runs on simulator, but nothing happens.

#include <QtGui>
#include <QDesktopServices>
#include <QUrl>

 int main(int argc, char *argv[])
 {
   QApplication app(argc, argv);

   QDesktopServices::openUrl(QUrl("http://www.google.com"));
   return app.exec();
  }

Is it possible that there is something missing in my simulator( e.g browser), because i can't move through menus or do anything else (no menu at all). I have only installed Nokia Qt SDK (read this tutorial http://wiki.forum.nokia.com/index.php/Using_Qt_Creator_With_Symbian).

Thank you.


问:
RunTimeException in SNMP4J agent
I have downloaded SNMP4J and I added it to buildpath of my project. Then I added some codes from http://shivasoft.in/blog/java/snmp/create-snmp-client-in-java-using-snmp4j/ and http://shivasoft.in/blog/java/snmp/creating-snmp-agent-server-in-java-using-snmp4j/ to check my agent. But now These strings printed in console:

```<code>Exception in thread "main" java.lang.RuntimeException: java.net.BindException: Address already in use: Cannot bind
    at org.snmp4j.transport.TransportMappings.createTransportMapping(TransportMappings.java:123)
    at org.bihe.SNMPAgent.initTransportMappings(SNMPAgent.java:145)
    at org.snmp4j.agent.BaseAgent.init(BaseAgent.java:144)
    at org.bihe.SNMPAgent.start(SNMPAgent.java:157)
    at org.bihe.TestSNMPAgent.init(TestSNMPAgent.java:35)
    at org.bihe.TestSNMPAgent.main(TestSNMPAgent.java:13)
Caused by: java.net.BindException: Address already in use: Cannot bind
    at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
    at java.net.DualStackPlainDatagramSocketImpl.bind0(Unknown Source)
    at java.net.AbstractPlainDatagramSocketImpl.bind(Unknown Source)
    at java.net.DatagramSocket.bind(Unknown Source)
    at java.net.DatagramSocket.<init>(Unknown Source)
    at java.net.DatagramSocket.<init>(Unknown Source)
    at org.snmp4j.transport.DefaultUdpTransportMapping.<init>(DefaultUdpTransportMapping.java:100)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.snmp4j.transport.TransportMappings.createTransportMapping(TransportMappings.java:104)
    ... 5 more
</code>```

I uploaded my hole project in mediafire:
https://www.mediafire.com/?lcyap63rs93qdwo
can anyone explain me, why the program throws these exceptions? I have not worked with snmp before and it is my first experience for a research in a network course.

答:
As noted by ooSNMP, some process is already using the port.  Either use a different port or stop the process.

Windows: There could be a service: SNMPT Trap on that was automatically listening for traps.  If you are on Windows this may be the issue.  This could be fixed by going to Services and stopping the service.  Make sure that you set the service to "manual", or it will eventually restart itself (this is done by right clicking on the service, selecting Properties and changing Startup Type.

Linux: You can find out about which application is using the port using the ss command.  You can kill the process using the kill command.

Title: RunTimeException in SNMP4J agent

Body:
I have downloaded SNMP4J and I added it to buildpath of my project. Then I added some codes from http://shivasoft.in/blog/java/snmp/create-snmp-client-in-java-using-snmp4j/ and http://shivasoft.in/blog/java/snmp/creating-snmp-agent-server-in-java-using-snmp4j/ to check my agent. But now These strings printed in console:

Exception in thread "main" java.lang.RuntimeException: java.net.BindException: Address already in use: Cannot bind
    at org.snmp4j.transport.TransportMappings.createTransportMapping(TransportMappings.java:123)
    at org.bihe.SNMPAgent.initTransportMappings(SNMPAgent.java:145)
    at org.snmp4j.agent.BaseAgent.init(BaseAgent.java:144)
    at org.bihe.SNMPAgent.start(SNMPAgent.java:157)
    at org.bihe.TestSNMPAgent.init(TestSNMPAgent.java:35)
    at org.bihe.TestSNMPAgent.main(TestSNMPAgent.java:13)
Caused by: java.net.BindException: Address already in use: Cannot bind
    at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
    at java.net.DualStackPlainDatagramSocketImpl.bind0(Unknown Source)
    at java.net.AbstractPlainDatagramSocketImpl.bind(Unknown Source)
    at java.net.DatagramSocket.bind(Unknown Source)
    at java.net.DatagramSocket.<init>(Unknown Source)
    at java.net.DatagramSocket.<init>(Unknown Source)
    at org.snmp4j.transport.DefaultUdpTransportMapping.<init>(DefaultUdpTransportMapping.java:100)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.snmp4j.transport.TransportMappings.createTransportMapping(TransportMappings.java:104)
    ... 5 more

I uploaded my hole project in mediafire:
https://www.mediafire.com/?lcyap63rs93qdwo
can anyone explain me, why the program throws these exceptions? I have not worked with snmp before and it is my first experience for a research in a network course.


问:
High Performance File I/O java API for file size of 300MB (max)
Building an Application, which is meant for only File I/O (could be pdf,jpg etc). Maximum file size can be 300MB. Application will be deployed on Linux 64 bit.
Tried the traditional blocking IO(FileOutputStream etc). But I am looking for Non-blocking or some better approach with good performance.

Here is the code that I am using right now.

```<code>FileOutputStream imageOutFile = new FileOutputStream("path/filename");
imageOutFile.write(byteArray);
imageOutFile.close();
</code>```

Please help me with better approach,code snippet for meeting this scenario.
Rest service will have input as filemetada and bytestream as input to my Service.

答:
All you need to do to your existing code is to use a BufferedOutputStream, thus:

```<code>OutputStream imageOutFile = new BufferedOutputStream(new FileOutputStream("path/filename"));
</code>```

This will make a substantial difference.

There is exactly zero reason to believe that a non-blocking API would be faster, even if it existed for file I/O in Java, which it doesn't.

If you know the output size exactly in advance, you could use a MappedByteBuffer, but you don't, so you can't.

Body:
Building an Application, which is meant for only File I/O (could be pdf,jpg etc). Maximum file size can be 300MB. Application will be deployed on Linux 64 bit.
Tried the traditional blocking IO(FileOutputStream etc). But I am looking for Non-blocking or some better approach with good performance.

Here is the code that I am using right now.

FileOutputStream imageOutFile = new FileOutputStream("path/filename");
imageOutFile.write(byteArray);
imageOutFile.close();

Please help me with better approach,code snippet for meeting this scenario.
Rest service will have input as filemetada and bytestream as input to my Service.

Body:
All you need to do to your existing code is to use a BufferedOutputStream, thus:

OutputStream imageOutFile = new BufferedOutputStream(new FileOutputStream("path/filename"));

This will make a substantial difference.

There is exactly zero reason to believe that a non-blocking API would be faster, even if it existed for file I/O in Java, which it doesn't.

If you know the output size exactly in advance, you could use a MappedByteBuffer, but you don't, so you can't.


问:
Caesar Cipher with Ascii Characters
I'm trying to encrypt a String using ascii characters with a key position integer. I've got two methods, one for encrypting, one for decrypting.

The problem is that when the character value is above 126, I try to mod 126 it and then add 32 back into it but I get numbers far out of these limits.

```<code>public static String encrypt(String s, int k) {
    char[] arr = s.toCharArray();
    int ascii;
    for(int i = 0; i < arr.length; i++) {
        ascii = (int) arr[i];
        ascii = ascii + k;
        // System.out.println(ascii);
        if (ascii > 126) {
            ascii = 32 + (126 % ascii);
            // System.out.print("Changed: " + ascii);
        }

        arr[i] = (char) ascii;
    }
    return String.valueOf(arr);
}
</code>```

The two commented out lines were for testing, and the changed values are crazy high, like instead of going from 127 % 126 = 1 + 32 for a total of 33 (intended value), I get 15870.

答:
Your modulo statement is written backwards for a start. Try:</p>

```<code>ascii = 32 + (ascii % 126);
</code>```

Title: Caesar Cipher with Ascii Characters

Body:
I'm trying to encrypt a String using ascii characters with a key position integer. I've got two methods, one for encrypting, one for decrypting.

The problem is that when the character value is above 126, I try to mod 126 it and then add 32 back into it but I get numbers far out of these limits.

public static String encrypt(String s, int k) {
    char[] arr = s.toCharArray();
    int ascii;
    for(int i = 0; i < arr.length; i++) {
        ascii = (int) arr[i];
        ascii = ascii + k;
        // System.out.println(ascii);
        if (ascii > 126) {
            ascii = 32 + (126 % ascii);
            // System.out.print("Changed: " + ascii);
        }

        arr[i] = (char) ascii;
    }
    return String.valueOf(arr);
}

The two commented out lines were for testing, and the changed values are crazy high, like instead of going from 127 % 126 = 1 + 32 for a total of 33 (intended value), I get 15870.

Body:
Your modulo statement is written backwards for a start. Try:

ascii = 32 + (ascii % 126);