问:
python listing mouse click coordinates
I would like to record and append to a list the x and y coordinates of limited number of mouse clicks (10 in this case (This will be a variable)). The script needs to record the clicks over the desktop, browsers or applications in general.

I am basically trying to create a list of coordinates for a flexible simple macro section of a larger program for desktop automation (Very simple and repetitive work but the layout does change that is why re-recording the coordinates is key).

I have searched through "Automate the boring stuff" and cant get pyautogui to record the positions (It does execute mouse positions perfectly but not the pre-recording list). Also this cannot be limited to a single frame as seems to be the case in pygame.

Im a noob any advice would be appreciated. I have included an image of the error I receive. The list portion is not included yet I will add that later.

```<code>from pynput import mouse

NumberOfMouseClicks = 0

def on_click(x, y, button, pressed):
    print(x, y)
    pynput.mouse.Listener.stop

while NumberOfMouseClicks < 10 :
    NumberOfMouseClicks = NumberOfMouseClicks + 1
    with mouse.Listener(on_click=on_click) as listener:
        listener.join()
</code>```

enter image description here

答:
You have not imported the pynput package only mouse from it.
So instead of

```<code>pynput.mouse.Listener.stop
</code>```

you should use

```<code>mouse.Listener.stop
</code>```

The mouse event is handled in the on_click function, the while loop is useless. You can use it so:

```<code>from pynput import mouse

class MyException(Exception):pass

NumberOfMouseClicks = 0

def on_click(x, y, button, pressed):
    global NumberOfMouseClicks
    print(x, y)
    NumberOfMouseClicks = NumberOfMouseClicks + 1
    if (NumberOfMouseClicks==10):
        raise MyException(button)

with mouse.Listener(on_click=on_click) as listener:
    try:
        listener.join()
    except MyException as e:
        pass
</code>```

Title: python listing mouse click coordinates

Body:
I would like to record and append to a list the x and y coordinates of limited number of mouse clicks (10 in this case (This will be a variable)). The script needs to record the clicks over the desktop, browsers or applications in general.

I am basically trying to create a list of coordinates for a flexible simple macro section of a larger program for desktop automation (Very simple and repetitive work but the layout does change that is why re-recording the coordinates is key).

I have searched through "Automate the boring stuff" and cant get pyautogui to record the positions (It does execute mouse positions perfectly but not the pre-recording list). Also this cannot be limited to a single frame as seems to be the case in pygame.

Im a noob any advice would be appreciated. I have included an image of the error I receive. The list portion is not included yet I will add that later.

from pynput import mouse

NumberOfMouseClicks = 0

def on_click(x, y, button, pressed):
    print(x, y)
    pynput.mouse.Listener.stop

while NumberOfMouseClicks < 10 :
    NumberOfMouseClicks = NumberOfMouseClicks + 1
    with mouse.Listener(on_click=on_click) as listener:
        listener.join()

enter image description here

Body:
You have not imported the pynput package only mouse from it.
So instead of

pynput.mouse.Listener.stop

you should use

mouse.Listener.stop

The mouse event is handled in the on_click function, the while loop is useless. You can use it so:

from pynput import mouse

class MyException(Exception):pass

NumberOfMouseClicks = 0

def on_click(x, y, button, pressed):
    global NumberOfMouseClicks
    print(x, y)
    NumberOfMouseClicks = NumberOfMouseClicks + 1
    if (NumberOfMouseClicks==10):
        raise MyException(button)

with mouse.Listener(on_click=on_click) as listener:
    try:
        listener.join()
    except MyException as e:
        pass


来源: stackexchange

问:
javascript onclick fade div in (short code)
i'm been lookin all over the place and cannot find exactly what im after anywhere.

the html structure is basically.

```<code><ul>
   <li><a href="">link</a></li>
   <div id="us">hidden info</div>
</ul>
</code>```

the css structure is.

```<code>#us {display:none}
</code>```

I'd like it so when "link" is clicked the div "us" is changed from dipslay:none; to display:block, in a graceful fade in as little lines of code as possible, and then again when the link is clicked its toggled back to display:hidden.

I'm aware that there are lots of things that can do this, but im really lookin for that simplicity in code.

thanks for your time x

答:
If jQuery UI is an option for you, I can only recommend it.
jQuery UI extends jQuery with many nice effects:

```<code>show( effect, [options], [speed], [callback] )
</code>```

But check out the website itself: http://jqueryui.com/demos/show/

ContentLicense: CC BY-SA 2.5

Body:
i'm been lookin all over the place and cannot find exactly what im after anywhere.

the html structure is basically.

link

hidden info

the css structure is.

#us {display:none}

I'd like it so when "link" is clicked the div "us" is changed from dipslay:none; to display:block, in a graceful fade in as little lines of code as possible, and then again when the link is clicked its toggled back to display:hidden.

I'm aware that there are lots of things that can do this, but im really lookin for that simplicity in code.

thanks for your time x

Body:
If jQuery UI is an option for you, I can only recommend it.
jQuery UI extends jQuery with many nice effects:

show( effect, [options], [speed], [callback] )

But check out the website itself: http://jqueryui.com/demos/show/


