问:
Passing value from HTML form to php variable
I'm trying to pass a value from an HTML form and store it to a php variable so i can use this variable into a query to determine what row to get from database. I'm using _post['category'] to get the selected value and I'm passing the variable to the query to get the desired row but I'm not getting anything so far any help will be appreciated. Here is what I wrote so far: </p>

```<code><form method="post" action="a34.php">
 <select name="category">
  <option value="6008">15</option>
  <option value="6018">25</option>
  <option value="6034">30</option>
  <option value="6038">40</option>

$V=$_POST['category'];

$getrow= "SELECT ProdID,
ProdCatID, ID_AC_seperate, ProdImage,
 ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable,
cart_thumb FROM accessories WHERE ProdID = '$V'";
</code>```

答:
I recommend you to use strip_tags function. Never put raw data into sql.

So

```<code>If(isset($_POST['category']) {
    $data = strip_tags ($_POST['category']);

    $getrow= "SELECT ProdID, ProdCatID, ID_AC_seperate, ProdImage,
                     ProdName, ProdPrice, ProdShippingPrice,
                     ProdShortDesc, ProdMediumDesc, suitable, cart_thumb
              FROM accessories
              WHERE ProdID = '. $data .'";
}
</code>```

Body:
I'm trying to pass a value from an HTML form and store it to a php variable so i can use this variable into a query to determine what row to get from database. I'm using _post['category'] to get the selected value and I'm passing the variable to the query to get the desired row but I'm not getting anything so far any help will be appreciated. Here is what I wrote so far:

<form method="post" action="a34.php">
 <select name="category">
  <option value="6008">15</option>
  <option value="6018">25</option>
  <option value="6034">30</option>
  <option value="6038">40</option>

$V=$_POST['category'];

$getrow= "SELECT ProdID,
ProdCatID, ID_AC_seperate, ProdImage,
 ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable,
cart_thumb FROM accessories WHERE ProdID = '$V'";

Body:
I recommend you to use strip_tags function. Never put raw data into sql.

So