问:
How do I integrate Google Translate into Java?
I was wondering if there's a way that I could integrate google translate into a Java program I am making. I use Eclipse. I sorta did a few things but now I'm completely lost (I'm only a rookie when it comes to programming).

my progress so far:
- I have a Google Translate API Key.
- I got the "google tab" for eclipse and installed the Translate API.

I also have the "Google CLoud SDK shell" downloaded but now I'm not exactly sure what to do.

Help walking me through the steps would be appreciated!

Thank You!

答:
I suggest you to see the google-api-services-translate-v2 here:
https://developers.google.com/api-client-library/java/apis/translate/v2

Basically, if you are using maven you have to add this dependency:

```<code><dependency>
  <groupId>com.google.apis</groupId>
  <artifactId>google-api-services-translate</artifactId>
  <version>v2-rev48-1.22.0</version>
</dependency>
</code>```

Then you can use it:

```<code>    TranslateRequestInitializer translateRequestInitializer = new TranslateRequestInitializer(
            "Generated key from google console");

    // Set up the HTTP transport and JSON factory
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    // set up translate
    final Translate translate = new Translate.Builder(httpTransport, jsonFactory, null)
            .setApplicationName("My Apps").setTranslateRequestInitializer(translateRequestInitializer).build();

    List<String> sourceTextList = Arrays.asList("source Text");
    // translate
    System.out.println(translate.translations().list(sourceTextList, "fr").execute());
</code>```

You can find samples here: https://developers.google.com/api-client-library/java/google-api-java-client/samples

ContentLicense: CC BY-SA 3.0

Body:
I suggest you to see the google-api-services-translate-v2 here:
https://developers.google.com/api-client-library/java/apis/translate/v2

Basically, if you are using maven you have to add this dependency:

<dependency>
  <groupId>com.google.apis</groupId>
  <artifactId>google-api-services-translate</artifactId>
  <version>v2-rev48-1.22.0</version>
</dependency>

Then you can use it:

    TranslateRequestInitializer translateRequestInitializer = new TranslateRequestInitializer(
            "Generated key from google console");

    // Set up the HTTP transport and JSON factory
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    // set up translate
    final Translate translate = new Translate.Builder(httpTransport, jsonFactory, null)
            .setApplicationName("My Apps").setTranslateRequestInitializer(translateRequestInitializer).build();

    List<String> sourceTextList = Arrays.asList("source Text");
    // translate
    System.out.println(translate.translations().list(sourceTextList, "fr").execute());

You can find samples here: https://developers.google.com/api-client-library/java/google-api-java-client/samples


问:
scala: assign null to primitive
I am trying to assign null to a variable which is Double like this:

```<code>var foo = 0.0
foo = null
</code>```

However, this gives an error that null cannot be implicitly converted to Double

So I do this instead:

```<code>foo = null.asInstanceOf[Double]
</code>```

however the new value for foo is 0.0

How can I set the value to null?

答:
To answer your question why the complier complain when assigning a null to double variable, you can easily understand via the scala classes hierarchy diagram:

http://docs.scala-lang.org/tutorials/tour/unified-types.html

In short,

Double is a sub class of Anyval

null (a instance of Null) is a sub class of AnyRef.

So they are different types or classes in scala, it is similar to assign a List to a String.

Title: scala: assign null to primitive

Body:
I am trying to assign null to a variable which is Double like this:

var foo = 0.0
foo = null

However, this gives an error that null cannot be implicitly converted to Double

So I do this instead:

foo = null.asInstanceOf[Double]

however the new value for foo is 0.0

How can I set the value to null?


问:
How to replace an array in perl with a query for contents of a sql database?
Edit: (See Revised Code Near bottom) I have the code working to pull from the 2 databases (I know some cleaning is still needed),
but where I am stuck is, I was prviously able to use:

```<code>next unless $currentuser ~~ @las;
</code>```

but once I linked the mySQL database, it isn't filtering out undefined/unqualified (blank) results. I am not sure how to restructure this function to re-enable the functionality. (I think the way I am approaching the logic may be off). But this is where I am currently confused and need guidance.

I currently use this code to view logged in users to check for employees in our department:

```<code> #! /usr/bin/perl
use strict;
use warnings;

$ENV{'ORACLE_HOME'} ="/usr/lib/oracle/11.2/client64";
use DBI;
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

#current emplyees go here:
my @las = qw(

user12
user13
user14
user15
user16
user17
user18
user19
user20
user21
user22
user23
user24
user25
user26
user27
user28
user29
user30
user31
user32
user33
user34
user35
user36
user37
user38
user39
user40
user41
user42
user43
user44
user45
user46
user47
user48
user49
user50
user51
user52
user53
user54
user55
user56
user57
user58
user59
user60
user61
user62
user63
user64
user65
user66
user67
user68
user69
user70
user71
user72
user73
user74
user75
user76
user77
user78
user79
user80
user81
user82
user83
user84
user85
user86
user87
user88
user89
user90
user91
user92
user93
user94
user95
user96
user97
user98
user99
user100
user101
user102
user103
user104
user105
user106
user107
user108
user109
user110
user111
user112
user113
user114
user115
user116
user117
user118
user119
user120
user121
user122
user123
user124
user125
user126
user127
user128
user129
user130
user131
user132
user133
user134
user135
user136
user137
user138
user139
user140
user141
user142
user143
user144
user145
user146
user147
user148
user149
user150
user151
user152
user153
user154
user155
user156
user157
user158
user159
user160
user161
user162
user163
user164
user165
user166
user167
user168
user169
user170
user171
user172
user173
user174
user175
user176
user177
user178
user179
user180
user181
user182
user183
user184
user185
user186
user187
user188
user189
user190
user191
user192
user193
user194
user195
user196
user197
user198
user199
user200
user201
user202
user203
user204
user205
user206
user207
user208
user209
user210
user211
user212
user213
user214
user215
user216
user217
user218
user219
user220
user221
user222
user223
user224
user225
user226
user227
user228
user229
user230
user231
user232
user233
user234
user235
user236
user237
user238
user239
user240
user241
user242
user243
user244
user245
user246
user247
user248
user249
user250
user251
user252
user253
user254
user255
user256
user257
user258
user259
user260
user261
user262
user263
user264
user265
user266
user267
user268
user269
user270
user271
user272
user273
user274
user275
user276
user277

systemdefault
admin1
admin2
admin3

);

#Find Current Users
$login="logg";
$password="pass32";
my $dbh = DBI->connect("DBI:Oracle:icsprod",$login,$password);
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

# Search Zone 2

my $sql = qq{
SELECT  hosts.currentuser, TO_CHAR(hosts.lastlogin, 'HH:MM:SS MM/DD/YYYY'),
        hosts.host_name
FROM    infadmin.inv_hosts hosts
WHERE  (hosts.host_name = '1408bcc204ap1')
OR      (hosts.host_name = '1408mathg135p1')
OR      (hosts.host_name = '1408mathg135p2')
OR      (hosts.host_name = '1408mathg135p3')
OR      (hosts.host_name = '1408mathg135p4')
OR      (hosts.host_name = '1408mathg135m1')
OR      (hosts.host_name = '1408mathb10p1')
OR      (hosts.host_name = '1408mathb10p2')
OR      (hosts.host_name = '1408mathb10p3')
OR      (hosts.host_name = '1408mathb10p4')
OR      (hosts.host_name = '1408mathb10p5')
OR      (hosts.host_name = '1408mathb10p6')
OR      (hosts.host_name = '1408mathb10p7')
OR      (hosts.host_name = '1408mathb10p8')
OR      (hosts.host_name = '1408mathb10p9')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')

ORDER BY hosts.host_name
};
my $sth = $dbh->prepare($sql);
$sth->execute();
my($currentuser, $lastlogin, $host_name);
$sth->bind_columns(undef, \$currentuser, \$lastlogin, \$host_name);
print "Content-type: text/html\n\n";
print "<html>\n";
print "<meta http-equiv=refresh content=300>\n";
print "<meta http-equiv='pragma' content='no-cache'>\n";
print "<style type=\"text/css\">\n";
print "body { font-family: \"Arial\", sans-serif; font-size: small; color: black }\n";
print "</style>\n";
print "<head>\n";
print "<title>\n";
print "Staff Stations\n";
print "</title>\n";
print "</head>\n";
print "<body>\n";
print "<table>\n";
printf("%02d:%02d:%02d", $hour, $min, $sec);
print "<tr><td><u>Zone 2</u></td><td><u>Login</u></td></tr>\n";
while($sth->fetch()) {
        next unless $currentuser~~@las  ;
        $lastlogin=~s/ .*$//;
        $host_name=~s/1408//;
        foreach(@las)   {
                if ($currentuser eq "$_") {
                       $lacolor = "orange";
                        last;
                } else {
                        $lacolor = "black";
                }
        }
        print "<tr>";
        print "<td>$host_name</td>";
        print "<td><font color=\"$lacolor\">$currentuser</font></td><td> </td>";
}
$sth->finish();

print "</table>";
print "</body>\n";
print "</html>\n";

$sth->finish();$sth->finish();

#end code

$
b
->disconnect();
</code>```

The usernames are already stored in a mysql database, I am trying to add lines to connect to it as follows, but I am stuck as to how to continue:

```<code>#Read Employee database

my $dbh = DBI->connect("DBI:mysql:myadmpr01", "user", "pass64");
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

my $sql = qq{
SELECT  user_id,
FROM    lsoemployee_info

};
my $sth = $dbh->prepare($sql);
$sth->execute();
</code>```

I am trying to compare the icsprodagainst the myadmpr01 for usernames so that out hr department can maintain this easily as they update the myadmpr01 database for current/non-current employees. icsprod is updated continuously and simply defines the current user. We would also like to return the user's fullname, rather than continuously look up usernames. Any help is greatly appreciated.

Revised code:

```<code>  #! /usr/bin/perl
$ENV{'ORACLE_HOME'} ="/usr/lib/oracle/11.2/client64";
use DBI;

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

my $dbh = DBI->connect("DBI:mysql:lsopskeys:myadmpr01.itap.purdue.edu", "lsops", "Fl4sh_l1ght")
  or die "Unable to connect: $DBI::errstr\n";

my $sql = qq{
  SELECT  user_id,
  FROM    lsoemployee_data
};

my $sth = $dbh->prepare($sql);
$sth->execute();

my @las = map { $_->[0] } $sth->fetchall_arrayref;

$login="user";
$password="pass";
my $dbh = DBI->connect("DBI:Oracle:icsprod",$login,$password);
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

# Zone 2 ROWS CODE
my $sql = qq{
SELECT  hosts.currentuser, TO_CHAR(hosts.lastlogin, 'HH:MM:SS MM/DD/YYYY'),
        hosts.host_name
FROM    infadmin.inv_hosts hosts
WHERE   (hosts.host_name = '1408stew102p1')
OR      (hosts.host_name = '1408stew102p2')
OR      (hosts.host_name = '1408stew102p3')

OR      (hosts.host_name = '1408stew111p1')
OR      (hosts.host_name = '1408stew111p2')
OR      (hosts.host_name = '1408stew111p3')
OR      (hosts.host_name = '1408stew111p4')
OR      (hosts.host_name = '1408stew111p5')
OR      (hosts.host_name = '1408stew111p6')
OR      (hosts.host_name = '1408stew111p7')
OR      (hosts.host_name = '1408stew111p8')
OR      (hosts.host_name = '1408stew111p9')
OR      (hosts.host_name = '1408stew111p10')
OR      (hosts.host_name = '1408stew111p11')
OR      (hosts.host_name = '1408mathg135p1')
OR      (hosts.host_name = '1408mathb18p5')
OR      (hosts.host_name = '1408mathg135p2')
OR      (hosts.host_name = '1408mathg135p3')
OR      (hosts.host_name = '1408mathg135p4')

OR      (hosts.host_name = '1408heav227m1')
OR      (hosts.host_name = '1408heav227m2')
OR      (hosts.host_name = '1408heav227m3')
OR      (hosts.host_name = '1408mthw116p1')
OR      (hosts.host_name = '1408hamp3144p21')

ORDER BY hosts.host_name
};

my $sth = $dbh->prepare($sql);
$sth->execute();
my($currentuser, $lastlogin, $host_name);
$sth->bind_columns(undef, \$currentuser, \$lastlogin, \$host_name);
print "Content-type: text/html\n\n";
print "<html>\n";
print "<meta http-equiv=refresh content=300>\n";
print "<meta http-equiv='pragma' content='no-cache'>\n";
print "<style type=\"text/css\">\n";
print "body { font-family: \"Arial\", sans-serif; font-size: small; color: black }\n";
print "</style>\n";
print "<head>\n";
print "<title>\n";
print "LA station usage.\n";
print "</title>\n";
print "</head>\n";
print "<body>\n";
print "<table>\n";
printf("%02d:%02d:%02d", $hour, $min, $sec);
print "<tr><td><font color=\"DodgerBlue \"><u>Zone 2 Station</u></td><td><font color=\"DodgerBlue \"><u>Login</u></td></tr>\n";
while($sth->fetch()) {
      #next unless $currentuser ~~ @las;
       $lastlogin=~s/ .*$//;
        $host_name=~s/1408//;
        foreach(@las)   {
                if ($currentuser eq "$_") {
                       $lacolor = "orange";
                        last;
                } else {
                        $lacolor = "black";
                }
        }
        print "<tr>";
        print "<td>$host_name</td>";
        print "<td><font color=\"$lacolor\">$currentuser</font></td><td> </td>";
}
$sth->finish();
print "</table>";
print "</body>\n";
print "</html>\n";
$sth->finish();$sth->finish();

#end code
$
b
->disconnect();
</code>```

答:
Your SQL query is a union of two subqueries, but one subquery has one column in its result and the other has two columns. This is not allowed in a UNION. All subqueries must have the same number of columns, and compatible data types in all columns. This has nothing to do with Perl, it's just a requirement of the SQL language.

In Perl, you should have called the query in a way that allowed you to see the SQL error it caused.

```<code>$sth->execute();
if ($sth->err)
{
  die "ERROR! return code: . $sth->err . " error msg: " . $sth->errstr . "\n";
}
</code>```

DBI also has connection options to make any SQL error cause the calling script to die, or print the error. See http://www.perlhowto.com/dbi_handling_database_errors

```<code>my $dbh = DBI->connect($dsn, $user, $pw, { RaiseError => 1, PrintError => 0 });
</code>```

Body:
Edit: (See Revised Code Near bottom) I have the code working to pull from the 2 databases (I know some cleaning is still needed),
but where I am stuck is, I was prviously able to use:

next unless $currentuser ~~ @las;

but once I linked the mySQL database, it isn't filtering out undefined/unqualified (blank) results. I am not sure how to restructure this function to re-enable the functionality. (I think the way I am approaching the logic may be off). But this is where I am currently confused and need guidance.

I currently use this code to view logged in users to check for employees in our department:

 #! /usr/bin/perl
use strict;
use warnings;

$ENV{'ORACLE_HOME'} ="/usr/lib/oracle/11.2/client64";
use DBI;
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

#current emplyees go here:
my @las = qw(

user12
user13
user14
user15
user16
user17
user18
user19
user20
user21
user22
user23
user24
user25
user26
user27
user28
user29
user30
user31
user32
user33
user34
user35
user36
user37
user38
user39
user40
user41
user42
user43
user44
user45
user46
user47
user48
user49
user50
user51
user52
user53
user54
user55
user56
user57
user58
user59
user60
user61
user62
user63
user64
user65
user66
user67
user68
user69
user70
user71
user72
user73
user74
user75
user76
user77
user78
user79
user80
user81
user82
user83
user84
user85
user86
user87
user88
user89
user90
user91
user92
user93
user94
user95
user96
user97
user98
user99
user100
user101
user102
user103
user104
user105
user106
user107
user108
user109
user110
user111
user112
user113
user114
user115
user116
user117
user118
user119
user120
user121
user122
user123
user124
user125
user126
user127
user128
user129
user130
user131
user132
user133
user134
user135
user136
user137
user138
user139
user140
user141
user142
user143
user144
user145
user146
user147
user148
user149
user150
user151
user152
user153
user154
user155
user156
user157
user158
user159
user160
user161
user162
user163
user164
user165
user166
user167
user168
user169
user170
user171
user172
user173
user174
user175
user176
user177
user178
user179
user180
user181
user182
user183
user184
user185
user186
user187
user188
user189
user190
user191
user192
user193
user194
user195
user196
user197
user198
user199
user200
user201
user202
user203
user204
user205
user206
user207
user208
user209
user210
user211
user212
user213
user214
user215
user216
user217
user218
user219
user220
user221
user222
user223
user224
user225
user226
user227
user228
user229
user230
user231
user232
user233
user234
user235
user236
user237
user238
user239
user240
user241
user242
user243
user244
user245
user246
user247
user248
user249
user250
user251
user252
user253
user254
user255
user256
user257
user258
user259
user260
user261
user262
user263
user264
user265
user266
user267
user268
user269
user270
user271
user272
user273
user274
user275
user276
user277

systemdefault
admin1
admin2
admin3

);

#Find Current Users
$login="logg";
$password="pass32";
my $dbh = DBI->connect("DBI:Oracle:icsprod",$login,$password);
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

# Search Zone 2

my $sql = qq{
SELECT  hosts.currentuser, TO_CHAR(hosts.lastlogin, 'HH:MM:SS MM/DD/YYYY'),
        hosts.host_name
FROM    infadmin.inv_hosts hosts
WHERE  (hosts.host_name = '1408bcc204ap1')
OR      (hosts.host_name = '1408mathg135p1')
OR      (hosts.host_name = '1408mathg135p2')
OR      (hosts.host_name = '1408mathg135p3')
OR      (hosts.host_name = '1408mathg135p4')
OR      (hosts.host_name = '1408mathg135m1')
OR      (hosts.host_name = '1408mathb10p1')
OR      (hosts.host_name = '1408mathb10p2')
OR      (hosts.host_name = '1408mathb10p3')
OR      (hosts.host_name = '1408mathb10p4')
OR      (hosts.host_name = '1408mathb10p5')
OR      (hosts.host_name = '1408mathb10p6')
OR      (hosts.host_name = '1408mathb10p7')
OR      (hosts.host_name = '1408mathb10p8')
OR      (hosts.host_name = '1408mathb10p9')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')

ORDER BY hosts.host_name
};
my $sth = $dbh->prepare($sql);
$sth->execute();
my($currentuser, $lastlogin, $host_name);
$sth->bind_columns(undef, \$currentuser, \$lastlogin, \$host_name);
print "Content-type: text/html\n\n";
print "\n";
print "<meta http-equiv=refresh content=300>\n";
print "<meta http-equiv='pragma' content='no-cache'>\n";
print "\n";
print "\n";
print "<title>\n";
print "Staff Stations\n";
print "</title>\n";
print "\n";
print "\n";
print "
\n";
printf("%02d:%02d:%02d", $hour, $min, $sec);
print "
Zone 2	Login
\n";
while($sth->fetch()) {
        next unless $currentuser~~@las  ;
        $lastlogin=~s/ .*$//;
        $host_name=~s/1408//;
        foreach(@las)   {
                if ($currentuser eq "$_") {
                       $lacolor = "orange";
                        last;
                } else {
                        $lacolor = "black";
                }
        }
        print "
";
        print "$host_name	";
        print "$currentuser	 	";
}
$sth->finish();

print "
";
print "\n";
print "\n";

$sth->finish();$sth->finish();

#end code

$
b
->disconnect();

The usernames are already stored in a mysql database, I am trying to add lines to connect to it as follows, but I am stuck as to how to continue:

#Read Employee database

my $dbh = DBI->connect("DBI:mysql:myadmpr01", "user", "pass64");
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

my $sql = qq{
SELECT  user_id,
FROM    lsoemployee_info

};
my $sth = $dbh->prepare($sql);
$sth->execute();

I am trying to compare the icsprodagainst the myadmpr01 for usernames so that out hr department can maintain this easily as they update the myadmpr01 database for current/non-current employees. icsprod is updated continuously and simply defines the current user. We would also like to return the user's fullname, rather than continuously look up usernames. Any help is greatly appreciated.

Revised code:

  #! /usr/bin/perl
$ENV{'ORACLE_HOME'} ="/usr/lib/oracle/11.2/client64";
use DBI;

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

my $dbh = DBI->connect("DBI:mysql:lsopskeys:myadmpr01.itap.purdue.edu", "lsops", "Fl4sh_l1ght")
  or die "Unable to connect: $DBI::errstr\n";

my $sql = qq{
  SELECT  user_id,
  FROM    lsoemployee_data
};

my $sth = $dbh->prepare($sql);
$sth->execute();

my @las = map { $_->[0] } $sth->fetchall_arrayref;

$login="user";
$password="pass";
my $dbh = DBI->connect("DBI:Oracle:icsprod",$login,$password);
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

# Zone 2 ROWS CODE
my $sql = qq{
SELECT  hosts.currentuser, TO_CHAR(hosts.lastlogin, 'HH:MM:SS MM/DD/YYYY'),
        hosts.host_name
FROM    infadmin.inv_hosts hosts
WHERE   (hosts.host_name = '1408stew102p1')
OR      (hosts.host_name = '1408stew102p2')
OR      (hosts.host_name = '1408stew102p3')

OR      (hosts.host_name = '1408stew111p1')
OR      (hosts.host_name = '1408stew111p2')
OR      (hosts.host_name = '1408stew111p3')
OR      (hosts.host_name = '1408stew111p4')
OR      (hosts.host_name = '1408stew111p5')
OR      (hosts.host_name = '1408stew111p6')
OR      (hosts.host_name = '1408stew111p7')
OR      (hosts.host_name = '1408stew111p8')
OR      (hosts.host_name = '1408stew111p9')
OR      (hosts.host_name = '1408stew111p10')
OR      (hosts.host_name = '1408stew111p11')
OR      (hosts.host_name = '1408mathg135p1')
OR      (hosts.host_name = '1408mathb18p5')
OR      (hosts.host_name = '1408mathg135p2')
OR      (hosts.host_name = '1408mathg135p3')
OR      (hosts.host_name = '1408mathg135p4')

OR      (hosts.host_name = '1408heav227m1')
OR      (hosts.host_name = '1408heav227m2')
OR      (hosts.host_name = '1408heav227m3')
OR      (hosts.host_name = '1408mthw116p1')
OR      (hosts.host_name = '1408hamp3144p21')

ORDER BY hosts.host_name
};

my $sth = $dbh->prepare($sql);
$sth->execute();
my($currentuser, $lastlogin, $host_name);
$sth->bind_columns(undef, \$currentuser, \$lastlogin, \$host_name);
print "Content-type: text/html\n\n";
print "\n";
print "<meta http-equiv=refresh content=300>\n";
print "<meta http-equiv='pragma' content='no-cache'>\n";
print "\n";
print "\n";
print "<title>\n";
print "LA station usage.\n";
print "</title>\n";
print "\n";
print "\n";
print "
\n";
printf("%02d:%02d:%02d", $hour, $min, $sec);
print "
Zone 2 Station	Login
\n";
while($sth->fetch()) {
      #next unless $currentuser ~~ @las;
       $lastlogin=~s/ .*$//;
        $host_name=~s/1408//;
        foreach(@las)   {
                if ($currentuser eq "$_") {
                       $lacolor = "orange";
                        last;
                } else {
                        $lacolor = "black";
                }
        }
        print "
";
        print "$host_name	";
        print "$currentuser	 	";
}
$sth->finish();
print "
";
print "\n";
print "\n";
$sth->finish();$sth->finish();

#end code
$
b
->disconnect();

Body:
Your SQL query is a union of two subqueries, but one subquery has one column in its result and the other has two columns. This is not allowed in a UNION. All subqueries must have the same number of columns, and compatible data types in all columns. This has nothing to do with Perl, it's just a requirement of the SQL language.

In Perl, you should have called the query in a way that allowed you to see the SQL error it caused.

$sth->execute();
if ($sth->err)
{
  die "ERROR! return code: . $sth->err . " error msg: " . $sth->errstr . "\n";
}

DBI also has connection options to make any SQL error cause the calling script to die, or print the error. See http://www.perlhowto.com/dbi_handling_database_errors

my $dbh = DBI->connect($dsn, $user, $pw, { RaiseError => 1, PrintError => 0 });


问:
How would I add new data via a REST service opposed to RPC style service?
I'm still learning about REST and, in my test, came up with this scenario I don't know how to deal with.

I have an existing sample WCF service which uses Linq-to-Sql.  Its a tremendously simple database with a single table called "Tasks" which has four fields: Id, Description, IsCompleted, and EnteredDate. (I mentioned this because I have no data contracts defined in the service itself, it all comes from the Context created by Linq.)

Getting data was trivial to convert to REST... as was deleting data.  However, inserting new records doesn't seem as easy.

My RPC-style contract operation looks like this:

```<code>    [OperationContract]
    void AddTask(string description);
</code>```

The Id, IsCompleted, and EnteredDate are not needed as the service implementation looks like this:

```<code>    public void AddTask(string description)
    {
        TaskListLinqDataContext db = new TaskListLinqDataContext();
        Task task = new Task()
           { Description = description, IsCompleted = false,
             EntryDate = DateTime.Now };

        db.Tasks.InsertOnSubmit(task);
        db.SubmitChanges();
    }
</code>```

The Id is an Identity and therefore handled by the database.

My first thought was to decorate the Operation contract like this:

```<code>    [WebInvoke(Method="PUT", UriTemplate="tasks/{description}")]
    [OperationContract]
    void AddTask(string description);
</code>```

But I don't really know how to get this to work.  When I try using Fiddler to add this it returns a result of 411 (Length Required).

What would be the proper way to do this?  Will I have to re-write the implementation to accept a whole XML document representing the new record?

答: I think this pretty much describes how to add an item to a container in a restful way.</p>

OwnerDisplayName: Sailing Judo

Body:
I'm still learning about REST and, in my test, came up with this scenario I don't know how to deal with.

I have an existing sample WCF service which uses Linq-to-Sql.  Its a tremendously simple database with a single table called "Tasks" which has four fields: Id, Description, IsCompleted, and EnteredDate. (I mentioned this because I have no data contracts defined in the service itself, it all comes from the Context created by Linq.)

Getting data was trivial to convert to REST... as was deleting data.  However, inserting new records doesn't seem as easy.

My RPC-style contract operation looks like this:

    [OperationContract]
    void AddTask(string description);

The Id, IsCompleted, and EnteredDate are not needed as the service implementation looks like this:

    public void AddTask(string description)
    {
        TaskListLinqDataContext db = new TaskListLinqDataContext();
        Task task = new Task()
           { Description = description, IsCompleted = false,
             EntryDate = DateTime.Now };

        db.Tasks.InsertOnSubmit(task);
        db.SubmitChanges();
    }

The Id is an Identity and therefore handled by the database.

My first thought was to decorate the Operation contract like this:

    [WebInvoke(Method="PUT", UriTemplate="tasks/{description}")]
    [OperationContract]
    void AddTask(string description);

But I don't really know how to get this to work.  When I try using Fiddler to add this it returns a result of 411 (Length Required).

What would be the proper way to do this?  Will I have to re-write the implementation to accept a whole XML document representing the new record?

LastEditorDisplayName: Sailing Judo


问:
How can I remove "holes" in indexes of an array?
Excuse me, but I don't know the proper way for spelling this. I hope the example will explain my problem:

```<code>$ array[1]=john
$ array[2]=smith
$ array[4]=jane
$ array[5]=doe
$ echo ${array[@]}
john smith jane doe
$ echo ${array[3]}

$
</code>```

I would like some method to remove the "hole" at position 3 in array, so that:

Value jane would be moved to position 3.

Value doe would be moved to position 4.

Value at position 5 would become empty (unset).

Array length (4 in this example) would not become changed.

Is it needed to program any loops(s) through the array to obtain this, or there is some simpler method?

Further data:

Assuming Bash as shell.

答:
Just use the elements to create a new array:

```<code>$ array=([1]=john smith [4]=jane doe)
$ declare -p array
declare -a array='([1]="john" [2]="smith" [4]="jane" [5]="doe")'
$ array=("${array[@]}")
$ declare -p array
declare -a array='([0]="john" [1]="smith" [2]="jane" [3]="doe")'
</code>```

Note that this counts from 0, not 1. If you really need a 1-based array, add a dummy element to the new array then delete it.

```<code>$ array=(foo "${array[@]}")
$ unset 'array[0]'
$ declare -p array
declare -a array='([1]="john" [2]="smith" [3]="jane" [4]="doe")'
</code>```

Body:
Excuse me, but I don't know the proper way for spelling this. I hope the example will explain my problem:

$ array[1]=john
$ array[2]=smith
$ array[4]=jane
$ array[5]=doe
$ echo ${array[@]}
john smith jane doe
$ echo ${array[3]}

$

I would like some method to remove the "hole" at position 3 in array, so that:

Value jane would be moved to position 3.

Value doe would be moved to position 4.

Value at position 5 would become empty (unset).

Array length (4 in this example) would not become changed.

Is it needed to program any loops(s) through the array to obtain this, or there is some simpler method?

Further data:

Assuming Bash as shell.

Body:
Just use the elements to create a new array:

$ array=([1]=john smith [4]=jane doe)
$ declare -p array
declare -a array='([1]="john" [2]="smith" [4]="jane" [5]="doe")'
$ array=("${array[@]}")
$ declare -p array
declare -a array='([0]="john" [1]="smith" [2]="jane" [3]="doe")'

Note that this counts from 0, not 1. If you really need a 1-based array, add a dummy element to the new array then delete it.

$ array=(foo "${array[@]}")
$ unset 'array[0]'
$ declare -p array
declare -a array='([1]="john" [2]="smith" [3]="jane" [4]="doe")'


问:
How can I find out if getDate() is between 2 time(7) timestamps?
I have an application that sends alerts if the temperature exceeds limits, but I only want to send alerts if it happens at certain times of the day.  I'm using time(7) datatype to store those times.  I need it to be flexible enough to cross midnight, so I could have the following times:

```<code>time_on   time_off
08:00:00  17:00:00
00:00:00  12:00:00
21:00:00  09:00:00
</code>```

How can I figure out if CONVERT(time(7), getdate()) is between any of those combinations?

答:
You can add TIME to a datetime value.  Here we truncate the current GetDate() to midnight via Declare @D datetime = convert(date,GetDate())

```<code>Declare @YourTable table (time_on time,time_off time)
Insert Into @YourTable values
('08:00:00','17:00:00'),
('00:00:00','12:00:00'),
('21:00:00','09:00:00'),
('00:00:00','12:00:00'),   -- Added for illustration
('12:00:00','00:00:00')    -- Added for illustration

Declare @D datetime = convert(date,GetDate())

Select *
 From  @YourTable
 Where GetDate() >= @D+convert(datetime,time_on)
   and GetDate() <= @D+convert(datetime,time_off)+case when time_off<=time_on then 1 else 0 end
</code>```

Returns

```<code>time_on             time_off
12:00:00.0000000    00:00:00.0000000
</code>```

My current Datetime was 2017-04-02 18:33:53.803 which did not satisfy any of the original criteria, so I added two records for illustration

Or, if you don't want to declare @D

```<code>Select *
 From  @YourTable
 Where GetDate() >= convert(datetime,convert(date,GetDate()))+convert(datetime,time_on)
   and GetDate() <= convert(datetime,convert(date,GetDate()))+convert(datetime,time_off)+case when time_off<=time_on then 1 else 0 end
</code>```

Body:
I have an application that sends alerts if the temperature exceeds limits, but I only want to send alerts if it happens at certain times of the day.  I'm using time(7) datatype to store those times.  I need it to be flexible enough to cross midnight, so I could have the following times:

time_on   time_off
08:00:00  17:00:00
00:00:00  12:00:00
21:00:00  09:00:00

How can I figure out if CONVERT(time(7), getdate()) is between any of those combinations?

Body:
You can add TIME to a datetime value.  Here we truncate the current GetDate() to midnight via Declare @D datetime = convert(date,GetDate())

Declare @YourTable table (time_on time,time_off time)
Insert Into @YourTable values
('08:00:00','17:00:00'),
('00:00:00','12:00:00'),
('21:00:00','09:00:00'),
('00:00:00','12:00:00'),   -- Added for illustration
('12:00:00','00:00:00')    -- Added for illustration

Declare @D datetime = convert(date,GetDate())

Select *
 From  @YourTable
 Where GetDate() >= @D+convert(datetime,time_on)
   and GetDate() <= @D+convert(datetime,time_off)+case when time_off<=time_on then 1 else 0 end

Returns

time_on             time_off
12:00:00.0000000    00:00:00.0000000

My current Datetime was 2017-04-02 18:33:53.803 which did not satisfy any of the original criteria, so I added two records for illustration

Or, if you don't want to declare @D

Select *
 From  @YourTable
 Where GetDate() >= convert(datetime,convert(date,GetDate()))+convert(datetime,time_on)
   and GetDate() <= convert(datetime,convert(date,GetDate()))+convert(datetime,time_off)+case when time_off<=time_on then 1 else 0 end


问:
JAVAFX event triggered when selecting a check box
My JavaFx FXML application has an issue.

When I select a checkbox on a form, I want to execute a method based on the checkbox that was clicked. Is there any way that I can pass the name of the checkbox through to the method so I can perform some conditional work on it?

I have two checkboxes and only one can be selected. When I click on one, the other should be de-selected and vice versa. Obviously the code below will not work so I am looking to pass the name of the object that was clicked.

Any help would be appreciated,
many thanks.

```<code>@FXML private void updateRcs(){

    if (chkRcsuri.isSelected()){
        chkRcsuri2.setSelected(false);
    }

    if (chkRcsuri2.isSelected()){
        chkRcsuri.setSelected(false);
    }

}
</code>```

答:
This is my solution. But be sure about the a variable to be appropriate for you

//First in FXML file
<CheckBox fx:id="chkbxAuto" mnemonicParsing="false" onAction="#autoConfig" text="Auto" />

// in controler
public class FXMLController implements Initializable {
    private static int a = 0;
    //references to lables
    ....
    @FXML
    private Label lblStateValue;
    @FXML
    private Group grpSetting; // a group of elements which I want to be disabled and enabled
    ...
    @FXML
    private void autoConfig(ActionEvent event) {
            System.out.println("Configing automatically");
             a++;
             if(a%2==1){
                 lblStateValue.setText("Auto configuration enabled"); // it change a lable to show the state
                 grpSetting.setDisable(true); // it disable a group of elements
             }
            else{
                 lblStateValue.setText("Auto configuration disabled");
                 grpSetting.setDisable(false);
             }
            a%=10;

        }
    ...
```

Body:
My JavaFx FXML application has an issue.

When I select a checkbox on a form, I want to execute a method based on the checkbox that was clicked. Is there any way that I can pass the name of the checkbox through to the method so I can perform some conditional work on it?

I have two checkboxes and only one can be selected. When I click on one, the other should be de-selected and vice versa. Obviously the code below will not work so I am looking to pass the name of the object that was clicked.

Any help would be appreciated,
many thanks.

@FXML private void updateRcs(){

    if (chkRcsuri.isSelected()){
        chkRcsuri2.setSelected(false);
    }

    if (chkRcsuri2.isSelected()){
        chkRcsuri.setSelected(false);
    }

}


问:
GDB core dump see content of container
I am poking around in a core dump ( for the first time ) and I am interested in the elements of a map m_my_map
I can see the map with info args, but it also gives the following output

```<code>info args
m_my_map = <error reading variable m_my_map (Unhandled dwarf expression opcode 0xf3)
</code>```

and when I try to see its content with

```<code>print m_my_map
Unhandled dwarf expression opcode 0xf3
</code>```

Is there a way to loop through the map and print the pairs?

答:
DWARF opcode 0xf3 comes from the "user" area of the opcode range; but it is probably DW_OP_GNU_entry_value, which is a GNU extension in DWARF 4 (now standardized in DWARF 5, but with a different value).

What this means for you is that you are most likely using a GDB that was released before the version of GCC that you are using.  The solution to your problem, then, is to upgrade GDB.  After you do this, printing the map will most likely work.

Title: GDB core dump see content of container

Body:
I am poking around in a core dump ( for the first time ) and I am interested in the elements of a map m_my_map
I can see the map with info args, but it also gives the following output

info args
m_my_map = <error reading variable m_my_map (Unhandled dwarf expression opcode 0xf3)

and when I try to see its content with

print m_my_map
Unhandled dwarf expression opcode 0xf3

Is there a way to loop through the map and print the pairs?


问:
Add method for custom LinkedList class
I have been working on this add method for a custom linkedlist lab I am working on. I cannot figure out how to shift values over by one index, once I insert the new node. Here is my source code.</p>

```<code>public void add(int index, Object element) throws IndexOutOfBoundsException {
    if(index > size() || index < 0) {
        throw new IndexOutOfBoundsException();
    }

    ListNode newNode = new ListNode(element, null);

    if(head == null) {
        head = newNode;
        return;
    }

    ListNode nextNode = head.nextNode;
    ListNode currNode = head;

    int i = 0;
    while(currNode!= null) {

        if(index == i) {
            break;
        }

        currNode = nextNode;
        //Breaks down here with null pointer exception
        nextNode = nextNode.nextNode;

    }

    currNode = newNode;
    currNode.nextNode = nextNode;
}
</code>```

答:
It is throwing null pointer as when you are iterating last node, next node points to null. Check for next node point to null also if you have to add new node in last.

Also in your code you are not increasing the value of i always it is iterating the whole list.

Title: Add method for custom LinkedList class

Body:
I have been working on this add method for a custom linkedlist lab I am working on. I cannot figure out how to shift values over by one index, once I insert the new node. Here is my source code.

public void add(int index, Object element) throws IndexOutOfBoundsException {
    if(index > size() || index < 0) {
        throw new IndexOutOfBoundsException();
    }

    ListNode newNode = new ListNode(element, null);

    if(head == null) {
        head = newNode;
        return;
    }

    ListNode nextNode = head.nextNode;
    ListNode currNode = head;

    int i = 0;
    while(currNode!= null) {

        if(index == i) {
            break;
        }

        currNode = nextNode;
        //Breaks down here with null pointer exception
        nextNode = nextNode.nextNode;

    }

    currNode = newNode;
    currNode.nextNode = nextNode;
}


问:
Getting values of a variable filtered by the missing values of another variable in a dataset
I have a data set with age and income variables. The income column has some missing values. I want to write a code where I can get all the values of age variable for all missing values of income variable only i.e. the result of my code would display the ages where income value is NA. I was trying to do this using dplyr function but I am stuck. I know this is simple but I have been unable to do this. Could anyone suggest the code for this. Thanks</p>

Body:
Some test data:

data<-data.frame(Age   = c(23,28,27,31,42,26,48,23,32,31),
                 income = c(20000, NA, 30000, 25000, NA, NA, 35000, NA, 40000, 250000))
> data
   Age income
1   23  20000
2   28     NA
3   27  30000
4   31  25000
5   42     NA
6   26     NA
7   48  35000
8   23     NA
9   32  40000
10  31 250000

Explicitly using the dplyr package:

require(dplyr)
data %>% filter(is.na(income))

  Age income
1  28     NA
2  42     NA
3  26     NA
4  23     NA


答: I don't really know what you are trying to achieve here, and I agree with @Pritam Banerjee's comment. But an obvious problem in your code is that you are never incrementing i, so you'll never break out of your while loop and at some point you are going to hit the end of your list and nextNode.nextNode is going to be null, hence your exception. (Also note that nextNode.nextNode will be null before currNode is.)</p>

Title: Add method for custom LinkedList class


问:
How to concat text in Android TextView?
I want to concat two text and display with single TextView in Android. I have tried following type. It displays in logcat only, but it isn't concat in XML textview.

Here is my code:

```<code><TextView
              android:id="@+id/heizgriffe"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Heizgriffe"
              android:textColor="#000"
              android:textSize="12dp"
              android:textStyle="bold"

              android:layout_below="@+id/txt"/>
</code>```

in Java class:

```<code>txtConcat = (TextView)findViewById(R.id.txt);
String hub="Hubraum:";
            String str= ItemList.getTxt(); // fetting from webservice
            txtConcat .setText(hub + str );
</code>```

Anything wrong here?

答:
txtConcat = (TextView)findViewById(R.id.txt);

Shouldn't it be:
txtConcat = (TextView)findViewById(R.id.heizgriffe);

ContentLicense: CC BY-SA 4.0

Title: How to concat text in Android TextView?

Body:
I want to concat two text and display with single TextView in Android. I have tried following type. It displays in logcat only, but it isn't concat in XML textview.

Here is my code:

<TextView
              android:id="@+id/heizgriffe"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Heizgriffe"
              android:textColor="#000"
              android:textSize="12dp"
              android:textStyle="bold"

              android:layout_below="@+id/txt"/>

in Java class:

txtConcat = (TextView)findViewById(R.id.txt);
String hub="Hubraum:";
            String str= ItemList.getTxt(); // fetting from webservice
            txtConcat .setText(hub + str );

Anything wrong here?


问:
Adding hours to a Javascript date in a loop
I'm getting some strange results from adding hours to a date.  I'm basically adding 0, 6, 12, 18, 24, 30, etc hours to a Javascript date.  I came across some of the recommendations online (like this: Adding hours to Javascript Date object?), but when in a loop it was skipping ahead many hours/months.  It seemed to be keeping the new version of the date and just adding hours to it...when I really just want to add the hours to the original date.

So, here's the basics of what I have.

```<code>for (var i = 1; i < 4; i++) {

hour_date.setHours(hour_date.getHours() + hour);

output.push(hour_date...)
}
//where hour is 6, 12, 18, 24, etc in a loop
//and where hour_date is defined earlier and is
//Sun Apr 02 2017 12:00:00 GMT-0700 (Pacific Daylight Time)
</code>```

So I'm trying to figure out how to simply add 6 hours to an initial date variable...so I can push those values out to an array.  I understand the push part...but I'm just trying to add the hours correctly within the loop.

Thanks very much for any help!

答:
It may be simpler to use the date's raw value and add to it in milliseconds.

Example:

```<code>var date = Date.now()
console.log(new Date(date))
var date2 = new Date(date+1000*60*60*6) // Add 6 hours.
console.log(date2)
var date3 = new Date(date+1000*60*60*3) // Add 3 hours.
console.log(date3)
</code>```

In a loop you'll have to make sure you create  new variables from the original variable, not modifying the original. In your case this is easy if you simply create new Date objects and insert them into an array. Use .valueOf() to access the underlying number value of a date object.

```<code>var date = new Date();
dates = [date];
for(var i = 6; i <= 30; i += 6) {
    dates.push(new Date(date.valueOf() + i * 1000 * 60 * 60));
}
console.log(JSON.stringify(dates, null, 4))

// [
//     "2017-04-03T00:57:52.420Z",
//     "2017-04-03T06:57:52.420Z",
//     "2017-04-03T12:57:52.420Z",
//     "2017-04-03T18:57:52.420Z",
//     "2017-04-04T00:57:52.420Z",
//     "2017-04-04T06:57:52.420Z"
// ]
</code>```

Body:
I'm getting some strange results from adding hours to a date.  I'm basically adding 0, 6, 12, 18, 24, 30, etc hours to a Javascript date.  I came across some of the recommendations online (like this: Adding hours to Javascript Date object?), but when in a loop it was skipping ahead many hours/months.  It seemed to be keeping the new version of the date and just adding hours to it...when I really just want to add the hours to the original date.

So, here's the basics of what I have.

for (var i = 1; i < 4; i++) {

hour_date.setHours(hour_date.getHours() + hour);

output.push(hour_date...)
}
//where hour is 6, 12, 18, 24, etc in a loop
//and where hour_date is defined earlier and is
//Sun Apr 02 2017 12:00:00 GMT-0700 (Pacific Daylight Time)

So I'm trying to figure out how to simply add 6 hours to an initial date variable...so I can push those values out to an array.  I understand the push part...but I'm just trying to add the hours correctly within the loop.

Thanks very much for any help!

Body:
It may be simpler to use the date's raw value and add to it in milliseconds.

Example:

var date = Date.now()
console.log(new Date(date))
var date2 = new Date(date+1000*60*60*6) // Add 6 hours.
console.log(date2)
var date3 = new Date(date+1000*60*60*3) // Add 3 hours.
console.log(date3)

In a loop you'll have to make sure you create  new variables from the original variable, not modifying the original. In your case this is easy if you simply create new Date objects and insert them into an array. Use .valueOf() to access the underlying number value of a date object.

var date = new Date();
dates = [date];
for(var i = 6; i <= 30; i += 6) {
    dates.push(new Date(date.valueOf() + i * 1000 * 60 * 60));
}
console.log(JSON.stringify(dates, null, 4))

// [
//     "2017-04-03T00:57:52.420Z",
//     "2017-04-03T06:57:52.420Z",
//     "2017-04-03T12:57:52.420Z",
//     "2017-04-03T18:57:52.420Z",
//     "2017-04-04T00:57:52.420Z",
//     "2017-04-04T06:57:52.420Z"
// ]


问:
How to add composite primary keys in db using Rails?
I'm using Rails 5.0 with Postgresql 9.5

I'm in need to add composite primary keys to my model 'User_achievement' (to link 'User' and 'Achievement' models as you may guess).

So I tried using the "composite_primary_keys" gem. I followed all the instructions, nevertheless, the result wasn't like I expected. Seems like it doesn't create pkey in the 'user_achievement' table according to the info by psql tool:

```<code>test1_development=> \d user_achievements

Table "public.user_achievements"
Column | Type | Modifiers

----------------+---------+-----------

user_id | integer |
achievement_id | integer |
uach_date | date |

Indexes:

"index_user_achievements_on_achievement_id" btree (achievement_id)

"index_user_achievements_on_user_id" btree (user_id)

Foreign-key constraints:

"fk_rails_4efde02858" FOREIGN KEY (user_id) REFERENCES users(id)

"fk_rails_c44f5b3b25" FOREIGN KEY (achievement_id) REFERENCES achievements(id)
</code>```

Here's models and migrations' code:

```<code>class CreateUsers < ActiveRecord::Migration[5.0]
 def change
  create_table :users do |t|
  t.string :name
  end
 end
end

class CreateAchievements < ActiveRecord::Migration[5.0]
 def change
  create_table :achievements do |t|
  t.string :ach_name
  t.text :ach_desc
  end
 end
end

class CreateUserAchievements < ActiveRecord::Migration[5.0]
  def change
   create_table :user_achievements, id: false do |t|
   t.belongs_to :user, :foreign_key => [:id]
   t.belongs_to :achievement, :foreign_key => [:id]
   t.date :uach_date
   end
  end
 end

class Achievement < ApplicationRecord
  has_many :user_achievements
end

class User < ApplicationRecord
  has_many :user_achievements
end

class UserAchievement < ApplicationRecord
  self.primary_keys = :user_id, :achievement_id
  belongs_to :user, :foreign_key => [:id]
  belongs_to :achievement, :foreign_key => [:id]
end
</code>```

So should the gem alter db tables? or it influences just the rails' environment?
Is there the only way to alter db - to add execute line in migration?

答:
Since nobody have posted anything useful, I'll share what I've got by now.

Gem 'composite_primary_key' (CPK) doesn't change anything in database, so if you still want it - you should do it manually (add the command to migration).

The only thing CPK does is extending Rails with 'understanding' what a composite primary key is, since it originally doesn't have and shows an error.

Anyway I found it is very sohpisticated and problematic to use composite primary keys in Rails apps because it makes using other gems quite nerveous (with every new gem installation you keep in mind that somewhere something can go wrong) as well as changing your code with cpks in future. Also it makes your code harder to understand for other people who are not familliar with this feature. So you should always specify that you have used CPK.

A very good alternative is adding an index with 'unique' option which technically means quite the same but doesn't require additional headache.

So use it only if you really have to and there's no other less sophisticated solution!

Body:
I'm using Rails 5.0 with Postgresql 9.5

I'm in need to add composite primary keys to my model 'User_achievement' (to link 'User' and 'Achievement' models as you may guess).

So I tried using the "composite_primary_keys" gem. I followed all the instructions, nevertheless, the result wasn't like I expected. Seems like it doesn't create pkey in the 'user_achievement' table according to the info by psql tool:

test1_development=> \d user_achievements

Table "public.user_achievements"
Column | Type | Modifiers

----------------+---------+-----------

user_id | integer |
achievement_id | integer |
uach_date | date |

Indexes:

"index_user_achievements_on_achievement_id" btree (achievement_id)

"index_user_achievements_on_user_id" btree (user_id)

Foreign-key constraints:

"fk_rails_4efde02858" FOREIGN KEY (user_id) REFERENCES users(id)

"fk_rails_c44f5b3b25" FOREIGN KEY (achievement_id) REFERENCES achievements(id)

Here's models and migrations' code:

class CreateUsers < ActiveRecord::Migration[5.0]
 def change
  create_table :users do |t|
  t.string :name
  end
 end
end

class CreateAchievements < ActiveRecord::Migration[5.0]
 def change
  create_table :achievements do |t|
  t.string :ach_name
  t.text :ach_desc
  end
 end
end

class CreateUserAchievements < ActiveRecord::Migration[5.0]
  def change
   create_table :user_achievements, id: false do |t|
   t.belongs_to :user, :foreign_key => [:id]
   t.belongs_to :achievement, :foreign_key => [:id]
   t.date :uach_date
   end
  end
 end

class Achievement < ApplicationRecord
  has_many :user_achievements
end

class User < ApplicationRecord
  has_many :user_achievements
end

class UserAchievement < ApplicationRecord
  self.primary_keys = :user_id, :achievement_id
  belongs_to :user, :foreign_key => [:id]
  belongs_to :achievement, :foreign_key => [:id]
end

So should the gem alter db tables? or it influences just the rails' environment?
Is there the only way to alter db - to add execute line in migration?


问:
MSG_READALL is to recv() as ?? is to send()
From the recv(2) man page:

MSG_WAITALL

This flag requests that the operation block until the full request is satisfied. However, the call may still return less data than requested if a signal is caught, an error or disconnect occurs, or the next data to be received is of a different type than that returned.

It doesn't look like there's an equivalent flag for send(2), which strikes me as strange.  Maybe send()s are guaranteed to always accept the whole buffer, but I don't see that written anywhere (and anyway, that seems unlikely to me).

Is there a way to tell send() to wait until it's sent the whole buffer before returning, equivalently to recv()'s MSG_WAITALL?

Edit: I understand that send() just copies data into a buffer in the operating system and that I can't force send() to put data onto the wire.  My question is: Can I force send() to block until all the data I gave it has been copied into the OS's buffer?

答:
You can't. send just offloads the buffer to the kernel, then returns.

To quote from the Unix standard:

The send() function shall initiate transmission of a message from the specified socket to its peer (...)
  Successful completion of a call to send() does not guarantee delivery of the message.

Note the word "initiate". It doesn't actually send anything, rather tells the OS to send the message when it's ready for it (when its buffers are full or after some time has passed).


问:
How RCS can be used with botframework
We do some bot development for channels like Skype, Messenger etc.
The framework we use is https://dev.botframework.com/.

We were trying to figure out how RCS can be used as channel for bots?

Any suggestions will be appreciated...

答:
I haven't personally worked with RCS, but you should be able to write a layer into your application between RCS and a bot exposed via the Direct Line channel, using the Direct Line API: https://docs.botframework.com/en-us/restapi/directline3/#navtitle  RCS wouldn't be a full fledged channel, perse.  But, the experience could be the same to the end user as if it were.

Please refer to this FAQ related to your question: https://docs.botframework.com/en-us/faq#i-have-a-communication-channel-id-like-to-be-configurable-with-bot-framework-can-i-work-with-microsoft-to-do-that

I have a communication channel I’d like to be configurable with Bot Framework. Can I work with Microsoft to do that?

We have not provided a general mechanism for developers to add new
  channels to Bot Framework, but you can connect your bot to your app
  via the Direct Line API. If you are a developer of a communication
  channel and would like to work with us to enable your channel in the
  Bot Framework we’d love to hear from you.

Title: How RCS can be used with botframework


问:
get result of AsyncTask in other Method
I am trying to get the response of a servlet as text, to parse this text and extract the coordinates for showing markers on google maps. My problem is that I don't know how to call the result from onPostExecute method in the onMapReady method. Like I'm calling in my code, the input String is obviously empty. </p>

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap map;
private static final String LOG_TAG = "ExampleApp";
TextView tvIsConnected;
TextView tvResult;
TextView textView2;
private static final String SERVICE_URL = "http://192.168.178.42:8080/TutorialApp/User/GetAll";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
    tvResult = (TextView) findViewById(R.id.tvResult);
    textView2 = (TextView) findViewById(R.id.textView2);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    if (checkNetworkConnection())
        // perform HTTP GET request
        new HTTPAsyncTask().execute("http://192.168.178.42:8080/TutorialApp/User/GetAll");
}

public boolean checkNetworkConnection() {
    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    boolean isConnected = false;
    if (networkInfo != null && (isConnected = networkInfo.isConnected())) {
        // show "Connected" & type of network "WIFI or MOBILE"
        tvIsConnected.setText("Connected " + networkInfo.getTypeName());
        // change background color to red
        tvIsConnected.setBackgroundColor(0xFF7CCC26);

    } else {
        // show "Not Connected"
        tvIsConnected.setText("Not Connected");
        // change background color to green
        tvIsConnected.setBackgroundColor(0xFFFF0000);
    }

    return isConnected;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while ((line = bufferedReader.readLine()) != null)
        result += line + "\n";

    inputStream.close();
    return result;

}
private String HttpGet(String myUrl) throws IOException {
    InputStream inputStream = null;
    String result = "";

    URL url = new URL(myUrl);

    // create HttpURLConnection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // make GET request to the given URL
    conn.connect();

    // receive response as inputStream
    inputStream = conn.getInputStream();

    // convert inputstream to string
    if (inputStream != null)
        result = convertInputStreamToString(inputStream);
    else
        result = "Did not work!";

    return result;
}

private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            return HttpGet(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    //onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        tvResult.setText(result);
    }

}
@Override
public void onMapReady(GoogleMap googleMap) {

    String input = tvResult.getText().toString();

    String[] lines = input.split( "\n" );
    List<Pair<Double, Double>> list = new ArrayList<>();
    String ss="i";
    for( int i =1; i < lines.length-1; i++ ) {
        int firstcomma = lines[i].indexOf(",");
        int secondcomma = lines[i].indexOf(",", firstcomma + 1);
        int thirdcomma = lines[i].indexOf(",", secondcomma + 1);
        Double lat = Double.parseDouble(lines[i].substring(secondcomma + 1, thirdcomma));
        Double longitude = Double.parseDouble(lines[i].substring(thirdcomma + 1, lines.length));
        list.add(new Pair(lat,longitude));
    }
    for(int j=1; j<list.size();j++) {

        map = googleMap;
        // Add a marker in Sydney and move the camera
        //LatLng sydney = new LatLng(-34, 151);
        LatLng sydney = new LatLng(list.get(j).first, list.get(j).second);
        map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}
</code>```

<p>}</p>

答: The reason you can't call the result of onPostExecute() in onMapReady() is because they are both running in the background. The only thing that you can really do here is either call getMapAsync() from your onPostExecute(), which will ensure that your onPostExecute() has completed; or, move the functionality of the onMapReady() into the onPostExecute(). You basically have 2 asyncTasks running, so you either need to chain them (which is kind of hacky) or move the logic from onMapReady() to  onPostExecute().

Title: get result of AsyncTask in other Method

Body:
I am trying to get the response of a servlet as text, to parse this text and extract the coordinates for showing markers on google maps. My problem is that I don't know how to call the result from onPostExecute method in the onMapReady method. Like I'm calling in my code, the input String is obviously empty.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap map;
private static final String LOG_TAG = "ExampleApp";
TextView tvIsConnected;
TextView tvResult;
TextView textView2;
private static final String SERVICE_URL = "http://192.168.178.42:8080/TutorialApp/User/GetAll";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
    tvResult = (TextView) findViewById(R.id.tvResult);
    textView2 = (TextView) findViewById(R.id.textView2);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    if (checkNetworkConnection())
        // perform HTTP GET request
        new HTTPAsyncTask().execute("http://192.168.178.42:8080/TutorialApp/User/GetAll");
}

public boolean checkNetworkConnection() {
    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    boolean isConnected = false;
    if (networkInfo != null && (isConnected = networkInfo.isConnected())) {
        // show "Connected" & type of network "WIFI or MOBILE"
        tvIsConnected.setText("Connected " + networkInfo.getTypeName());
        // change background color to red
        tvIsConnected.setBackgroundColor(0xFF7CCC26);

    } else {
        // show "Not Connected"
        tvIsConnected.setText("Not Connected");
        // change background color to green
        tvIsConnected.setBackgroundColor(0xFFFF0000);
    }

    return isConnected;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while ((line = bufferedReader.readLine()) != null)
        result += line + "\n";

    inputStream.close();
    return result;

}
private String HttpGet(String myUrl) throws IOException {
    InputStream inputStream = null;
    String result = "";

    URL url = new URL(myUrl);

    // create HttpURLConnection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // make GET request to the given URL
    conn.connect();

    // receive response as inputStream
    inputStream = conn.getInputStream();

    // convert inputstream to string
    if (inputStream != null)
        result = convertInputStreamToString(inputStream);
    else
        result = "Did not work!";

    return result;
}

private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            return HttpGet(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    //onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        tvResult.setText(result);
    }

}
@Override
public void onMapReady(GoogleMap googleMap) {

    String input = tvResult.getText().toString();

    String[] lines = input.split( "\n" );
    List<Pair<Double, Double>> list = new ArrayList<>();
    String ss="i";
    for( int i =1; i < lines.length-1; i++ ) {
        int firstcomma = lines[i].indexOf(",");
        int secondcomma = lines[i].indexOf(",", firstcomma + 1);
        int thirdcomma = lines[i].indexOf(",", secondcomma + 1);
        Double lat = Double.parseDouble(lines[i].substring(secondcomma + 1, thirdcomma));
        Double longitude = Double.parseDouble(lines[i].substring(thirdcomma + 1, lines.length));
        list.add(new Pair(lat,longitude));
    }
    for(int j=1; j<list.size();j++) {

        map = googleMap;
        // Add a marker in Sydney and move the camera
        //LatLng sydney = new LatLng(-34, 151);
        LatLng sydney = new LatLng(list.get(j).first, list.get(j).second);
        map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

}


问:
sublime text not opening from command line tmux
I have Sublime Text as an alias so I can call it from the terminal on MacOS.

Since I started using tmux, Running the following command opens sublime but not on the current directory.  It's like aliases are not accepting arguments on tmux.

```<code>subl .
</code>```

Without tmux this command works fine.

Any known issue with tmux alias arguments?

答:
This answer from SuperUser did the trick for me.

```<code>brew install reattach-to-user-namespace
</code>```

And then append the following to your ~/.tmux.conf

```<code>set-option -g default-command "reattach-to-user-namespace -l zsh"
</code>```

Lastly, source the config file for tmux

```<code>tmux source ~/.tmux.conf
</code>```

I use subl . all the time! It's a shame you've trained yourself not to use this helpful command.

Body:
I have Sublime Text as an alias so I can call it from the terminal on MacOS.

Since I started using tmux, Running the following command opens sublime but not on the current directory.  It's like aliases are not accepting arguments on tmux.

subl .

Without tmux this command works fine.

Any known issue with tmux alias arguments?

Body:
This answer from SuperUser did the trick for me.

brew install reattach-to-user-namespace

And then append the following to your ~/.tmux.conf

set-option -g default-command "reattach-to-user-namespace -l zsh"

Lastly, source the config file for tmux

tmux source ~/.tmux.conf

I use subl . all the time! It's a shame you've trained yourself not to use this helpful command.


问:
Mocking getActionBar() returns null
I'm testing an activity, and I want to mock getActionBar(). I've tried doing it the usual way, that is

```<code>ActionBar mActionBar;

@Before
public void setup() {
    initMocks(this);
    mActionBar = Mockito.mock(ActionBar.class);
}

@Test
public void someTest(){
    when(activity.getActionBar()).thenReturn(mActionBar);
}
</code>```

But that doesn't seem to do anything, because I still get an NPE, when I try using the action bar in the activity after getActionBar().

答:
I assume you're setting Activity as it is written in Robolectric tutorial. There is no simple way to mock real activity method inside of activity code itself.

I would suggest you create TestMyActivity that extends your activity and lives only in test sources. Then you can override getActionBar() (probably getSupportActionBar())).