If(isset($_POST['category']) {
    $data = strip_tags ($_POST['category']);

    $getrow= "SELECT ProdID, ProdCatID, ID_AC_seperate, ProdImage,
                     ProdName, ProdPrice, ProdShippingPrice,
                     ProdShortDesc, ProdMediumDesc, suitable, cart_thumb
              FROM accessories
              WHERE ProdID = '. $data .'";
}


来源: stackexchange

问:
Exporting and importing "schema" from/to Oracle 12.1 on AWS RDS
I have my database on Oracle @ AWS RDS (v12.1). I want to backup a schema in a flat file and import it back to the database when required. The obvious choice is to use expdp/impdp commands however, Oracle version 12.1 require a full Oracle server setup to use these. I don't have a full Oracle server to use. Version 12.2 does provide the tools as independent installers but AWS RDS does not support v12.2. I wish to backup and restore only a specific schema and not the full database.
  The approach I can think of is to write a PL/SQL script that will loop through the DDL, data, constraints and other artifacts and dump it to a flat file and another PL/SQL script which would import the contents from the flat file to the database.
  Does anyone have any pointers to do this in an efficient way ? </p>

答: You can use "SQL Developer" to connect to the specified DB and extract complete schema DDL using "Database Export"(Tools > Database Export) functionality. At a later time you can just execute this extracted DDL script and recreate the schema.

ContentLicense: CC BY-SA 3.0


问:
Fetch Table Column values into varchar in SQL Sever
I have

```<code>tableA (strX varchar(10), strY varchar(10))
Values ('Me', 'Today')
       ('You', 'Yesterday')

tableB (strP varchar(10), strQ varchar(10))
Values ('He', 'Rejected')
       ('Me', 'Accepted')
       ('You', 'Rejected')
       ('Her', 'Accepted')
</code>```

and my Query in stored procedure goes like below and is being called more than 10 times in my procedure.

```<code>Select * from tableB  Where strp in (Select strX from tableA);
</code>```

Is there a way I can store Select strX from tableA into a variable and make use of it like below ?

```<code>Declare @strValues = (Select strX from tableA);

Select * from tableB  Where strp in @strValues;
</code>```

no of entries for strX is dynamic in tableA.

答:
Why would you bother trying to convert a working query to something else?

If performance is your concern, then simply make strX the primary key:

```<code>create tableA (
    strX varchar(10) primary key,
    strY varchar(10)
);
</code>```

This should be pretty wickedly fast.

Body:
I have

tableA (strX varchar(10), strY varchar(10))
Values ('Me', 'Today')
       ('You', 'Yesterday')

tableB (strP varchar(10), strQ varchar(10))
Values ('He', 'Rejected')
       ('Me', 'Accepted')
       ('You', 'Rejected')
       ('Her', 'Accepted')

and my Query in stored procedure goes like below and is being called more than 10 times in my procedure.

Select * from tableB  Where strp in (Select strX from tableA);

Is there a way I can store Select strX from tableA into a variable and make use of it like below ?

Declare @strValues = (Select strX from tableA);

Select * from tableB  Where strp in @strValues;

no of entries for strX is dynamic in tableA.

Body:
Why would you bother trying to convert a working query to something else?

If performance is your concern, then simply make strX the primary key:

create tableA (
    strX varchar(10) primary key,
    strY varchar(10)
);

This should be pretty wickedly fast.


问:
c# application crashes on ShowDialog() after running oledbconnection
I have been working on a c# project that connects to a access database, but a certain sequence of events causes it to crash with a AccessViolationException

The issue comes after calling a database connection using oledb in a separate form than the savefiledialog, and than calling savefiledialog1.ShowDialog()

Note: This also applies to the open file dialog.

答:
It might be a bug in Access Database Engine 2010. Use 2007 instead.

connect.microsoft.com: oledb-operations-cause-accessviolationexception-during-savefiledialog

Codeproject: OpenFileDialog + OleDbConnection = AccessViolationException

ContentLicense: CC BY-SA 2.5


问:
How can I refresh a JTree after adding some nodes to the underlying model?
First of all, let me say that I dont use the DefaultTreeModel. I implement my own TreeModel, so i cant use the DefaultXXX stuff. The problem is this: Through some addStuff() methods which my model defines I add nodes to the underlying data structure. I then notify listeners by calling treeNodesChanged() inside the addStuff() function (I Know there are treeNodesInserted methods but it is the same thing. It just notifies listeners with a different method). Now, one of the listeners is a static class in my main form and this listener can tell the JTree, which is also contained in my main form,  to refresh itself. How do I tell the JTree to "reload" some or all of its nodes from the model?

UPDATE:
Found this question that although not exactly the same, it gives the answer I want.

UPDATE 2:
My problem was not how to notify the viewer (the JTree), but rather in what way should the jtree be reloaded after the notification from the model.

First of all let me say that the only way i know to refresh a tree to reflect underlying changes, is to call the updateUI(), or reuse the setModel() method. Essentially, my problem is this:

Suppose the TreeModelListener has just been notified (through the TreeModelListener API) that a change has occured in the model. Ok, what now?

I have this problem because the JTree does not implement TreeModelListener. So the listener, in my situation, is the JTree's container, or an internal class implementing the Listener, living under the same container as Jtree.

So suppose I am a TreeModelListener implementation, living happily in a JForm with my brother JTree. Suddenly my method treeNodesInserted(TreeModelEvent evt) is called. What do I do now? If i call Jtree.updateUI() from inside me, then the model's listeners List throws ConcurrentModification Exception. Can I call something else other than updateUI?

I tried a number of things, but only updateUI refreshed the JTree. So I did it outside of the listener. From the JForm, I just call the model's method that alters the undrlying structure, and then i call updateUI. No TreeModelListener gets used.

UPDATE3:
I found out that there are implicit TreeModelListeners registered. In my model's addTreeModelListener(TreeModelListener listener) implementation i put a debug system.out line:

```<code>System.out.println("listener added: " + listener.getClass().getCanonicalName());
</code>```

and I saw this debug output just when I executed jTree.setModel(model):

listener added: javax.swing.JTree.TreeModelHandler

listener added: javax.swing.plaf.basic.BasicTreeUI.Handler

The ConcurrentModificationException is caused because a call to jtree.updateUI() re registers the listener (only the plaf, not both) so it is thrown when i call updateUI inside a listener notification loop.
The only way now to refresh the tree is do it outside of TreeModelListener.  Any comments or ideas for a better solution? Am I missing something?

答:
It seems to be possible to reinitialize the whole tree by setting the model to null:
e.g.

```<code>        TreePath path = tree.getSelectionPath();
        model.doChanges(); // do something with model
        tree.setModel(null);
        tree.setModel(model);
        tree.setSelectionPath(path);
        tree.expandPath(path);
</code>```

Tree update works for me

kr Achim

Body:
First of all, let me say that I dont use the DefaultTreeModel. I implement my own TreeModel, so i cant use the DefaultXXX stuff. The problem is this: Through some addStuff() methods which my model defines I add nodes to the underlying data structure. I then notify listeners by calling treeNodesChanged() inside the addStuff() function (I Know there are treeNodesInserted methods but it is the same thing. It just notifies listeners with a different method). Now, one of the listeners is a static class in my main form and this listener can tell the JTree, which is also contained in my main form,  to refresh itself. How do I tell the JTree to "reload" some or all of its nodes from the model?

UPDATE:
Found this question that although not exactly the same, it gives the answer I want.

UPDATE 2:
My problem was not how to notify the viewer (the JTree), but rather in what way should the jtree be reloaded after the notification from the model.

First of all let me say that the only way i know to refresh a tree to reflect underlying changes, is to call the updateUI(), or reuse the setModel() method. Essentially, my problem is this:

Suppose the TreeModelListener has just been notified (through the TreeModelListener API) that a change has occured in the model. Ok, what now?

I have this problem because the JTree does not implement TreeModelListener. So the listener, in my situation, is the JTree's container, or an internal class implementing the Listener, living under the same container as Jtree.

So suppose I am a TreeModelListener implementation, living happily in a JForm with my brother JTree. Suddenly my method treeNodesInserted(TreeModelEvent evt) is called. What do I do now? If i call Jtree.updateUI() from inside me, then the model's listeners List throws ConcurrentModification Exception. Can I call something else other than updateUI?

I tried a number of things, but only updateUI refreshed the JTree. So I did it outside of the listener. From the JForm, I just call the model's method that alters the undrlying structure, and then i call updateUI. No TreeModelListener gets used.

UPDATE3:
I found out that there are implicit TreeModelListeners registered. In my model's addTreeModelListener(TreeModelListener listener) implementation i put a debug system.out line:

System.out.println("listener added: " + listener.getClass().getCanonicalName());

and I saw this debug output just when I executed jTree.setModel(model):

listener added: javax.swing.JTree.TreeModelHandler

listener added: javax.swing.plaf.basic.BasicTreeUI.Handler

The ConcurrentModificationException is caused because a call to jtree.updateUI() re registers the listener (only the plaf, not both) so it is thrown when i call updateUI inside a listener notification loop.
The only way now to refresh the tree is do it outside of TreeModelListener.  Any comments or ideas for a better solution? Am I missing something?

Body:
It seems to be possible to reinitialize the whole tree by setting the model to null:
e.g.

        TreePath path = tree.getSelectionPath();
        model.doChanges(); // do something with model
        tree.setModel(null);
        tree.setModel(model);
        tree.setSelectionPath(path);
        tree.expandPath(path);

Tree update works for me

kr Achim


问:
Sublime Text 3 - Search multiple folders with regex for files in one folder
I want to perform a search on all of the files in the /app/libraries and /app/views folders, but I only want to search within files starting with App in the /app/models folder.

If I use /app/libraries, /app/views, /app/models/App* it gives me:

```<code>/app/models/App*:
    ERROR: Unable to open file
0 matches
</code>```

If I use /app/libraries, /app/views, /app/models, App* it only gives me files starting with App in all of the folders.

I've tried getting rid of the leading slash /app/libraries, /app/views, app/models/App* as suggested by this answer, but I get this:

```<code>Searching 0 files for "search string" (regex, case sensitive)

0 matches
</code>```

答:
The point here is that you have been using wildcard pattern while you needed a regex pattern.

To match any amount of any chars in wildcard patterns, an asterisk is used, but in regex patterns, you may use either .* (any 0+ chars other than line break chars) or - if you need to only match App as part of the file name (and thus, no more / are allowed) - you may use [^/]* (zero or more chars other than /.

So, use either

```<code>/app/models/App.*
</code>```

or

```<code>/app/models/App[^/]*
</code>```

Body:
I want to perform a search on all of the files in the /app/libraries and /app/views folders, but I only want to search within files starting with App in the /app/models folder.

If I use /app/libraries, /app/views, /app/models/App* it gives me:

/app/models/App*:
    ERROR: Unable to open file
0 matches

If I use /app/libraries, /app/views, /app/models, App* it only gives me files starting with App in all of the folders.

I've tried getting rid of the leading slash /app/libraries, /app/views, app/models/App* as suggested by this answer, but I get this:

Searching 0 files for "search string" (regex, case sensitive)

0 matches

Body:
The point here is that you have been using wildcard pattern while you needed a regex pattern.

To match any amount of any chars in wildcard patterns, an asterisk is used, but in regex patterns, you may use either .* (any 0+ chars other than line break chars) or - if you need to only match App as part of the file name (and thus, no more / are allowed) - you may use [^/]* (zero or more chars other than /.

So, use either

/app/models/App.*

or

/app/models/App[^/]*


问:
create corner arc with css
How would you create such corner arc using css?

This is starter template: https://codepen.io/anon/pen/rwraXG

I was hoping that I would be able to use black outer div and red inner div, and use border radius to leave just the top left corner showing through. I messed something midway.

.bar {
  width: 100px;
  height: 20px;
  background-color: red;
}

.outer {
  height: 100%;
  width: 8px;
  background-color: black;
}

.inner {
  height: 100%;
  width: 100%;
  background-color: red;
  border: 2px solid black;
  border-radius: 15px 0px 0px 0px:
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bar">
  <div class="outer">
    <div class="inner"></div>
  </div>
</div></code>```

答:
It is possible to do this with the inner and outer boxes as you have. You would change your css to the below. You don't need to declare the color red on '.bar' because your '.inner' div will be the red portion of this.

```<code>.bar{
  width:200px;
  height:100px;
}
.outer{
  height:100%;
  width:100%;
  background-color:black;
}
.inner{
  height:100%;
  width:100%;
  background-color:red;
  border-radius: 20px 0 0 0;
}
</code>```

As long as your parent div ('.bar') has a set width and height '.inner' and '.outer' can have width and heights of 100%.

*Please note though that the higher you make '.bar' the better the top left tab will look.

Title: create corner arc with css

Body:
It is possible to do this with the inner and outer boxes as you have. You would change your css to the below. You don't need to declare the color red on '.bar' because your '.inner' div will be the red portion of this.

.bar{
  width:200px;
  height:100px;
}
.outer{
  height:100%;
  width:100%;
  background-color:black;
}
.inner{
  height:100%;
  width:100%;
  background-color:red;
  border-radius: 20px 0 0 0;
}

As long as your parent div ('.bar') has a set width and height '.inner' and '.outer' can have width and heights of 100%.

*Please note though that the higher you make '.bar' the better the top left tab will look.


问:
how to set a header.php redirect in wordpress?
i just want to ask how to set a redirect url in header.php? it seems I am having a redirect loop.</p>

```<code><?php
header("Location: http://www.sitename.com/category/videos/");
?>
</code>```

答:
Place the following HTML redirect code in a WordPress Page or Post:

```<code>    <meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourURL.com/index.htm">
</code>```

This code tells your browser to auto-refresh the current Web page. When it does, it loads the URL in the "url" string. The "0" attribute associated to "content" determines how many seconds before the redirect takes place. The attributes associated with "content" and "url" are the only ones you should alter.

Body:
i just want to ask how to set a redirect url in header.php? it seems I am having a redirect loop.

<?php
header("Location: http://www.sitename.com/category/videos/");
?>

Body:
Place the following HTML redirect code in a WordPress Page or Post:

    <meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourURL.com/index.htm">

This code tells your browser to auto-refresh the current Web page. When it does, it loads the URL in the "url" string. The "0" attribute associated to "content" determines how many seconds before the redirect takes place. The attributes associated with "content" and "url" are the only ones you should alter.


问:
"The parameter is incorrect" error using "netsh http add sslcert"
Following the instructions in How to: Configure a Port with an SSL Certificate, I entered this command on the command line (duh):

```<code>netsh http add sslcert ipport:10.141.146.227:7001 certhash=5d48e604007b867ae8a69260a4ad318d2c05d8ff appid={EDE3C891-306C-40fe-BAD4-895B236A1CC8}
</code>```

Output:

```<code>The parameter is incorrect.
</code>```

My certhash thumbprint was taken from the certificate in Certificates (Local Computer) → Personal → Certificates folder.

The appid GUID was generated.

What else is wrong that I need to fix to get this to work?

答:
I must have ended up mangling the relationship between Visual Studio and IIS Express by deleting the localhost certificate. I was really stuck. The application wouldn't start and nothing I could do seemed to correct this disconnect (which is want brought me to this thread to begin with).

I was finally able to get over the issue by changing the assigned port on the non-SSL URL (launchSettings.json in .NET Core applications) and disabling the Enable SSL checkbox in the project settings and taking a fresh start. I was then able to add my newly created cert with this command: netsh http add sslcert ipport=0.0.0.0:44392 appid={214124cd-d05b-4309-9af9-9caa44b2b74b} certhash=A0ADC1A1002F288CCFA96261F9F352D28C675A90.

Also, note that the appid variable is not a reflection of your Visual Studio project AppID (or at least it doesn't have to be). It's just an arbitrary GUID, according to Scott Hanselmann:

The AppId doesn't really matter, it's just a GUID. This tells HTTP.SYS that we're using that certificate.

This was not obvious to me and made dealing with the parameter is incorrect error that much more obscure.

ContentLicense: CC BY-SA 4.0

Body:
Following the instructions in How to: Configure a Port with an SSL Certificate, I entered this command on the command line (duh):

netsh http add sslcert ipport:10.141.146.227:7001 certhash=5d48e604007b867ae8a69260a4ad318d2c05d8ff appid={EDE3C891-306C-40fe-BAD4-895B236A1CC8}

Output:

The parameter is incorrect.

My certhash thumbprint was taken from the certificate in Certificates (Local Computer) → Personal → Certificates folder.

The appid GUID was generated.

What else is wrong that I need to fix to get this to work?


问:
How to change results in Access query?
I have a table, we'll call it users.

```<code>id username type
</code>```

The type field is a two character type, so each user either has US, MO, AD.  Not sure why the original developer did this, but I cannot change this method, unfortunately.

```<code>1 mike US
2 Tim AD
3 mark MO
</code>```

Instead of returning US, AD... etc types in Access, I'd like the query to replace the US with USER, replace MO with MODERATOR, and replace AD with ADMIN.

Is this possible?

Kind of like SELECT * FROM USERS and then if statements within Access (if US, then USER).  Not sure how to proceed?

答:
Sql Server has a construct called Case When but it's not available in MS Access.

Here is a workaround

Title: How to change results in Access query?

Body:
I have a table, we'll call it users.

id username type

The type field is a two character type, so each user either has US, MO, AD.  Not sure why the original developer did this, but I cannot change this method, unfortunately.

1 mike US
2 Tim AD
3 mark MO

Instead of returning US, AD... etc types in Access, I'd like the query to replace the US with USER, replace MO with MODERATOR, and replace AD with ADMIN.

Is this possible?

Kind of like SELECT * FROM USERS and then if statements within Access (if US, then USER).  Not sure how to proceed?


问:
ASP.NET CORE Application using some Angular 4 pages (--> ASP.NET CORE routing)
We have an existing ASP.NET CORE App with lots of controllers and views (with knockout for 2-way-binding).
Now the requirement is to build new pages (views) with Angular 4 but the rest of the App should stay unchanged.

The management says it should be made like previous knockout extensions which integrate seamlessly in ASP.NET CORE views. This means each page should be a seperate Angular 4 SPA. This requires that routing has to be done with ASP.NET CORE and not Angular 4.

Question: Is this feasible? If yes, how?

Question: Are there better strategies to extend an existing ASP.NET CORE App with Angular 4 parts than this approach?

EDIT:
What I don't understand so far is how to provide routing by ASP.NET CORE in combination with Angular4. In ASP.NET we use _Layout.cshtml for common layout code including a @Html.Partial("_Navigation") for navigation and @RenderBody() for rendering the views. We want to use razor partial views as for the Angular templates. This excellent article describes how.
But how can this be done with ASP.NET routing?

答: I have found a solution that works for our requirements. For each "mini SPA" I created the necessary files (NgModule, main.ts) to bootstrap them. Then I add a Controller that delivers cshtml-views that contains the load command for the different "mini SPAs". Referencing them in ASP.NET navigation worked like a charm!


问:
GetAsyncKeyState() don't work with 'OEM' keys
I'm trying to create a keylogger. I decided to use the function GetAsyncKeyState. I programmed all of keys. And when I was testing my keylogger, I realized that keys like ,<.>/?;:'"[{]}\|=+-_ aren't displaying on the console. Why?

This is my code:

```<code>#include <iostream>
#include <Windows.h>
#include <string>
#include <cctype>
#include <conio.h>

using namespace std;

string WhichKey(char key)
{
string ToReturn;

switch (key)
{
case VK_BACK:
    return "*BACKSPACE*";
case VK_TAB:
    return "*TAB*";
case VK_RETURN:
    return "*ENTER*";
case VK_SHIFT:
    return "*SHIFT*";
case VK_MENU:
    return "*ALT*";
case VK_CONTROL:
    return "*CTRL*";
case VK_ESCAPE:
    return "*ESC*";
case VK_SPACE:
    return " ";
case VK_PRIOR:
    return "*PAGE_UP*";
case VK_NEXT:
    return "*PAGE_DOWN*";
case VK_END:
    return "*END*";
case VK_HOME:
    return "*HOME*";
case VK_CAPITAL:
    return "*CAPS_LOCK*";
case VK_UP:
    return "*UP_ARROW*";
case VK_DOWN:
    return "*DOWN_ARROW*";
case VK_LEFT:
    return "*LEFT_ARROW*";
case VK_RIGHT:
    return "*RIGHT_ARROW*";
case VK_EXECUTE:
    return "*EXECUTE*";
case VK_SNAPSHOT:
    return "*PRINTSCREEN*";
case VK_INSERT:
    return "*INSERT*";
case VK_DELETE:
    return "*DELETE*";
case VK_LWIN:
case VK_RWIN:
    return "*WIN*";
case VK_NUMPAD0:
    return "0";
case VK_NUMPAD1:
    return "1";
case VK_NUMPAD2:
    return "2";
case VK_NUMPAD3:
    return "3";
case VK_NUMPAD4:
    return "4";
case VK_NUMPAD5:
    return "5";
case VK_NUMPAD6:
    return "6";
case VK_NUMPAD7:
    return "7";
case VK_NUMPAD8:
    return "8";
case VK_NUMPAD9:
    return "9";
case VK_F1:
    return "*F1*";
case VK_F2:
    return "*F2*";
case VK_F3:
    return "*F3*";
case VK_F4:
    return "*F4*";
case VK_F5:
    return "*F5*";
case VK_F6:
    return "*F6*";
case VK_F7:
    return "*F7*";
case VK_F8:
    return "*F8*";
case VK_F9:
    return "*F9*";
case VK_F10:
    return "*F10*";
case VK_F11:
    return "*F11*";
case VK_F12:
    return "*F12*";
case VK_SCROLL:
    return "*SCROLL_LOCK*";
case VK_NUMLOCK:
    return "*NUM_LOCK*";
case VK_MULTIPLY:
    return "*";
case VK_ADD:
    return "+";
case VK_SUBTRACT:
    return "-";
case VK_DIVIDE:
    return "/";
case VK_DECIMAL:
    return ".";
case VK_LBUTTON:
    return "*left_click*";
case VK_RBUTTON:
    return "*right_click*";
case VK_MBUTTON:
    return "*middle_click*";
}

if (isalpha(key))
{
    if (!((GetKeyState(VK_CAPITAL) & 0x0001) == 0) ^ (((GetKeyState(VK_SHIFT) & 0x1000) == 0)))
    {
        key = tolower(key);                                                     //off
        ToReturn += key;
        return ToReturn;
    }
    else
    {
        ToReturn += key;                                                        //on
        return ToReturn;
    }
}
else if (isdigit(key))
{
    if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
    {
        ToReturn += key;                                                        //off
        return ToReturn;
    }
    else
    {
        switch (key)
        {
        case '1':
        {
            key = '!';
            break;
        }
        case '2':
        {
            key = '@';
            break;
        }
        case '3':
        {
            key = '#';
            break;
        }
        case '4':
        {
            key = '$';
            break;
        }
        case '5':
        {
            key = '%';
            break;
        }
        case '6':
        {
            key = '^';
            break;
        }
        case '7':
        {
            key = '&';
            break;
        }
        case '8':
        {
            key = '*';
            break;
        }
        case '9':
        {
            key = '(';
            break;
        }
        case '0':
        {
            key = ')';
            break;
        }

        }

        ToReturn += key;                                                        //on
        return ToReturn;
    }

}
else
{

    switch (key)
    {
    case VK_OEM_1:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = ';';                                                      //off
        else
            key = ':';
        break;
    }
    case VK_OEM_PLUS:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '=';                                                      //off
        else
            key = '+';
        break;
    }
    case VK_OEM_COMMA:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = ',';                                                      //off
        else
            key = '<';
        break;
    }
    case VK_OEM_MINUS:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '-';                                                      //off
        else
            key = '_';
        break;
    }
    case VK_OEM_PERIOD:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '.';                                                      //off
        else
            key = '>';
        break;
    }
    case VK_OEM_2:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '/';                                                      //off
        else
            key = '?';
        break;
    }
    case VK_OEM_3:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '`';                                                      //off
        else
            key = '~';
        break;
    }
    case VK_OEM_4:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '[';                                                      //off
        else
            key = '{';
        break;
    }
    case VK_OEM_5:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '\\';                                                     //off
        else
            key = '|';
        break;
    }
    case VK_OEM_6:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = ']';                                                      //off
        else
            key = '}';
        break;
    }
    case VK_OEM_7:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '\'';                                                     //off
        else
            key = '\"';
        break;
    }

    }

    ToReturn += key;
    return ToReturn;

}