```<code>public class TestMyActivity extends MyActivity {
   @Override
   ActionBar getActionBar() {
      return mockedActionBar;
   }
}
</code>```

Title: Mocking getActionBar() returns null

Body:
I'm testing an activity, and I want to mock getActionBar(). I've tried doing it the usual way, that is

ActionBar mActionBar;

@Before
public void setup() {
    initMocks(this);
    mActionBar = Mockito.mock(ActionBar.class);
}

@Test
public void someTest(){
    when(activity.getActionBar()).thenReturn(mActionBar);
}

But that doesn't seem to do anything, because I still get an NPE, when I try using the action bar in the activity after getActionBar().

Body:
I assume you're setting Activity as it is written in Robolectric tutorial. There is no simple way to mock real activity method inside of activity code itself.

I would suggest you create TestMyActivity that extends your activity and lives only in test sources. Then you can override getActionBar() (probably getSupportActionBar())).

public class TestMyActivity extends MyActivity {
   @Override
   ActionBar getActionBar() {
      return mockedActionBar;
   }
}


问:
How do I find commands matching a set of filters with Get-Command?
I'm fairly new to powershell. I've done searches and checked stackoverflow and super user. Even my mobile app and affordable textbook say nothing of it.

Is there an easy way to apply multiple options / filters that I don't understand. Or is there a term that I don't know of that means options / filters?

I've been trying to use:

```<code>get-command -commandtype cmdlet -and -verb add
get-command -commandtype cmdlet| -verb add
get-command -commandtype cmdlet|get-command -verb add
</code>```

None of these bring back the proper list. And the last brings back something but it is always random and only some of the proper results.

I'd be interested in any response. Very interested if you are a great powershell user that could simply and concisely help.

Thanks in advance.

答:
```<code>Get-Command -Verb Add
</code>```

would show you all cmdlets and functions whose name starts with Add-.

If you want to limit the output to cmdlets only, use wildcard pattern Add-* with the (implied) -Name parameter instead:

```<code>Get-Command -CommandType cmdlet Add-*
</code>```

A less efficient, pipeline-based equivalent would be:

```<code>Get-Command -CommandType cmdlet | ? Verb -eq 'Add' # '?' is an alias for 'Where-Object'
</code>```

While it would make sense to be able to combine -CommandType with the specific value of Cmdlet with a -Verb argument, the current syntax (as of PSv5.1) doesn't permit that, as evidenced by (part of) the output from Get-Command -?:

```<code>Get-Command [[-Name] <String[]>] [[-ArgumentList] <Object[]>] [-All] [-CommandType {Alias | Function | Filter | Cmdlet | ExternalScript | Application |
Script | Workflow | Configuration | All}] [-FullyQualifiedModule <ModuleSpecification[]>] [-ListImported] [-Module <String[]>] [-ParameterName <String[]>]
[-ParameterType <PSTypeName[]>] [-ShowCommandInfo] [-Syntax] [-TotalCount <Int32>] [<CommonParameters>]

Get-Command [[-ArgumentList] <Object[]>] [-All] [-FullyQualifiedModule <ModuleSpecification[]>] [-ListImported] [-Module <String[]>] [-Noun <String[]>]
[-ParameterName <String[]>] [-ParameterType <PSTypeName[]>] [-ShowCommandInfo] [-Syntax] [-TotalCount <Int32>] [-Verb <String[]>] [<CommonParameters>]
</code>```