ToReturn += key;
return ToReturn;
}

int main()
{

char key;

while(1)
{
    for(key = 0; key <= 256; key++)
    {
        if (GetAsyncKeyState(key) & 0x0001)
        {
                cout << WhichKey(key);
        }

    }

}

return 0;
}
</code>```

Thanks in advance and sorry for my English.

答:
First off, this is a very naive approach to writing a keylogger. I actually tried this same thing the same way you are about 10 years ago.

A better approach would be to use Windows Hooks.

```<code>LRESULT CALLBACK llKeyboardHook(int nCode, WPARAM wParam, LPARAM lParam)
{
    KBDLLHOOKSTRUCT *hookStruct = (KBDLLHOOKSTRUCT*) lParam;

    // Parse the lParam value and members of the hookStruct structure

    return CallNextHookEx(0, nCode, wParam, lParam);
}

// Somewhere in your program, call the following function:
// Initialize the hook
SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC) llKeyboardHook, 0, 0);
</code>```

The main idea here is to let Windows determine the resulting "output" character for you, instead of having to create a switch-case for each possibility like you have done.

I know this doesn't directly answer your question, but the approach you're taking is really the worst way to do it.

Body:
I'm trying to create a keylogger. I decided to use the function GetAsyncKeyState. I programmed all of keys. And when I was testing my keylogger, I realized that keys like ,<.>/?;:'"[{]}\|=+-_ aren't displaying on the console. Why?

This is my code:

#include <iostream>
#include <Windows.h>
#include <string>
#include <cctype>
#include <conio.h>

using namespace std;

string WhichKey(char key)
{
string ToReturn;

switch (key)
{
case VK_BACK:
    return "*BACKSPACE*";
case VK_TAB:
    return "*TAB*";
case VK_RETURN:
    return "*ENTER*";
case VK_SHIFT:
    return "*SHIFT*";
case VK_MENU:
    return "*ALT*";
case VK_CONTROL:
    return "*CTRL*";
case VK_ESCAPE:
    return "*ESC*";
case VK_SPACE:
    return " ";
case VK_PRIOR:
    return "*PAGE_UP*";
case VK_NEXT:
    return "*PAGE_DOWN*";
case VK_END:
    return "*END*";
case VK_HOME:
    return "*HOME*";
case VK_CAPITAL:
    return "*CAPS_LOCK*";
case VK_UP:
    return "*UP_ARROW*";
case VK_DOWN:
    return "*DOWN_ARROW*";
case VK_LEFT:
    return "*LEFT_ARROW*";
case VK_RIGHT:
    return "*RIGHT_ARROW*";
case VK_EXECUTE:
    return "*EXECUTE*";
case VK_SNAPSHOT:
    return "*PRINTSCREEN*";
case VK_INSERT:
    return "*INSERT*";
case VK_DELETE:
    return "*DELETE*";
case VK_LWIN:
case VK_RWIN:
    return "*WIN*";
case VK_NUMPAD0:
    return "0";
case VK_NUMPAD1:
    return "1";
case VK_NUMPAD2:
    return "2";
case VK_NUMPAD3:
    return "3";
case VK_NUMPAD4:
    return "4";
case VK_NUMPAD5:
    return "5";
case VK_NUMPAD6:
    return "6";
case VK_NUMPAD7:
    return "7";
case VK_NUMPAD8:
    return "8";
case VK_NUMPAD9:
    return "9";
case VK_F1:
    return "*F1*";
case VK_F2:
    return "*F2*";
case VK_F3:
    return "*F3*";
case VK_F4:
    return "*F4*";
case VK_F5:
    return "*F5*";
case VK_F6:
    return "*F6*";
case VK_F7:
    return "*F7*";
case VK_F8:
    return "*F8*";
case VK_F9:
    return "*F9*";
case VK_F10:
    return "*F10*";
case VK_F11:
    return "*F11*";
case VK_F12:
    return "*F12*";
case VK_SCROLL:
    return "*SCROLL_LOCK*";
case VK_NUMLOCK:
    return "*NUM_LOCK*";
case VK_MULTIPLY:
    return "*";
case VK_ADD:
    return "+";
case VK_SUBTRACT:
    return "-";
case VK_DIVIDE:
    return "/";
case VK_DECIMAL:
    return ".";
case VK_LBUTTON:
    return "*left_click*";
case VK_RBUTTON:
    return "*right_click*";
case VK_MBUTTON:
    return "*middle_click*";
}

if (isalpha(key))
{
    if (!((GetKeyState(VK_CAPITAL) & 0x0001) == 0) ^ (((GetKeyState(VK_SHIFT) & 0x1000) == 0)))
    {
        key = tolower(key);                                                     //off
        ToReturn += key;
        return ToReturn;
    }
    else
    {
        ToReturn += key;                                                        //on
        return ToReturn;
    }
}
else if (isdigit(key))
{
    if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
    {
        ToReturn += key;                                                        //off
        return ToReturn;
    }
    else
    {
        switch (key)
        {
        case '1':
        {
            key = '!';
            break;
        }
        case '2':
        {
            key = '@';
            break;
        }
        case '3':
        {
            key = '#';
            break;
        }
        case '4':
        {
            key = '$';
            break;
        }
        case '5':
        {
            key = '%';
            break;
        }
        case '6':
        {
            key = '^';
            break;
        }
        case '7':
        {
            key = '&';
            break;
        }
        case '8':
        {
            key = '*';
            break;
        }
        case '9':
        {
            key = '(';
            break;
        }
        case '0':
        {
            key = ')';
            break;
        }

        }

        ToReturn += key;                                                        //on
        return ToReturn;
    }

}
else
{

    switch (key)
    {
    case VK_OEM_1:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = ';';                                                      //off
        else
            key = ':';
        break;
    }
    case VK_OEM_PLUS:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '=';                                                      //off
        else
            key = '+';
        break;
    }
    case VK_OEM_COMMA:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = ',';                                                      //off
        else
            key = '<';
        break;
    }
    case VK_OEM_MINUS:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '-';                                                      //off
        else
            key = '_';
        break;
    }
    case VK_OEM_PERIOD:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '.';                                                      //off
        else
            key = '>';
        break;
    }
    case VK_OEM_2:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '/';                                                      //off
        else
            key = '?';
        break;
    }
    case VK_OEM_3:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '`';                                                      //off
        else
            key = '~';
        break;
    }
    case VK_OEM_4:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '[';                                                      //off
        else
            key = '{';
        break;
    }
    case VK_OEM_5:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '\\';                                                     //off
        else
            key = '|';
        break;
    }
    case VK_OEM_6:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = ']';                                                      //off
        else
            key = '}';
        break;
    }
    case VK_OEM_7:
    {
        if ((GetKeyState(VK_SHIFT) & 0x1000) == 0)
            key = '\'';                                                     //off
        else
            key = '\"';
        break;
    }

    }

    ToReturn += key;
    return ToReturn;

}