Each paragraph above represents a so-called parameter set, and as you can see, -Verb and -Name are in different parameter sets, which means you can't use them as part of the same command line.

As for what you tried:

get-command -commandtype cmdlet -and -verb add

Commands take a list of parameters (parameter values) - the interpretation of which is up to the target command; there is no support for using Boolean operators (such as -and) to combine these.

Boolean operators can only be used in expressions, not in commands.

get-command -commandtype cmdlet| -verb add

You can only use a pipeline to pipe to commands (cmdlets, functions, aliases, external utilities and their arguments) - in your case, -verb is interpreted as a command name, which obviously fails.

get-command -commandtype cmdlet|get-command -verb add

One you've used get-command -commandtype cmdlet to retrieve all cmdlets, you don't need a 2nd get-command instance to further filter the results - instead, you filter by the properties of the objects output by the 1st get-command call, as demonstrated above.

Body:
I'm fairly new to powershell. I've done searches and checked stackoverflow and super user. Even my mobile app and affordable textbook say nothing of it.

Is there an easy way to apply multiple options / filters that I don't understand. Or is there a term that I don't know of that means options / filters?

I've been trying to use:

get-command -commandtype cmdlet -and -verb add
get-command -commandtype cmdlet| -verb add
get-command -commandtype cmdlet|get-command -verb add

None of these bring back the proper list. And the last brings back something but it is always random and only some of the proper results.

I'd be interested in any response. Very interested if you are a great powershell user that could simply and concisely help.

Thanks in advance.

Body:
Get-Command -Verb Add

would show you all cmdlets and functions whose name starts with Add-.

If you want to limit the output to cmdlets only, use wildcard pattern Add-* with the (implied) -Name parameter instead:

Get-Command -CommandType cmdlet Add-*

A less efficient, pipeline-based equivalent would be:

Get-Command -CommandType cmdlet | ? Verb -eq 'Add' # '?' is an alias for 'Where-Object'

While it would make sense to be able to combine -CommandType with the specific value of Cmdlet with a -Verb argument, the current syntax (as of PSv5.1) doesn't permit that, as evidenced by (part of) the output from Get-Command -?:

Get-Command [[-Name] <String[]>] [[-ArgumentList] <Object[]>] [-All] [-CommandType {Alias | Function | Filter | Cmdlet | ExternalScript | Application |
Script | Workflow | Configuration | All}] [-FullyQualifiedModule <ModuleSpecification[]>] [-ListImported] [-Module <String[]>] [-ParameterName <String[]>]
[-ParameterType <PSTypeName[]>] [-ShowCommandInfo] [-Syntax] [-TotalCount <Int32>] [<CommonParameters>]

Get-Command [[-ArgumentList] <Object[]>] [-All] [-FullyQualifiedModule <ModuleSpecification[]>] [-ListImported] [-Module <String[]>] [-Noun <String[]>]
[-ParameterName <String[]>] [-ParameterType <PSTypeName[]>] [-ShowCommandInfo] [-Syntax] [-TotalCount <Int32>] [-Verb <String[]>] [<CommonParameters>]

Each paragraph above represents a so-called parameter set, and as you can see, -Verb and -Name are in different parameter sets, which means you can't use them as part of the same command line.

As for what you tried:

get-command -commandtype cmdlet -and -verb add

Commands take a list of parameters (parameter values) - the interpretation of which is up to the target command; there is no support for using Boolean operators (such as -and) to combine these.

Boolean operators can only be used in expressions, not in commands.

get-command -commandtype cmdlet| -verb add

You can only use a pipeline to pipe to commands (cmdlets, functions, aliases, external utilities and their arguments) - in your case, -verb is interpreted as a command name, which obviously fails.

get-command -commandtype cmdlet|get-command -verb add

One you've used get-command -commandtype cmdlet to retrieve all cmdlets, you don't need a 2nd get-command instance to further filter the results - instead, you filter by the properties of the objects output by the 1st get-command call, as demonstrated above.


问:
Why is my div header and div disappearing?
So, the div header is placed is supposed to be placed on top of the div theoretically. This code was copied and pasted from another page of my website, and I just changed the div names, because everything else is identical. However, for some reason, my div header nor the div are showing up on my page, does anyone have any idea why?

My CSS:

```<code>#3D {
    background-color: cornsilk;
    float: left;
    height: 180px;
    width: 500px;
    margin-top: 215px;
    margin-left: 420px;
    margin-right: 400px;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    z-level: 12;
    position: absolute;
}
#3DHeader {
    float: left;
    background-color: #111111;
    width: 490px;
    height: 75px;
    margin-top: 220px;
    margin-left: 425px;
    position: absolute;
    z-level: 13;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    box-shadow: 0px 10px 10px 0px #888888;
}
h4 {
    font-size: 25px;
    padding-left: 265px;
    color: cornsilk;
    font-family:'Garamond'
}
p {
    font-size: 15px;
    color: black;
    font-family:'Garamond'
}
</code>```

答: Without your html it's hard to know, but my guess is it has something to do with your #3D... HTML ids cannot start with numbers. Try changing the ID to start with letters and change your css as well, and see if that fixes it.</p>

Body:
So, the div header is placed is supposed to be placed on top of the div theoretically. This code was copied and pasted from another page of my website, and I just changed the div names, because everything else is identical. However, for some reason, my div header nor the div are showing up on my page, does anyone have any idea why?

My CSS:

#3D {
    background-color: cornsilk;
    float: left;
    height: 180px;
    width: 500px;
    margin-top: 215px;
    margin-left: 420px;
    margin-right: 400px;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    z-level: 12;
    position: absolute;
}
#3DHeader {
    float: left;
    background-color: #111111;
    width: 490px;
    height: 75px;
    margin-top: 220px;
    margin-left: 425px;
    position: absolute;
    z-level: 13;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    box-shadow: 0px 10px 10px 0px #888888;
}
h4 {
    font-size: 25px;
    padding-left: 265px;
    color: cornsilk;
    font-family:'Garamond'
}
p {
    font-size: 15px;
    color: black;
    font-family:'Garamond'
}