ToReturn += key;
return ToReturn;
}

int main()
{

char key;

while(1)
{
    for(key = 0; key <= 256; key++)
    {
        if (GetAsyncKeyState(key) & 0x0001)
        {
                cout << WhichKey(key);
        }

    }

}

return 0;
}

Thanks in advance and sorry for my English.

Body:
First off, this is a very naive approach to writing a keylogger. I actually tried this same thing the same way you are about 10 years ago.

A better approach would be to use Windows Hooks.

LRESULT CALLBACK llKeyboardHook(int nCode, WPARAM wParam, LPARAM lParam)
{
    KBDLLHOOKSTRUCT *hookStruct = (KBDLLHOOKSTRUCT*) lParam;

    // Parse the lParam value and members of the hookStruct structure

    return CallNextHookEx(0, nCode, wParam, lParam);
}

// Somewhere in your program, call the following function:
// Initialize the hook
SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC) llKeyboardHook, 0, 0);

The main idea here is to let Windows determine the resulting "output" character for you, instead of having to create a switch-case for each possibility like you have done.

I know this doesn't directly answer your question, but the approach you're taking is really the worst way to do it.


问:
Why did my while loop fail when I defined the break code?
I am new to Python and was exploring a simple side project to understand how functions and loops work.

I have this code right here

```<code>age = 0

def ageInMonths (age):
    months =  int(age) * 12
    return print('You are ' + str(months) + ' months old!')

def ageInDays(age):
     days = int(age)*365
     return print('You are ' + str(days) + ' days old!')

def ageInHrs(age):
    hrs = int(age)* 8765.81
    return print('You are ' + str(hrs) + ' hours old!')

    def ageinMin(age):
       minutes = int(age)* 525948.8
       return print('You are ' + str(minutes) + ' minutes old!')

    def ageinSec(age):
       sec= int(age)* 31556926
       return print('You are ' + str(sec) + ' seconds old!')

def agePrint(age):
    age=age
    ageInMonths(age)
    ageInDays(age)
    ageInHrs(age)
    ageinMin(age)
    ageinSec(age)
      print('Done')
    return

while age != 99:

    print( 'Please enter your age?')

    age = input()
    if age == 99:
     break

    print('You are ' + age + ' years old!')

    agePrint(age)
</code>```

Every time I enter 99 the while loop does not break.  Any suggestions to where I went wrong..

答:
You forgot to convert the input to int:

```<code>age = int(input())
</code>```

If you don't do that explicitly, age will be a string, and naturally '99' != 99.

Body:
I am new to Python and was exploring a simple side project to understand how functions and loops work.

I have this code right here

age = 0

def ageInMonths (age):
    months =  int(age) * 12
    return print('You are ' + str(months) + ' months old!')

def ageInDays(age):
     days = int(age)*365
     return print('You are ' + str(days) + ' days old!')

def ageInHrs(age):
    hrs = int(age)* 8765.81
    return print('You are ' + str(hrs) + ' hours old!')

    def ageinMin(age):
       minutes = int(age)* 525948.8
       return print('You are ' + str(minutes) + ' minutes old!')

    def ageinSec(age):
       sec= int(age)* 31556926
       return print('You are ' + str(sec) + ' seconds old!')

def agePrint(age):
    age=age
    ageInMonths(age)
    ageInDays(age)
    ageInHrs(age)
    ageinMin(age)
    ageinSec(age)
      print('Done')
    return

while age != 99:

    print( 'Please enter your age?')

    age = input()
    if age == 99:
     break

    print('You are ' + age + ' years old!')

    agePrint(age)

Every time I enter 99 the while loop does not break.  Any suggestions to where I went wrong..

Body:
You forgot to convert the input to int:

age = int(input())

If you don't do that explicitly, age will be a string, and naturally '99' != 99.


问:
Is it possible to perform a batch upload to amazon s3?
Does amazon s3 support batch uploads?
I have a job that needs to upload each night ~100K of files that can be up to 1G but is strongly skewed towards small files (90% are less than 100 bytes and 99% are less than 1000 bytes long).

Does the s3 API support uploading multiple objects in a single HTTP call?

All the objects must be available in S3 as individual objects. I cannot host them anywhere else (FTP, etc) or in another format (Database, EC2 local drive, etc). That is an external requirement that I cannot change.

答: One file (or part of a file) = one HTTP request, but the Java API now supports efficient multiple file upload without having to write the multithreading on your own, by using TransferManager</p>


问:
CSS only modal window OK on Android, not working on iOS
I've got some CSS code in order to display the title attribute when touching on abbreviations and symbols of a smartphone's screen. Within a section '@media only screen and (max-width: 767px)' of my stylesheet I have the following code:

span[title]:active::after,abbr:active::after {
  color: Maroon;
  font-weight: bold;
  content: 'Meaning: ' attr(title);
  position: fixed;
  top: 3ex;
  left: 2ex;
  display: block;
  z-index: 100;
  background-color: White;
  box-shadow: .3ex .3ex .1ex Grey;
  border: 1px solid grey;
  padding: .4ex;
  width: 70%;
  height: auto;
 }```

It does work flawlessly on Android -I've tested it on Chrome, Firefox and Samsung browser- and my iMac -tested it on Chrome, Firefox, Safari and Opera after stretching the width of the browser's window, but it doesn't work on iOS at all! The trick/workaround of adding '-webkit-transform: translate3d (0,0,0);' added to the code did not help to this.
I should appreciate any help a lot!
Thank you very much indeed!

SOLVED!

I tried the solution as proposed in the following link: Enable CSS active pseudo styles in Mobile Safari
and it works fine. The problem was that Safari Mobile disables :active pseudo-class by default, and this simple idea solves it.
I tried some other working solutions, such as 'body ontouchstart=””' and similar ones, but all of them gave errors when checking the code against W3C validator.
Many thanks to all those that answered and tried to help!

答:
The  :active property only works on activabe elements. Documentation says:

There may be document language or implementation specific limits on which elements can become :active or acquire :focus.

So the most simple thing to do is to set the tabindex attribute to 0 for each element you want to be activable.

This has the big advantage that your code will work with keyboard.

EDIT: adding tabindex=-1 for all elements can be done easily with jQuery using

```<code>$("abbr[title]").attr("tabindex", -1);
</code>```

or using standard javascript

```<code>var ele=document.querySelectorAll("abbr[title]");
for (var i=0;i<ele.length;i++) {
   ele[i].setAttribute("tabindex", -1);
}
</code>```

Body:
I've got some CSS code in order to display the title attribute when touching on abbreviations and symbols of a smartphone's screen. Within a section '@media only screen and (max-width: 767px)' of my stylesheet I have the following code:

span[title]:active::after,abbr:active::after {
  color: Maroon;
  font-weight: bold;
  content: 'Meaning: ' attr(title);
  position: fixed;
  top: 3ex;
  left: 2ex;
  display: block;
  z-index: 100;
  background-color: White;
  box-shadow: .3ex .3ex .1ex Grey;
  border: 1px solid grey;
  padding: .4ex;
  width: 70%;
  height: auto;
 }

It does work flawlessly on Android -I've tested it on Chrome, Firefox and Samsung browser- and my iMac -tested it on Chrome, Firefox, Safari and Opera after stretching the width of the browser's window, but it doesn't work on iOS at all! The trick/workaround of adding '-webkit-transform: translate3d (0,0,0);' added to the code did not help to this.
I should appreciate any help a lot!
Thank you very much indeed!

SOLVED!

I tried the solution as proposed in the following link: Enable CSS active pseudo styles in Mobile Safari
and it works fine. The problem was that Safari Mobile disables :active pseudo-class by default, and this simple idea solves it.
I tried some other working solutions, such as 'body ontouchstart=””' and similar ones, but all of them gave errors when checking the code against W3C validator.
Many thanks to all those that answered and tried to help!

Body:
The  :active property only works on activabe elements. Documentation says:

There may be document language or implementation specific limits on which elements can become :active or acquire :focus.

So the most simple thing to do is to set the tabindex attribute to 0 for each element you want to be activable.

This has the big advantage that your code will work with keyboard.

EDIT: adding tabindex=-1 for all elements can be done easily with jQuery using

$("abbr[title]").attr("tabindex", -1);

or using standard javascript

var ele=document.querySelectorAll("abbr[title]");
for (var i=0;i<ele.length;i++) {
   ele[i].setAttribute("tabindex", -1);
}


问:
JavaScript location.reload() is losing post data
I am trying to reload the page using java script the page reloads but the post data in the page is not loading the post data are deleted while the page reloads can any one help me with it

```<code>function currencychange(xxx) {
    setTimeout('delay()', 2000);
}
function delay(){
    location.reload();
}
</code>```

this is the javascript code which I am using to reload the page onchange

答:
This was a complete hack, but necessary and allowed it to work with Safari.  So at the end of the page I pushed all the post data into a session

```<code>$_SESSION['post'] = $_POST
</code>```

I then used jQuery to update the session variables.  Then used location.reload(); to reload the page once I was completed making changes and the as the page loads I simple pushed all session data back into post.

```<code>$_POST = £_SESSION['post'];
</code>```

The result is the same as if a form was submitted.

Body:
I am trying to reload the page using java script the page reloads but the post data in the page is not loading the post data are deleted while the page reloads can any one help me with it

function currencychange(xxx) {
    setTimeout('delay()', 2000);
}
function delay(){
    location.reload();
}

this is the javascript code which I am using to reload the page onchange

Body:
This was a complete hack, but necessary and allowed it to work with Safari.  So at the end of the page I pushed all the post data into a session

$_SESSION['post'] = $_POST

I then used jQuery to update the session variables.  Then used location.reload(); to reload the page once I was completed making changes and the as the page loads I simple pushed all session data back into post.

$_POST = £_SESSION['post'];

The result is the same as if a form was submitted.


问:
How can I get the timezone name in JavaScript?
I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset?</p>

答:
The Internationalization API supports getting the user timezone, and is supported in all current browsers.

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)```

Keep in mind that on some older browser versions that support the Internationalization API, the timeZone property is set to undefined rather than the user’s timezone string. As best as I can tell, at the time of writing (July 2017) all current browsers except for IE11 will return the user timezone as a string.

Body:
The Internationalization API supports getting the user timezone, and is supported in all current browsers.

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)

Keep in mind that on some older browser versions that support the Internationalization API, the timeZone property is set to undefined rather than the user’s timezone string. As best as I can tell, at the time of writing (July 2017) all current browsers except for IE11 will return the user timezone as a string.


问:
Duplicate items in ListView vb.net 2008
I am trying to remove the duplicates in my listview. Here's my code:

```<code>Imports System.Data.OleDb
Public Class frmQuizSelector

Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click
    Me.Hide()
End Sub

Private Sub lvwQuizzes()
    With Me.lvwListOfQuizzes
        .FullRowSelect = True
        .GridLines = False
        .View = View.Details
        .Columns.Add("QuizID", 1)
        .Columns.Add("Quiz Title", 268)
    End With
End Sub

Private Sub frmQuizSelector_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.cmdPrevQ.Visible = False
    Me.cmdNextQ.Visible = False

    lvwQuizzes()

    Try
        Dim dtb As New DataTable
        Dim strSql As String = "SELECT * FROM tblQuestions"
        AConn.Open()
        Using dataadapter As New OleDbDataAdapter(strSql, AConn)
            dataadapter.Fill(dtb)
        End Using
        AConn.Close()
        Me.lvwListOfQuizzes.Items.Clear()
        Dim i As Integer = 0
        For i = 0 To dtb.Rows.Count - 1
            Dim lv As New ListViewItem
            lv.Text = dtb.Rows(i).Item("QuizID1")
            lv.SubItems.Add(dtb.Rows(i).Item("QuizTitle"))
            lv.SubItems.Add(dtb.Rows(i).Item("CourseSubject"))
            lv.SubItems.Add(dtb.Rows(i).Item("QuestionNumber"))
            lv.SubItems.Add(dtb.Rows(i).Item("ActualQuestion"))
            lv.SubItems.Add(dtb.Rows(i).Item("Answer1"))
            lv.SubItems.Add(dtb.Rows(i).Item("Answer2"))
            lv.SubItems.Add(dtb.Rows(i).Item("Answer3"))
            lv.SubItems.Add(dtb.Rows(i).Item("Answer4"))
            Me.lvwListOfQuizzes.Items.Add(lv)
        Next
    Catch ex As Exception
        MsgBox(ex.Message)
        AConn.Close()
    End Try
End Sub

Private Sub lvwListOfQuizzes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvwListOfQuizzes.Click
    Me.cmdNextQ.Visible = True

    Try
        Dim strSql As String = "SELECT * FROM tblQuestions WHERE [QuizID1] =  " & lvwListOfQuizzes.SelectedItems(0).SubItems(0).Text & ""
        Dim dtb As New DataTable
        AConn.Open()
        Using dataadapter As New OleDbDataAdapter(strSql, AConn)
            dataadapter.Fill(dtb)
        End Using
        AConn.Close()
        For Each row As DataRow In dtb.Rows
            Me.lblQuizName.Text = row("QuizTitle").ToString()
            Me.lblCourseSubject.Text = row("CourseSubject").ToString()
            Me.lblQNum.Text = row("QuestionNumber").ToString()
            Me.lblQuestion.Text = row("ActualQuestion").ToString()
            Me.lblA.Text = row("Answer1").ToString()
            Me.lblB.Text = row("Answer2").ToString()
            Me.lblC.Text = row("Answer3").ToString()
            Me.lblD.Text = row("Answer4").ToString()
        Next
    Catch ex As Exception
        MsgBox(ex.Message)
        AConn.Close()
    End Try
End Sub
</code>```

The above code generates duplicates in my listview. For example I have five quiz titles saying "Countries" in my database (with different questions attached to each of the five titles), my listview shows all of the five same titles. I only need it to show just one since it's just one quiz title

答:
You can do this,

Since data is assigned to datarows before being poured into a listview, I would suggest preventing duplicates from accessing rows rather than making long researches of data at anytime you inject 'em into listview.

```<code>Dim lastrow As DataRow
Sub tbnewrow(Objet As DataTable, e As DataRowChangeEventArgs)
        If (e.Action = DataRowAction.Commit) Then
            If (Objet.Rows.IndexOf(lastrow) > 0 AndAlso e.Row.Item(1) = Objet.Rows(Objet.Rows.IndexOf(lastrow)).Item(1)) Then
                e.Row.Item(1) = ""
            Else
                lastrow = e.Row
            End If
        End If
End Sub
</code>```

This can assure that the second column doesn't have duplicate rows all stowed repeatedly in one load.

Now just bind this event to your datatable.

```<code>Dim dtb As New DataTable
AddHandler dtb .RowChanged, AddressOf tbnewrow
</code>```

Following this, you could maybe prefer to use a datagrid instead of listview, this is more time saving.

Title: Duplicate items in ListView vb.net 2008

Body:
I am trying to remove the duplicates in my listview. Here's my code:

Imports System.Data.OleDb
Public Class frmQuizSelector

Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click
    Me.Hide()
End Sub

Private Sub lvwQuizzes()
    With Me.lvwListOfQuizzes
        .FullRowSelect = True
        .GridLines = False
        .View = View.Details
        .Columns.Add("QuizID", 1)
        .Columns.Add("Quiz Title", 268)
    End With
End Sub

Private Sub frmQuizSelector_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.cmdPrevQ.Visible = False
    Me.cmdNextQ.Visible = False

    lvwQuizzes()

    Try
        Dim dtb As New DataTable
        Dim strSql As String = "SELECT * FROM tblQuestions"
        AConn.Open()
        Using dataadapter As New OleDbDataAdapter(strSql, AConn)
            dataadapter.Fill(dtb)
        End Using
        AConn.Close()
        Me.lvwListOfQuizzes.Items.Clear()
        Dim i As Integer = 0
        For i = 0 To dtb.Rows.Count - 1
            Dim lv As New ListViewItem
            lv.Text = dtb.Rows(i).Item("QuizID1")
            lv.SubItems.Add(dtb.Rows(i).Item("QuizTitle"))
            lv.SubItems.Add(dtb.Rows(i).Item("CourseSubject"))
            lv.SubItems.Add(dtb.Rows(i).Item("QuestionNumber"))
            lv.SubItems.Add(dtb.Rows(i).Item("ActualQuestion"))
            lv.SubItems.Add(dtb.Rows(i).Item("Answer1"))
            lv.SubItems.Add(dtb.Rows(i).Item("Answer2"))
            lv.SubItems.Add(dtb.Rows(i).Item("Answer3"))
            lv.SubItems.Add(dtb.Rows(i).Item("Answer4"))
            Me.lvwListOfQuizzes.Items.Add(lv)
        Next
    Catch ex As Exception
        MsgBox(ex.Message)
        AConn.Close()
    End Try
End Sub

Private Sub lvwListOfQuizzes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvwListOfQuizzes.Click
    Me.cmdNextQ.Visible = True

    Try
        Dim strSql As String = "SELECT * FROM tblQuestions WHERE [QuizID1] =  " & lvwListOfQuizzes.SelectedItems(0).SubItems(0).Text & ""
        Dim dtb As New DataTable
        AConn.Open()
        Using dataadapter As New OleDbDataAdapter(strSql, AConn)
            dataadapter.Fill(dtb)
        End Using
        AConn.Close()
        For Each row As DataRow In dtb.Rows
            Me.lblQuizName.Text = row("QuizTitle").ToString()
            Me.lblCourseSubject.Text = row("CourseSubject").ToString()
            Me.lblQNum.Text = row("QuestionNumber").ToString()
            Me.lblQuestion.Text = row("ActualQuestion").ToString()
            Me.lblA.Text = row("Answer1").ToString()
            Me.lblB.Text = row("Answer2").ToString()
            Me.lblC.Text = row("Answer3").ToString()
            Me.lblD.Text = row("Answer4").ToString()
        Next
    Catch ex As Exception
        MsgBox(ex.Message)
        AConn.Close()
    End Try
End Sub

The above code generates duplicates in my listview. For example I have five quiz titles saying "Countries" in my database (with different questions attached to each of the five titles), my listview shows all of the five same titles. I only need it to show just one since it's just one quiz title

Body:
You can do this,

Since data is assigned to datarows before being poured into a listview, I would suggest preventing duplicates from accessing rows rather than making long researches of data at anytime you inject 'em into listview.

Dim lastrow As DataRow
Sub tbnewrow(Objet As DataTable, e As DataRowChangeEventArgs)
        If (e.Action = DataRowAction.Commit) Then
            If (Objet.Rows.IndexOf(lastrow) > 0 AndAlso e.Row.Item(1) = Objet.Rows(Objet.Rows.IndexOf(lastrow)).Item(1)) Then
                e.Row.Item(1) = ""
            Else
                lastrow = e.Row
            End If
        End If
End Sub

This can assure that the second column doesn't have duplicate rows all stowed repeatedly in one load.

Now just bind this event to your datatable.

Dim dtb As New DataTable
AddHandler dtb .RowChanged, AddressOf tbnewrow

Following this, you could maybe prefer to use a datagrid instead of listview, this is more time saving.


问:
passing function reference to a C pointer type, C will invoke the function
I have a simple question i.e. how can I pass objective-C function reference as a C function pointer so that C can invoke that function.

edit: Sorry for not providing the sample source here it is:

```<code>- (void)init {
      CLibStructure cLibObject;
      cLibObject.on_work_done = &cWorkDone;
}
</code>```

the function that will point to on_work_done will have this signature in C

```<code>static void cWorkDone(const char *workInfo);
</code>```

whereas in objective-C this is the signature that I made

```<code>- (void) workDoneWithStatusMessage:(const char *message);
</code>```

Now i want is to point cLib.on_work_done the pointer to objective-c function, if I point to standard C function it works.

答:
You can create a function that calls the method, and then manipulate a pointer to that:

```<code>int function(NSObject *something, int someArg)
{
     return [something thisIsAMethod:someArg];
     //assuming NSObject has a method called thisIsAMethod that takes an int as a parameter and returns an int.
}
</code>```

and then you could use a pointer to this function:

```<code>int (*pointerToFunction)(NSObject *, int) = &function;
</code>```

Body:
I have a simple question i.e. how can I pass objective-C function reference as a C function pointer so that C can invoke that function.

edit: Sorry for not providing the sample source here it is:

- (void)init {
      CLibStructure cLibObject;
      cLibObject.on_work_done = &cWorkDone;
}

the function that will point to on_work_done will have this signature in C

static void cWorkDone(const char *workInfo);

whereas in objective-C this is the signature that I made

- (void) workDoneWithStatusMessage:(const char *message);

Now i want is to point cLib.on_work_done the pointer to objective-c function, if I point to standard C function it works.

Body:
You can create a function that calls the method, and then manipulate a pointer to that:

int function(NSObject *something, int someArg)
{
     return [something thisIsAMethod:someArg];
     //assuming NSObject has a method called thisIsAMethod that takes an int as a parameter and returns an int.
}

and then you could use a pointer to this function:

int (*pointerToFunction)(NSObject *, int) = &function;


问:
Peewee Access one-to-many attribute after Join
I have a table called Posts

```<code>class Posts(BaseModel):
    post_id= peewee.PrimaryKeyField()
    content = CharField(null=True)
    author = CharField(null=True)
</code>```

and a table called Likes

```<code>class Likes(BaseModel):
    user_like_id = ForeignKeyField(User,to_field='uniqueid', db_column='user_like_id')
    post_like_id = ForeignKeyField(Posts,to_field='post_id', db_column='post_like_id')

    class Meta:
        db_table='likes'
        primary_key = CompositeKey("user_like_id","post_like_id")
</code>```