问:
Getting error "No such module" using Xcode, but the framework is there
I'm currently coding in Swift, and I've got an error:

No such module Social

But I don't understand, because the module is in my project, declared in "Linked frameworks and Libraries" and in "Embedded Binaries".

The frameworks is in Objective-C, so I wrote a Bridge Header for it.

Please, how can I make Xcode recognize the framework?

答:
If you're building for a platform like tvOS, make sure you have an Apple TV (i.e. matching) simulator selected.

Building a tvOS app with an iOS simulator selected gave me exactly this error. Spent the better part of an hour looking for all sorts of build issues... doh.


问:
Android Studio 2.3 not showing properties window
I am using Android Studio 2.3 When I click on a button or textfield or any widget I want the properties windows to show up on the right so I can see all available properties for that widget and edit the properties there. How can I get the properties window to appear?

答: I have solved it. If you press shift+f12 it will restore the default layout.</p>


问:
APK Parsing Error
I do not know how to continue...

I build a signed or unsigned apk with Android Studio (everything is up to date). Now I want to test this apk and install it on my phone.
But I always get a parsing error...

I tried diffrent devices but with the same result. I tryed a blank app but with the same result. I can't install it because of a parsing error. But deploying directly from AS works just fine!

What I tried out:
Reinstalling SDK (latest)
Reinstalling Android Studio (latest)
Reinstalling Java (latest)

an older gradle version (2.2.3)

Dev options and allowing unknown sources are aktive on all my devices.
minSdkVersion is set to 19 (I just have devices with Android 5 and 6)

I don't have an idea where the problem comes from...

Can somebody help me?

Thanks in advance!!!

答:
It's not the code at all! I tried a new blank project and I couldn't install it too

but here is the Manifest and the gradle:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.brokenbricksstudios.todo"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="19"
        android:targetSdkVersion="23"/>

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ToDo"
            android:clearTaskOnLaunch="true"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <service android:name=".bubbles.BubblesService"
            android:enabled="true"
            android:exported="false" />
    </application>

</manifest>
</code>```

gradle:

```<code>    apply plugin: 'com.android.application'

    android {
        signingConfigs {
            TODO {
                keyAlias 'TODO'
                keyPassword '***********'
                storeFile file('E:/AndroidStudioProjects/KeyStore.jks')
                storePassword '***********'
             }
        }
        compileSdkVersion 23
        buildToolsVersion '25.0.2'
        defaultConfig {
            applicationId "com.brokenbricksstudios.todo"
            minSdkVersion 19
            targetSdkVersion 23
            versionCode 1
            versionName "1.0"
            signingConfig signingConfigs.TODO
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.TODO
        }
        debug {
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.google.android.gms:play-services-appindexing:8.1.0'
}
</code>```

Title: APK Parsing Error

Body:
It's not the code at all! I tried a new blank project and I couldn't install it too

but here is the Manifest and the gradle:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.brokenbricksstudios.todo"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="19"
        android:targetSdkVersion="23"/>

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ToDo"
            android:clearTaskOnLaunch="true"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <service android:name=".bubbles.BubblesService"
            android:enabled="true"
            android:exported="false" />
    </application>

</manifest>

gradle:

    apply plugin: 'com.android.application'

    android {
        signingConfigs {
            TODO {
                keyAlias 'TODO'
                keyPassword '***********'
                storeFile file('E:/AndroidStudioProjects/KeyStore.jks')
                storePassword '***********'
             }
        }
        compileSdkVersion 23
        buildToolsVersion '25.0.2'
        defaultConfig {
            applicationId "com.brokenbricksstudios.todo"
            minSdkVersion 19
            targetSdkVersion 23
            versionCode 1
            versionName "1.0"
            signingConfig signingConfigs.TODO
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.TODO
        }
        debug {
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.google.android.gms:play-services-appindexing:8.1.0'
}


问:
upgrading php 5.6.3 to 5.6.4 or higher (branch 5.6)
I have a Centos 7, with a php 5.6.3 installed on it.

```<code>php -v
PHP 5.6.30 (cli) (built: Jan 19 2017 07:08:58)
</code>```

Now I want to install an open source project that requires minimum php version 5.6.4.

```<code>(*) PHP 5.6.0 - 5.6.3 are not compatible caused by a session bug
</code>```

How can I do the upgrade?
I tried many howto's found with google, but none of them work. For example:
https://www.centos.org/forums/viewtopic.php?t=52586
Of course I have the latest (I think) repos:

package webtatic-release-7-3.noarch is already installed

package epel-release-7-9.noarch already installed and latest version

When I run

```<code>yum update php
</code>```

I get:

```<code>...
Package(s) php available, but not installed.
No packages marked for update
</code>```

or:

```<code>yum -y upgrade php*
</code>```

I get:

```<code>Loaded plugins: fastestmirror, replace
Loading mirror speeds from cached hostfile
 * base: mirrors.hostingfuze.net
 * extras: centos.mirrors.telekom.ro
 * ius: ftp.astral.ro
 * remi-safe: mirrors.neterra.net
 * updates: centos.mirrors.telekom.ro
No packages marked for update
</code>```

So basically my question is: how can I install the PHP 5.6.4 or higher on my system that already has PHP 5.6.3

答:
Try this:

```<code>yum install -y http://dl.iuscommunity.org/pub/ius/stable/CentOS/7/x86_64/ius-release-1.0-14.ius.centos7.noarch.rpm
yum -y update
yum -y install php70u php70u-pdo php70u-mysqlnd php70u-opcache php70u-xml php70u-mcrypt php70u-gd php70u-devel php70u-mysql php70u-intl php70u-mbstring php70u-bcmath php70u-json php70u-iconv
</code>```

or check this link: https://stackoverflow.com/a/40406823/7804966

Body:
I have a Centos 7, with a php 5.6.3 installed on it.

php -v
PHP 5.6.30 (cli) (built: Jan 19 2017 07:08:58)

Now I want to install an open source project that requires minimum php version 5.6.4.

(*) PHP 5.6.0 - 5.6.3 are not compatible caused by a session bug

How can I do the upgrade?
I tried many howto's found with google, but none of them work. For example:
https://www.centos.org/forums/viewtopic.php?t=52586
Of course I have the latest (I think) repos:

package webtatic-release-7-3.noarch is already installed

package epel-release-7-9.noarch already installed and latest version

When I run

yum update php

I get:

...
Package(s) php available, but not installed.
No packages marked for update

or:

yum -y upgrade php*

I get:

Loaded plugins: fastestmirror, replace
Loading mirror speeds from cached hostfile
 * base: mirrors.hostingfuze.net
 * extras: centos.mirrors.telekom.ro
 * ius: ftp.astral.ro
 * remi-safe: mirrors.neterra.net
 * updates: centos.mirrors.telekom.ro
No packages marked for update

So basically my question is: how can I install the PHP 5.6.4 or higher on my system that already has PHP 5.6.3

Body:
Try this:

yum install -y http://dl.iuscommunity.org/pub/ius/stable/CentOS/7/x86_64/ius-release-1.0-14.ius.centos7.noarch.rpm
yum -y update
yum -y install php70u php70u-pdo php70u-mysqlnd php70u-opcache php70u-xml php70u-mcrypt php70u-gd php70u-devel php70u-mysql php70u-intl php70u-mbstring php70u-bcmath php70u-json php70u-iconv

or check this link: https://stackoverflow.com/a/40406823/7804966


问:
How to draw a line on top of multiple layouts in android
Im new to android programming, and facing a difficulty in understanding what to needs to be done. Im trying to create a line that will move according to time, an appointment app,similar to the attached photo. Each column is going to be a separate relative layout. How can i draw a line across all the layouts?

Image

答:
i think you have to user View for it and give height to 1px (if you want to make horizontal line if you want to create vertical line then set width to 1px and height as you like)with background color as you like.

```<code><View android:layout_width="match_parent"
      android:layout_height="1px"
      android:background="#000000" />
</code>```

Like this

Body:
i think you have to user View for it and give height to 1px (if you want to make horizontal line if you want to create vertical line then set width to 1px and height as you like)with background color as you like.

<View android:layout_width="match_parent"
      android:layout_height="1px"
      android:background="#000000" />

Like this


问:
How to get the next row value in another column
I have Table called Opp Table

```<code>   OppID         actualclosedate
--------------------------------------
    1            10-March
</code>```

I have a Table called stagechange

```<code>--------------------------------------
   OppID      Stage       createdon
--------------------------------------
    1         Propsect    1-Jan
    1         Qualify     15-Jan
    1         Develop     25-Jan
    1         Qualify     9-Feb
    1         Develop     7-March
    1         Prospect    9-April
</code>```

How Can I create a new column and get the next row value that is in createdon column; to have something like this. If there is no more next values, we get the date from other table like actual close date in Opp Table

```<code>--------------------------------------
   OppID      Stage       createdon   newcolumn
--------------------------------------
    1         Propsect    1-Jan        15-Jan
    1         Qualify     15-Jan       25-Jan
    1         Develop     25-Jan       9-Feb
    1         Qualify     9-Feb        7-March
    1         Develop     7-March      9-April
    1         Prospect    9-April     10-March ----(actualclosedate)
</code>```

答: you can use the COALESCE fonction https://msdn.microsoft.com/fr-fr/library/ms190349.aspx</p>

Body:
I have Table called Opp Table

   OppID         actualclosedate
--------------------------------------
    1            10-March

I have a Table called stagechange

--------------------------------------
   OppID      Stage       createdon
--------------------------------------
    1         Propsect    1-Jan
    1         Qualify     15-Jan
    1         Develop     25-Jan
    1         Qualify     9-Feb
    1         Develop     7-March
    1         Prospect    9-April

How Can I create a new column and get the next row value that is in createdon column; to have something like this. If there is no more next values, we get the date from other table like actual close date in Opp Table

--------------------------------------
   OppID      Stage       createdon   newcolumn
--------------------------------------
    1         Propsect    1-Jan        15-Jan
    1         Qualify     15-Jan       25-Jan
    1         Develop     25-Jan       9-Feb
    1         Qualify     9-Feb        7-March
    1         Develop     7-March      9-April
    1         Prospect    9-April     10-March ----(actualclosedate)


问:
Close virtual keyboard on button press
I have an Activity with an EditText, a button and a ListView.  The purpose is to type a search screen in the EditText, press the button and have the search results populate this list.

This is all working perfectly, but the virtual keyboard is behaving strange.

If I click the EditText, I get the virtual keyboard.  If I click the "Done" button on the virtual keyboard, it goes away.  However, if I click my search button before clicking "Done" on the virtual keyboard, the virtual keyboard stays and I can't get rid of it.  Clicking the "Done" button does not close the keyboard.  It changes the "Done" button from "Done" to an arrow and remains visible.

Thanks for your help

答:
```<code>View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm =(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);enter code here}
</code>```

Title: Close virtual keyboard on button press