Where the post_like_id refers to the post_id.
I am trying to make a single database call where I can get 10 posts and all the likes for those posts without issuing a database call for each post (iterating over each post_id and getting the count of Likes with that ID).

When I join as follows:

```<code>k = Posts.select().join(Likes,on=(Posts.post_id == Likes.post_like_id)).execute()
</code>```

I have no way of accessing how many Likes were made on a single post.

答:
Get the 10 most-liked posts, e.g. (JOIN.LEFT_OUTER is needed to include posts that have zero likes, fyi):</p>

```<code>query = (Posts
         .select(Post, fn.COUNT(Likes.id).alias('ct'))
         .join(Likes, JOIN.LEFT_OUTER)
         .group_by(Post)
         .order_by(fn.COUNT(Likes.id).desc())
         .limit(10))
</code>```

Body:
I have a table called Posts

class Posts(BaseModel):
    post_id= peewee.PrimaryKeyField()
    content = CharField(null=True)
    author = CharField(null=True)

and a table called Likes

class Likes(BaseModel):
    user_like_id = ForeignKeyField(User,to_field='uniqueid', db_column='user_like_id')
    post_like_id = ForeignKeyField(Posts,to_field='post_id', db_column='post_like_id')

    class Meta:
        db_table='likes'
        primary_key = CompositeKey("user_like_id","post_like_id")

Where the post_like_id refers to the post_id.
I am trying to make a single database call where I can get 10 posts and all the likes for those posts without issuing a database call for each post (iterating over each post_id and getting the count of Likes with that ID).

When I join as follows:

k = Posts.select().join(Likes,on=(Posts.post_id == Likes.post_like_id)).execute()

I have no way of accessing how many Likes were made on a single post.

Body:
Get the 10 most-liked posts, e.g. (JOIN.LEFT_OUTER is needed to include posts that have zero likes, fyi):

query = (Posts
         .select(Post, fn.COUNT(Likes.id).alias('ct'))
         .join(Likes, JOIN.LEFT_OUTER)
         .group_by(Post)
         .order_by(fn.COUNT(Likes.id).desc())
         .limit(10))


问:
Determine elapsed time in function?
I am using RabbitMQ and Python to retrieve messages from the RabbitMQ server.  I would like the program to do something if more than 5 minutes have elapsed and no message was received from Rabbitmq.

I found the sample python code on the RabbitMQ website, and it runs and prints each message received.  I am trying to figure out how to add a timer so that I can do XYZ if more than 5 minutes have elapsed since a message was received.

Any thoughts on how to accomplish this?  Below is the code from RabbitMQ:

```<code>#!/usr/bin/env python
import pika
import time

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)        # Print out received message

channel.basic_consume(callback,
                      queue='SlackWebhook',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
</code>```

答:
You can create a Singleton object that is instantiated only once in your program. Inside this object, you can create a timer. You start the timer, keep it running, and reset it to zero each time receive something from RabbitMQ. Inside that Singleton, you need to have a while True loop that checks the timer and triggers some action if time elapsed is more than 5 minutes.

The basic idea is to have a timer running, setting it to zero each time you receive from RabbitMQ, and have an observer checking that timer for how much time has elapsed. The implementation can be with a Singleton, or any other data structure that will persist throughout your program. If you have multiple threads or processes, it'd be easier to use a persistent database or built-in thread-safe Python data structures.

Hope this helped.

Title: Determine elapsed time in function?

Body:
I am using RabbitMQ and Python to retrieve messages from the RabbitMQ server.  I would like the program to do something if more than 5 minutes have elapsed and no message was received from Rabbitmq.

I found the sample python code on the RabbitMQ website, and it runs and prints each message received.  I am trying to figure out how to add a timer so that I can do XYZ if more than 5 minutes have elapsed since a message was received.

Any thoughts on how to accomplish this?  Below is the code from RabbitMQ:

#!/usr/bin/env python
import pika
import time

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)        # Print out received message

channel.basic_consume(callback,
                      queue='SlackWebhook',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()


问:
Highlight item onClick - React.js
Add underscore to category-item onClick and remove underscore for any other item. Found some answers on how to do this with only two components, a "item-container-component" and "item-components". But i have three components involved. This is what I hope to achieve:

Archive-component (mother component):

```<code>class Archive extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      products: [],
      category: "",
      activeIndex: 0
    }
    this.filterHandler = this.filterHandler.bind(this);
  }

  filterHandler(tag, index){
    console.log('INDEX: ' + index);
    this.setState({
      category: tag,
      activeIndex: index
    })
  }

  componentDidMount(){
    const myInit = {
      method: "GET",
      headers: {
         "Content-Type": "application/json"
      }
    };

    fetch("/getProducts", myInit)
      .then((res) => {
        return res.json();
      })
      .then((data) => {
        this.setState({products:data});
      })
      .catch(function(err) {
        console.log('ERROR!!! ' + err.message);
      });
  }

  render() {
    return (
      <div>
        <Menu />
        <div className="archive-container">
          <div className="archive-wrapper">
            <CategoryContainer
              filterHandler={this.filterHandler}
              products={this.state.products}
              activeIndex={this.state.activeIndex}
            />
            <br/><br/>
            <ProductContainer
              products={this.state.category.length
                ? this.state.products.filter((prod) => prod.category === this.state.category)
                : this.state.products.filter((prod) => prod.category === 'Paint')
              }
            />
          </div>
        </div>
        <Footer />
      </div>
    );
  };
};
</code>```

Category-container component:

```<code>class CategoryContainer extends Component {

  render(){
    const categories = [...new Set(this.props.products.map(cat => cat.category))];

    return (
      <div>
        <ul className="filterList">{
          categories.map((cat, index) =>
            <CategoryItem
              key={index}
              index={index}
              category={cat}
              active={index === this.props.activeIndex}
              handleClick={() => this.props.filterHandler(cat, index)}
            />
          )
        }</ul>
      </div>
    );
  };
};
</code>```

Category-item component:

```<code>class CategoryItem extends Component {
  render(){
    return (
      <div>
        <li
          className={this.props.active ? 'active' : 'category'}
          onClick={this.props.handleClick}
        >
            {this.props.category}

        </li>
      </div>
    );
  };
};
</code>```

Yelp!
M

答:
Suppose you have a li tag for which you want to change the color of.
you could probably try something like this.

Then in your react class you can have the on click function with parameters e:

```<code>onClick(e) {
   //This would give you all the field of the target
   console.log(e.target.elements);
   // you can do all sorts of Css change by this way
   e.target.element.class="newGreenColor";
}
</code>```

Also make sure to make a state or a prop change otherwise the page would not render again.

Title: Highlight item onClick - React.js

Body:
Add underscore to category-item onClick and remove underscore for any other item. Found some answers on how to do this with only two components, a "item-container-component" and "item-components". But i have three components involved. This is what I hope to achieve:

Archive-component (mother component):

class Archive extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      products: [],
      category: "",
      activeIndex: 0
    }
    this.filterHandler = this.filterHandler.bind(this);
  }

  filterHandler(tag, index){
    console.log('INDEX: ' + index);
    this.setState({
      category: tag,
      activeIndex: index
    })
  }

  componentDidMount(){
    const myInit = {
      method: "GET",
      headers: {
         "Content-Type": "application/json"
      }
    };

    fetch("/getProducts", myInit)
      .then((res) => {
        return res.json();
      })
      .then((data) => {
        this.setState({products:data});
      })
      .catch(function(err) {
        console.log('ERROR!!! ' + err.message);
      });
  }

  render() {
    return (

        <Menu />

            <CategoryContainer
              filterHandler={this.filterHandler}
              products={this.state.products}
              activeIndex={this.state.activeIndex}
            />

            <ProductContainer
              products={this.state.category.length
                ? this.state.products.filter((prod) => prod.category === this.state.category)
                : this.state.products.filter((prod) => prod.category === 'Paint')
              }
            />

    );
  };
};

Category-container component:

class CategoryContainer extends Component {

  render(){
    const categories = [...new Set(this.props.products.map(cat => cat.category))];

    return (

{
          categories.map((cat, index) =>
            <CategoryItem
              key={index}
              index={index}
              category={cat}
              active={index === this.props.activeIndex}
              handleClick={() => this.props.filterHandler(cat, index)}
            />
          )
        }

    );
  };
};

Category-item component:

class CategoryItem extends Component {
  render(){
    return (

            {this.props.category}

    );
  };
};

Yelp!
M

Body:
Suppose you have a li tag for which you want to change the color of.
you could probably try something like this.

<li id="colorChangeOnClick" class="redColor" onclick={this.onClickFunction()}></li>

Then in your react class you can have the on click function with parameters e:

onClick(e) {
   //This would give you all the field of the target
   console.log(e.target.elements);
   // you can do all sorts of Css change by this way
   e.target.element.class="newGreenColor";
}

Also make sure to make a state or a prop change otherwise the page would not render again.


问:
Looking to Create a Randomized Array using Java
I'm building out a user defined array as a game board.  The characters used "O" and "." have to be randomized and the "O" has to appear more than once.

This is what I have thus far.

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

public class PacMan {

    public static void main(String[] args)
    {

        Scanner input = new Scanner(System.in);
        System.out.println("Input total rows:");
        int row = input.nextInt();
        System.out.println("Input total columns:");
        int column = input.nextInt();

        boolean[][] cookies = new boolean[row+2][column+2];
        for (int i = 1; i <= row; i++)
            for (int j = 1; j <= column; j++);
                cookies [row][column] = (Math.random() < 100);

        // print game
        for (int i = 1; i <= row; i++)
        {
            for (int j = 1; j <= column; j++)
                if (cookies[i][j]) System.out.print(" O ");
                else             System.out.print(". ");
            System.out.println();
        }
    }
}
</code>```

The output, for example, produces a 5 x 5 grid, but the "O" only appears once and is at the bottom right of the grid.

Assistance randomizing the "O" and "." and having the "O" appear in random fashion throughout the board which is initialized by the user input via Scanner.

Here is the updated code which is producing the output that I'm looking for and is user defined.

```<code>import java.util.*;
public class PacManTest
{
    public static void main(String[] args)
    {
        char O;
        Scanner input = new Scanner(System.in);
        System.out.println("Input total rows:");
        int row = input.nextInt();
        System.out.println("Input total columns:");
        int column = input.nextInt();

        char board[][] = new char[row][column];

        for(int x = 0; x < board.length; x++)
        {
            for(int i = 0; i < board.length; i++)
            {
                double random = Math.random();
                if(random >.01 && random <=.10)
                {
                    board[x][i] = 'O';
                }

                else {
                    board[x][i] = '.';
                }
                System.out.print(board[x][i] + " ");
            }
            System.out.println("");
        }
    }
}
</code>```

答:
The main issue is the typo in the first loop:

```<code>cookies [row][column] = (Math.random() < 100);
</code>```

should be

```<code>cookies [i][j] = (Math.random() < 100);
</code>```

Second, Math.random() returns a value greater than or equal to 0.0 and less than 1.0 (doc). So, (Math.random() < 100); will always be true. If you want a 50% chance of an O or . use:

```<code>cookies[i][j] = Math.random() < 0.5;
</code>```

Also, not sure what your motivation is for using a starting index of 1 but array indexes start at 0.

Body:
I'm building out a user defined array as a game board.  The characters used "O" and "." have to be randomized and the "O" has to appear more than once.

This is what I have thus far.

import java.util.Scanner;

public class PacMan {

    public static void main(String[] args)
    {

        Scanner input = new Scanner(System.in);
        System.out.println("Input total rows:");
        int row = input.nextInt();
        System.out.println("Input total columns:");
        int column = input.nextInt();

        boolean[][] cookies = new boolean[row+2][column+2];
        for (int i = 1; i <= row; i++)
            for (int j = 1; j <= column; j++);
                cookies [row][column] = (Math.random() < 100);

        // print game
        for (int i = 1; i <= row; i++)
        {
            for (int j = 1; j <= column; j++)
                if (cookies[i][j]) System.out.print(" O ");
                else             System.out.print(". ");
            System.out.println();
        }
    }
}

The output, for example, produces a 5 x 5 grid, but the "O" only appears once and is at the bottom right of the grid.

Assistance randomizing the "O" and "." and having the "O" appear in random fashion throughout the board which is initialized by the user input via Scanner.

Here is the updated code which is producing the output that I'm looking for and is user defined.

import java.util.*;
public class PacManTest
{
    public static void main(String[] args)
    {
        char O;
        Scanner input = new Scanner(System.in);
        System.out.println("Input total rows:");
        int row = input.nextInt();
        System.out.println("Input total columns:");
        int column = input.nextInt();

        char board[][] = new char[row][column];

        for(int x = 0; x < board.length; x++)
        {
            for(int i = 0; i < board.length; i++)
            {
                double random = Math.random();
                if(random >.01 && random <=.10)
                {
                    board[x][i] = 'O';
                }

                else {
                    board[x][i] = '.';
                }
                System.out.print(board[x][i] + " ");
            }
            System.out.println("");
        }
    }
}

Body:
The main issue is the typo in the first loop:

cookies [row][column] = (Math.random() < 100);

should be

cookies [i][j] = (Math.random() < 100);

Second, Math.random() returns a value greater than or equal to 0.0 and less than 1.0 (doc). So, (Math.random() < 100); will always be true. If you want a 50% chance of an O or . use:

cookies[i][j] = Math.random() < 0.5;

Also, not sure what your motivation is for using a starting index of 1 but array indexes start at 0.


问:
How to return the getText() values in array using protractor
I'm trying to return the options present in the list using the below function.

HTML

```<code><select>
  <option>one</option>
  <option>two</option>
  <option>three</option>
<select>
</code>```

Function

```<code>getValues(){
  var ele = element(by.xpath("......../select"));
  return ele.all(by.tagName('option')).getAttribute('value').getText().then(function (text){
  for (var i = 0; i < text.length; i++) {
    text[i] = text[i].trim();
  }
  return text;
 });
</code>```

}

When I print the values in console using console.log(getValues()), the console displays theManagedPromise{.....} function instead of options.

But I'm expecting the options as ["one","two","three"] array. Can anyone help me?

答:
```<code><!DOCTYPE html>
<html>
<body>

<select id="sel">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<p>Click the button to display values</p>

<button onclick="clickHandler()">Try it</button>

<p id="demo"></p>
</body>
<script "text/javacript">
function clickHandler() {
    var options = document.getElementById("sel").childNodes;
    let results =[];
    [].forEach.call(options, function(option) {
      if (option instanceof HTMLOptionElement) {
        results.push(option.text);
        // Swap for option.value if you like too would be lower case
      }
    });
    document.getElementById("demo").innerHTML = results.toString();
}
</script>
</html>
</code>```

See live demo here

HTMLOptionElement on MDN

Body:
I'm trying to return the options present in the list using the below function.

HTML

<select>
  <option>one</option>
  <option>two</option>
  <option>three</option>
<select>

Function

getValues(){
  var ele = element(by.xpath("......../select"));
  return ele.all(by.tagName('option')).getAttribute('value').getText().then(function (text){
  for (var i = 0; i < text.length; i++) {
    text[i] = text[i].trim();
  }
  return text;
 });

}

When I print the values in console using console.log(getValues()), the console displays theManagedPromise{.....} function instead of options.

But I'm expecting the options as ["one","two","three"] array. Can anyone help me?

Body:
<!DOCTYPE html>
<html>
<body>

<select id="sel">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<p>Click the button to display values</p>

<button onclick="clickHandler()">Try it</button>

<p id="demo"></p>
</body>
<script "text/javacript">
function clickHandler() {
    var options = document.getElementById("sel").childNodes;
    let results =[];
    [].forEach.call(options, function(option) {
      if (option instanceof HTMLOptionElement) {
        results.push(option.text);
        // Swap for option.value if you like too would be lower case
      }
    });
    document.getElementById("demo").innerHTML = results.toString();
}
</script>
</html>

See live demo here

HTMLOptionElement on MDN


问:
Cannot assign value of type UnsafeMutablePointer ObjCBool in Swift
I'm unfamiliar with Objective C.

I'm using a private framework and need to be able to change one of the properties from within my Swift code.

The property is declared in Objective C this way:

```<code>@property (nonatomic, assign) BOOL *isSSNField;
</code>```

in swift I am trying to change the value of the property this way:

```<code>myClass.isSSNField = true
</code>```

I am getting this error

```<code>Cannot assign a value of type 'Bool' to a value of type 'UnsafeMutablePointer<ObjcBool>'
</code>```

I'm not sure where to go from here, or why I'm getting this error at all

答:
The safer way to handle this would be very similar to @TanJunHao 's answer:</p>

```<code>var isSSNField = ObjCBool(true)
myClass.isSSNField = &isSSNField
</code>```

Body:
I'm unfamiliar with Objective C.

I'm using a private framework and need to be able to change one of the properties from within my Swift code.

The property is declared in Objective C this way:

@property (nonatomic, assign) BOOL *isSSNField;

in swift I am trying to change the value of the property this way:

myClass.isSSNField = true

I am getting this error

Cannot assign a value of type 'Bool' to a value of type 'UnsafeMutablePointer<ObjcBool>'

I'm not sure where to go from here, or why I'm getting this error at all

Body:
The safer way to handle this would be very similar to @TanJunHao 's answer:

var isSSNField = ObjCBool(true)
myClass.isSSNField = &isSSNField


问:
How to extract data from JS array in an html file to VBA
I'm trying to automate retrieval of information from an online source at my new internship. I've managed to create code that manages to open up the password-protected site, and navigate two additional pages to get to the page I want. However, this page has information tabulated that I am having trouble extracting. The information seems o be stored inside a javascript file being accessed by the HTML. Is there a way to get this info and put it in an excel worksheet?

Here is my code so far...Unfortunately, I can't display the URL, as I am not sure if my company will allow it.

```<code>            Sub AutomateIE()

            Dim URL As String
            Dim URL2 As String
            Dim IE As Object
            Dim objPage As Object

            Set IE = CreateObject("InternetExplorer.Application")
            IE.Visible = True

            URL = "URL"
            URL2 = "URL2"
            URL3 = "URL3"
            IE.navigate URL
            Do While IE.ReadyState < 4:
            DoEvents: Loop
            Do Until IE.ReadyState = 4:
            DoEvents: Loop

            Set objPage = IE.document
            objPage.getelementbyid("ucLogin_txtLogonID").Value = "Employee name"
            objPage.getelementbyid("ucLogin_txtLogonPassword").Value = "Employee password"
            Application.SendKeys "{Return}", True '
            Application.Wait (Now + TimeValue("0:00:05"))
            IE.navigate URL2
            Application.Wait (Now + TimeValue("0:00:05"))
            IE.navigate URL3

            End Sub
</code>```

答:
If it a static value defined in the script file , you can use XMLHTTP60 to get the responseText of the script file.

Such as :

var arr = ["hello", "world"];

Let's say you want "world"

Then load up the script in a ScriptControl object, and evaluate it:

```<code>Dim script As IHTMLScriptElement
Set script = doc.getElementById("myScript") 'may need another way to identify

Dim sControl As ScriptControl 'needs reference to Miscrosoft Script Control 1.0
Set sControl = New ScriptControl
sControl.Language = "JScript"

Dim xhr As MSXML2.XMLHTTP60
Set xhr = New MSXML2.XMLHTTP60
With xhr
     .Open "GET", URL3.Path & "/" & script.src, False 'define full path to script file properly
     'if necessary change above path to full script src URL
     .send
     Dim jsText As String
     jsText = .responseText
End With
sControl.AddCode jsText 'adds the contents of the script file to ScriptControl object

Dim v As Variant
v = sControl.Eval("arr[1]")

MsgBox v
</code>```

Body:
I'm trying to automate retrieval of information from an online source at my new internship. I've managed to create code that manages to open up the password-protected site, and navigate two additional pages to get to the page I want. However, this page has information tabulated that I am having trouble extracting. The information seems o be stored inside a javascript file being accessed by the HTML. Is there a way to get this info and put it in an excel worksheet?

Here is my code so far...Unfortunately, I can't display the URL, as I am not sure if my company will allow it.

            Sub AutomateIE()

            Dim URL As String
            Dim URL2 As String
            Dim IE As Object
            Dim objPage As Object

            Set IE = CreateObject("InternetExplorer.Application")
            IE.Visible = True

            URL = "URL"
            URL2 = "URL2"
            URL3 = "URL3"
            IE.navigate URL
            Do While IE.ReadyState < 4:
            DoEvents: Loop
            Do Until IE.ReadyState = 4:
            DoEvents: Loop

            Set objPage = IE.document
            objPage.getelementbyid("ucLogin_txtLogonID").Value = "Employee name"
            objPage.getelementbyid("ucLogin_txtLogonPassword").Value = "Employee password"
            Application.SendKeys "{Return}", True '
            Application.Wait (Now + TimeValue("0:00:05"))
            IE.navigate URL2
            Application.Wait (Now + TimeValue("0:00:05"))
            IE.navigate URL3

            End Sub

Body:
If it a static value defined in the script file , you can use XMLHTTP60 to get the responseText of the script file.

Such as :

var arr = ["hello", "world"];

Let's say you want "world"

Then load up the script in a ScriptControl object, and evaluate it:

Dim script As IHTMLScriptElement
Set script = doc.getElementById("myScript") 'may need another way to identify

Dim sControl As ScriptControl 'needs reference to Miscrosoft Script Control 1.0
Set sControl = New ScriptControl
sControl.Language = "JScript"

Dim xhr As MSXML2.XMLHTTP60
Set xhr = New MSXML2.XMLHTTP60
With xhr
     .Open "GET", URL3.Path & "/" & script.src, False 'define full path to script file properly
     'if necessary change above path to full script src URL
     .send
     Dim jsText As String
     jsText = .responseText
End With
sControl.AddCode jsText 'adds the contents of the script file to ScriptControl object

Dim v As Variant
v = sControl.Eval("arr[1]")

MsgBox v


问:
Ninject + ASP.NET MVC + InRequestScope
I have a problem with the Ninject.

My binding rules:

```<code>this.Bind<ISphinxQLServer>().To<SQLServer>();
this.Bind<IMySQLServer>().To<SQLServer>();

this.Bind<ISQLLogger>().To<StandardSQLLogger>()
    .InRequestScope();

this.Bind<DatabaseConnections>()
    .ToMethod(x => ConnectionFactory.GetConnections())
    .InRequestScope();

this.Bind<SQLServer>().ToSelf()
    .InRequestScope()
    .WithConstructorArgument("connections", Kernel.Get<DatabaseConnections>())
    .WithConstructorArgument("logger", Kernel.Get<ISQLLogger>());
</code>```

Where

SQLServer, ISphinxQLServer and IMySQLServer are:

```<code>public class SQLServer: ISphinxQLServer, IMySQLServer
{
    public DatabaseConnections Connections { get; internal set; }
    public ISQLLogger Logger { get; internal set; }

    public SQLServer(DatabaseConnections connections)
    {
        this.Connections = connections;
    }

    public SQLServer(DatabaseConnections connections, ISQLLogger logger)
    {
        this.Connections = connections;
        this.Logger = logger;
    }
}
</code>```

I want that each user request to my asp.net mvc site creates a single SQLServer, a single ISQLLogger and a single DatabaseConnections. But my solution dont work. What am I doing wrong? =(

答:
You don't need to specify the WithConstructorArgument. Resolving the parameters to the constructors of your injected objects is part of what Ninject does for you. So the definitions should look more like this:

```<code>this.Bind<SQLServer>()
    .ToSelf()
    .InRequestScope();

this.Bind<ISphinxQLServer>()
    .ToMethod( x => x.Kernel.Get<SQLServer>() );

this.Bind<IMySQLServer>()
    .ToMethod( x => x.Kernel.Get<SQLServer>() );

this.Bind<ISQLLogger>()
    .To<StandardSQLLogger>()
    .InRequestScope();

this.Bind<DatabaseConnections>()
    .ToMethod(x => ConnectionFactory.GetConnections())
    .InRequestScope();
</code>```

Title: Ninject + ASP.NET MVC + InRequestScope

Body:
I have a problem with the Ninject.

My binding rules:

this.Bind<ISphinxQLServer>().To<SQLServer>();
this.Bind<IMySQLServer>().To<SQLServer>();

this.Bind<ISQLLogger>().To<StandardSQLLogger>()
    .InRequestScope();

this.Bind<DatabaseConnections>()
    .ToMethod(x => ConnectionFactory.GetConnections())
    .InRequestScope();

this.Bind<SQLServer>().ToSelf()
    .InRequestScope()
    .WithConstructorArgument("connections", Kernel.Get<DatabaseConnections>())
    .WithConstructorArgument("logger", Kernel.Get<ISQLLogger>());

Where

SQLServer, ISphinxQLServer and IMySQLServer are:

public class SQLServer: ISphinxQLServer, IMySQLServer
{
    public DatabaseConnections Connections { get; internal set; }
    public ISQLLogger Logger { get; internal set; }

    public SQLServer(DatabaseConnections connections)
    {
        this.Connections = connections;
    }

    public SQLServer(DatabaseConnections connections, ISQLLogger logger)
    {
        this.Connections = connections;
        this.Logger = logger;
    }
}

I want that each user request to my asp.net mvc site creates a single SQLServer, a single ISQLLogger and a single DatabaseConnections. But my solution dont work. What am I doing wrong? =(

Body:
You don't need to specify the WithConstructorArgument. Resolving the parameters to the constructors of your injected objects is part of what Ninject does for you. So the definitions should look more like this:

this.Bind<SQLServer>()
    .ToSelf()
    .InRequestScope();

this.Bind<ISphinxQLServer>()
    .ToMethod( x => x.Kernel.Get<SQLServer>() );

this.Bind<IMySQLServer>()
    .ToMethod( x => x.Kernel.Get<SQLServer>() );

this.Bind<ISQLLogger>()
    .To<StandardSQLLogger>()
    .InRequestScope();

this.Bind<DatabaseConnections>()
    .ToMethod(x => ConnectionFactory.GetConnections())
    .InRequestScope();


问:
Regex in Vim- inserting blank line before numbered lines
I have following text:

```<code>Title line
1. First list
First line
Second line
2. Second list
Oranges
Mangoes
3. Stationary
Pen
Pencils
Etc
</code>```

I want to add a blank line before every numbered line, so that above text looks like following:

```<code>Title line

1. First list
First line
Second line

2. Second list
Oranges
Mangoes

3. Stationary
Pen
Pencils
Etc
</code>```

I tried following code but it is not working:

```<code>%s/^(\d)/\r\1/g
</code>```

and

```<code>%s/(^\d)/\r\1/g
</code>```

and

%s/^([0-9])/\r\1/gc

Where is the problem and how can this be solved. Thanks for your help.

答:
You can use the global command, :g to execute an empty :put on each line before the matching number, ^\d.

```<code>:g/^\d/pu!_
</code>```

Note: Using the blackhole register, "_, combined with :put to give us the empty line.

For more help see:

```<code>:h :g
:h /\d
:h :put
:h quote_
</code>```

Body:
I have following text:

Title line
1. First list
First line
Second line
2. Second list
Oranges
Mangoes
3. Stationary
Pen
Pencils
Etc

I want to add a blank line before every numbered line, so that above text looks like following:

Title line

1. First list
First line
Second line

2. Second list
Oranges
Mangoes

3. Stationary
Pen
Pencils
Etc

I tried following code but it is not working:

%s/^(\d)/\r\1/g

and

%s/(^\d)/\r\1/g

and

%s/^([0-9])/\r\1/gc

Where is the problem and how can this be solved. Thanks for your help.

Body:
You can use the global command, :g to execute an empty :put on each line before the matching number, ^\d.

:g/^\d/pu!_

Note: Using the blackhole register, "_, combined with :put to give us the empty line.

For more help see:

:h :g
:h /\d
:h :put
:h quote_


问:
How can I get Visual Studio 2017 to sign a Win32 application automatically?
I am using visual studio 2017. I am not a developer. I am just trying to write a simple parsing script and I am familiar with visual studio. I use Atmel Studio(which is based off VS) to write embedded code, but I don't have to deal with signing. I installed visual studio on my work computer and now I get bit9 errors every time I make a new build.

Internal IT has pointed me to a bunch of slightly outdated certificate stuff. I now have a certificate to apply to my builds, however the process defined here will apparently not work for a Win32 application. I do not have a Signing tab in the project properties.

I have also looked into the visual studio command line using signtool. However, it would take a lot of my time to learn how it works and implement it.

Hopefully someone else has solved this and I can save the time. If there are no easy solutions I'll just go back to manually parsing, because this has already taken up to much of my time.

答:
This is how i've done this with Visual Studio 2010 and Visual Studio 2015 for unmanaged C or C++ Win32 applications. You need:

A signing certificate. This is normally given as a PFX when working in Windows, and is typically an intermediate certificate in your certificate chain.

The password to the above PFX to decrypt the certificate private key.

With those, the following custom build step for your Win32 project can be created:

```<code>"$(FrameworkSDKDir)bin\x86\signtool.exe" sign /v /f "path-to-your-cert\yourcert.pfx" /p password "$(TargetPath)" > "$(OutDir)sign\$(ProjectName)-sign.out"
</code>```

This will use your certificate to sign the project output (be it a DLL or EXE makes no difference), and record the output of the signing certificate in a file named after your project with the suffix sign.out, placing that file in a folder called sign off your output directory.

That may seem a bit overkill, but there is a reason for that generated output file. By creating that file, and naming it as one of the "Outputs" of the custom build step:

it can be comparatively used to determine whether to re-sign or not. Each time the project is built, if the target image (your exe or dll) is regenerated that output file will be out-of-date and the custom build step will be kicked off to regenerate it (and thusly also re-sign the image). The sign.out file, btw, will contain something like this:

The following certificate was selected:
    Issued to: The Signing Cert Name Here

    Issued by: The Issuer Cert Name Here

    Expires:   Sat Dec 31 16:59:59 2039

    SHA1 hash: 232C80E19EBC71330E7C12CA8C07B345B1531777

Done Adding Additional Store
Successfully signed: full-path-to-image-here

Number of files successfully Signed: 1

Number of warnings: 0

Number of errors: 0
```

Once you have your PFX and password, you can easily just hand-test the command before you finally configure it as part of the build. The only real wildcard I've seen is the full path to the signtool.exe, which seemingly changes from time to time (different with VS2008 than with VS2015, for example.

Anyway, that's how I did it. Hopefully you can too.

Body:
This is how i've done this with Visual Studio 2010 and Visual Studio 2015 for unmanaged C or C++ Win32 applications. You need:

A signing certificate. This is normally given as a PFX when working in Windows, and is typically an intermediate certificate in your certificate chain.

The password to the above PFX to decrypt the certificate private key.

With those, the following custom build step for your Win32 project can be created:

"$(FrameworkSDKDir)bin\x86\signtool.exe" sign /v /f "path-to-your-cert\yourcert.pfx" /p password "$(TargetPath)" > "$(OutDir)sign\$(ProjectName)-sign.out"

This will use your certificate to sign the project output (be it a DLL or EXE makes no difference), and record the output of the signing certificate in a file named after your project with the suffix sign.out, placing that file in a folder called sign off your output directory.

That may seem a bit overkill, but there is a reason for that generated output file. By creating that file, and naming it as one of the "Outputs" of the custom build step:

it can be comparatively used to determine whether to re-sign or not. Each time the project is built, if the target image (your exe or dll) is regenerated that output file will be out-of-date and the custom build step will be kicked off to regenerate it (and thusly also re-sign the image). The sign.out file, btw, will contain something like this:

The following certificate was selected:
    Issued to: The Signing Cert Name Here

    Issued by: The Issuer Cert Name Here

    Expires:   Sat Dec 31 16:59:59 2039

    SHA1 hash: 232C80E19EBC71330E7C12CA8C07B345B1531777

Done Adding Additional Store
Successfully signed: full-path-to-image-here

Number of files successfully Signed: 1

Number of warnings: 0

Number of errors: 0

Once you have your PFX and password, you can easily just hand-test the command before you finally configure it as part of the build. The only real wildcard I've seen is the full path to the signtool.exe, which seemingly changes from time to time (different with VS2008 than with VS2015, for example.

Anyway, that's how I did it. Hopefully you can too.


问:
Github integration & Services (How to enable)
I have github repository with Amazon SNS service enable. It suppose to push message, but it never does it with grey dot "this hook has never been triggered".
I can trigger this service manually by clicking "Test service". It works fine. </p>

<p>I've tried git push (pushing changes). </p>

答: Since you are adding ARN into Github field, make sure you use relevant AWS role and it has sufficient permissions to access your lambda code. </p>

Body:
I have github repository with Amazon SNS service enable. It suppose to push message, but it never does it with grey dot "this hook has never been triggered".
I can trigger this service manually by clicking "Test service". It works fine.

I've tried git push (pushing changes).