问:
I am trying to get the DateTimeFormatter for a date string in joda time
I need the format string for a date that is formatted like this: 2017-06-14T00:00:00Z.

Currently, I have:

```<code>DateTimeFormatter DT_SCHEDULE_FORMATTER_START_TIME = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
</code>```

If I parse a the string 2017-06-14T00:00:00Z with this, it gives me the right time in UTC.

But when I take a DateTime object and try to do:

```<code>String strNow = new DateTime().toString(DT_SCHEDULE_FORMATTER_START_TIME);
</code>```

I get something like 2017-06-14T00:00:00 -07:00

I've looked in the documentation and can't seem to find the right formatting string.

答:
You can try to use the parseDateTime function

```<code>DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
DateTime dateTime = f.parseDateTime("2017-06-14T00:00:00Z");
</code>```

Hope it will help.

Body:
I need the format string for a date that is formatted like this: 2017-06-14T00:00:00Z.

Currently, I have:

DateTimeFormatter DT_SCHEDULE_FORMATTER_START_TIME = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");

If I parse a the string 2017-06-14T00:00:00Z with this, it gives me the right time in UTC.

But when I take a DateTime object and try to do:

String strNow = new DateTime().toString(DT_SCHEDULE_FORMATTER_START_TIME);

I get something like 2017-06-14T00:00:00 -07:00

I've looked in the documentation and can't seem to find the right formatting string.

Body:
You can try to use the parseDateTime function

DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
DateTime dateTime = f.parseDateTime("2017-06-14T00:00:00Z");

Hope it will help.


来源: stackexchange

问:
How to make a foreach of an object in javascript?
I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

```<code>var CurrentSelec = app1.selectionState().selections;
console.log(CurrentSelec);`
console.log(typeof CurrentSelec);
</code>```

This is what I get on my browser console :

I'm trying to show the qSelected value in a Foreach :

I have tried with Javascript :

```<code>for(var index in CurrentSelec) {
    console.log(index.qSelected);
}
</code>```

I have tried with jQuery:

```<code>$.each(CurrentSelec, function(i, index) {
  console.log(index.qSelected)
});
</code>```

But my browser console do not show the log of my foreach.

Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

Regards.

答:
Try using below code and see if it works, instead of CurrentSelec use CurrentSelec[0]

```<code>$.each(CurrentSelec[0], function(i, index) {
  console.log(index.qSelected)
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

var CurrentSelec = app1.selectionState().selections;
console.log(CurrentSelec);`
console.log(typeof CurrentSelec);

This is what I get on my browser console :

I'm trying to show the qSelected value in a Foreach :

I have tried with Javascript :

for(var index in CurrentSelec) {
    console.log(index.qSelected);
}

I have tried with jQuery:

$.each(CurrentSelec, function(i, index) {
  console.log(index.qSelected)
});

But my browser console do not show the log of my foreach.

Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

Regards.

Body:
Try using below code and see if it works, instead of CurrentSelec use CurrentSelec[0]

$.each(CurrentSelec[0], function(i, index) {
  console.log(index.qSelected)
});


问:
How to lower case entire column data in Google Cloud BigQuery
I am trying to find a "quick" way to lower case all the data (strings) in a table's column inside Google Cloud BigQuery.

Before going into building a script, I'm looking for more shorter way like Query.

How can I query BigQuery to lower case entire column?

答:
Found out my self. it can be done using UPDATE as Elliott suggested. but it must use standartSQL. I used the #standardSQL declration for that.

```<code>#standardSQL
UPDATE dataset.table
SET field = LOWER(field)
WHERE TRUE
</code>```

Body:
Found out my self. it can be done using UPDATE as Elliott suggested. but it must use standartSQL. I used the #standardSQL declration for that.

#standardSQL
UPDATE dataset.table
SET field = LOWER(field)
WHERE TRUE


问:
What is the correct way of supporting an Options request when using OAuthAuthorizationServer with Angular2 Apps
I have spent considerable time learning about OAuth servers and have arrived at what I believe to be a relatively good solution thanks to multiple posts in StackOverflow (also following this excellent guide). I have a working OAuth server, with Refresh Tokens, Client support and controllable Origin management by client id. I'm happy with the technical solution all except for one thing, when an Angular app attempts to perform a CORS Options call the first apparent method that is called within my service is:

```<code>Task ValidateClientAuthentication (OAuthValidateClientAuthenticationContext context);
</code>```

Which internally tries to validate the calling client and check the client secret. With Options calls, no ClientID or anything like that would be supplied so my service throws an authentication error.

Is there a way of allowing the Options call in the OAuthServer Validation Method? Should it be done somewhere else?

答:
My fix for this seems to be to override the behaviour for the:

```<code> MatchEndpoint (OAuthMatchEndpointContext context)
{
  if ( context.OwinContext.Request.Method == "OPTIONS" && context.IsTokenEndpoint )
   {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new [] { "*" });
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new [] { "POST" });
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new [] { "accept", "authorisation", "content-type" });
        context.OwinContext.Response.StatusCode = 200;
        context.RequestCompleted();
        return Task.CompletedTask;
   }
}
</code>```

In my implementation of the OAuthAuthorizationServerProvider...

Body:
I have spent considerable time learning about OAuth servers and have arrived at what I believe to be a relatively good solution thanks to multiple posts in StackOverflow (also following this excellent guide). I have a working OAuth server, with Refresh Tokens, Client support and controllable Origin management by client id. I'm happy with the technical solution all except for one thing, when an Angular app attempts to perform a CORS Options call the first apparent method that is called within my service is:

Task ValidateClientAuthentication (OAuthValidateClientAuthenticationContext context);

Which internally tries to validate the calling client and check the client secret. With Options calls, no ClientID or anything like that would be supplied so my service throws an authentication error.

Is there a way of allowing the Options call in the OAuthServer Validation Method? Should it be done somewhere else?

Body:
My fix for this seems to be to override the behaviour for the:

 MatchEndpoint (OAuthMatchEndpointContext context)
{
  if ( context.OwinContext.Request.Method == "OPTIONS" && context.IsTokenEndpoint )
   {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new [] { "*" });
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new [] { "POST" });
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new [] { "accept", "authorisation", "content-type" });
        context.OwinContext.Response.StatusCode = 200;
        context.RequestCompleted();
        return Task.CompletedTask;
   }
}

In my implementation of the OAuthAuthorizationServerProvider...


问:
Double-pipe statement with two commands using the `&&` on a `for` loop (batch script)
Based on answers and comments from this question, I cannot understand how to add a double-pipe || statement with two commands using the && on a for loop. Consider the following example taken from here:

```<code>@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
</code>```

If I try

```<code>for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a" || echo Error while getting datetime. >> %someoutputfile% && GOTO endthis
</code>```

I get a Unexpected && error. I tried adding parenthesis around the each command after the || but they too give Unexpected ) similar errors.

Can someone explain what I am doing wrong? Should I put the || commands before the do set "dt=%%a" or something?

答:
You may also use this approach:

```<code>(for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a") || rem

if errorlevel 1 echo Error while getting datetime. >> %someoutputfile% & GOTO endthis
</code>```

This method is fully described below Exit Code management at this answer.

Body:
Based on answers and comments from this question, I cannot understand how to add a double-pipe || statement with two commands using the && on a for loop. Consider the following example taken from here:

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

If I try

for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a" || echo Error while getting datetime. >> %someoutputfile% && GOTO endthis

I get a Unexpected && error. I tried adding parenthesis around the each command after the || but they too give Unexpected ) similar errors.

Can someone explain what I am doing wrong? Should I put the || commands before the do set "dt=%%a" or something?

Body:
You may also use this approach:

(for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a") || rem

if errorlevel 1 echo Error while getting datetime. >> %someoutputfile% & GOTO endthis

This method is fully described below Exit Code management at this answer.


问:
Scribe-LinkedIn Search API
I want to fetch data from the LinkedIn API for that I am using the Scribe library.All requests are giving me data as expected but when I tried two facet in the url then scribe is not able to get data from LinkedIn API.
If I gave this URL : http://api.linkedin.com/v1/people-search?facets=location,network&facet=location,in:0 then it gives me proper result

but if I entered this URL:
http://api.linkedin.com/v1/people-search?facets=location,network&facet=location,in:0&facet=network,F i.e. URL containing multiple facets then it gives me this output:

```<code>  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <error>
     <status>401</status>
     <timestamp>1292487039516</timestamp>
     <error-code>0</error-code>
     <message> [unauthorized].OAU:CiEgwWDkA5BFpNrc0RfGyVuSlOh4tig5kOTZ9q97qcXNrFl7zqk-   Ts7DqRGaKDCV|94f13544-9844-41eb-9d53-8fe36535bbc3|*01|*01:1292487039:VseHXaJXM2gerxJyn6kHhIka7zw=</message>
      </error>
</code>```

Any kind of help to solve this will be appreciated.Thanks.

答: When I saw that there is no help available so I decided to fix this bug of Scribe library and I am able to fixed that bug by modifying code.The modified code of Scribe is here.You can see as well as you can take checkout. And if you want to use that code then you need to just create its jar and add it to your projects build path.</p>

ContentLicense: CC BY-SA 2.5

Title: Scribe-LinkedIn Search API

Body:
I want to fetch data from the LinkedIn API for that I am using the Scribe library.All requests are giving me data as expected but when I tried two facet in the url then scribe is not able to get data from LinkedIn API.
If I gave this URL : http://api.linkedin.com/v1/people-search?facets=location,network&facet=location,in:0 then it gives me proper result

but if I entered this URL:
http://api.linkedin.com/v1/people-search?facets=location,network&facet=location,in:0&facet=network,F i.e. URL containing multiple facets then it gives me this output:

  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <error>
     <status>401</status>
     <timestamp>1292487039516</timestamp>
     <error-code>0</error-code>
     <message> [unauthorized].OAU:CiEgwWDkA5BFpNrc0RfGyVuSlOh4tig5kOTZ9q97qcXNrFl7zqk-   Ts7DqRGaKDCV|94f13544-9844-41eb-9d53-8fe36535bbc3|*01|*01:1292487039:VseHXaJXM2gerxJyn6kHhIka7zw=</message>
      </error>

Any kind of help to solve this will be appreciated.Thanks.


问:
QUndoStack remove specific command
How can I remove a specific command from a QUndoStack?

This command can be given by its index or pointer.

答:
That's the thing about stacks - you only work on top of the stack. You can push and you can pop. You don't remove stuff from the middle of the stack.

In an undo-redo scenario this is even more important, as the order of commands must be diligently preserved for the whole thing to work. Otherwise you will break it.

Which is why it is called an "undo stack" and not "reverse arbitrary action whatchamacallit".

There is QUndoStack::setIndex(int idx) which will undo all commands until the provided index. But you cannot really remove only a specific command. You need to undo all commands until you reach and remove the one you want.

Title: QUndoStack remove specific command


问:
Python function scope
I have a question about the scope in python functions. I've included an example that demonstrates the issue I am having.

fun0 redefines the first entry in varible c's list. This change is reflected outside of fun0, even when I don't return any values from fun0.

fun1 redefines the variable c entirely, but the change isn't reflected outside of fun1. Similarly, fun2 redefines c, and the change isn't reflected outside of fun2.

My question is, why does fun0 modify val3 in the main function, while fun1 and fun2 don't modify val4 and val7, respectively?

```<code>def fun0(a, b, c):
    c[0] = a[0] + b[0]
    return

def fun1(a, b, c):
    c = a[0] + b[0]
    return

def fun2(a, b, c):
    c = a + b
    return

def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print val3

    val4 = []
    fun1(val1, val2, val4)
    print val4

    val5 = 1
    val6 = 1
    val7 = 0
    fun2(val5, val6, val7)
    print val7
    return

if __name__=='__main__':
    main()
</code>```

答:
What Cary Shindell is absolutely correct.  Furthermore, if you DID want to save the updated values, here is how you can change your code to do that, I changed the print statements since I tested this in python 3.6.1.  Good question though.</p>

```<code>def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print(val3)

    val4 = []
    val4 = fun1(val1, val2, val4)
    print(val4)

    val5 = 1
    val6 = 1
    val7 = 0
    val7 = fun2(val5, val6, val7)
    print(val7)
    return
</code>```

Title: Python function scope

Body:
I have a question about the scope in python functions. I've included an example that demonstrates the issue I am having.

fun0 redefines the first entry in varible c's list. This change is reflected outside of fun0, even when I don't return any values from fun0.

fun1 redefines the variable c entirely, but the change isn't reflected outside of fun1. Similarly, fun2 redefines c, and the change isn't reflected outside of fun2.

My question is, why does fun0 modify val3 in the main function, while fun1 and fun2 don't modify val4 and val7, respectively?

def fun0(a, b, c):
    c[0] = a[0] + b[0]
    return

def fun1(a, b, c):
    c = a[0] + b[0]
    return

def fun2(a, b, c):
    c = a + b
    return

def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print val3

    val4 = []
    fun1(val1, val2, val4)
    print val4

    val5 = 1
    val6 = 1
    val7 = 0
    fun2(val5, val6, val7)
    print val7
    return

if __name__=='__main__':
    main()

Body:
What Cary Shindell is absolutely correct.  Furthermore, if you DID want to save the updated values, here is how you can change your code to do that, I changed the print statements since I tested this in python 3.6.1.  Good question though.

def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print(val3)

    val4 = []
    val4 = fun1(val1, val2, val4)
    print(val4)

    val5 = 1
    val6 = 1
    val7 = 0
    val7 = fun2(val5, val6, val7)
    print(val7)
    return


问:
How to find socket fds opened by a process in windows
I have a client process running in windows (win 7/win 2008 server). The task is to enable keepalive for one of the socket it opened to get connected with a server.
To make this connection i'm using windows API (connection to MSSQL server), from which i was unable to retrieve the socket fd it created.

1) What is the way to retrieve all the socket fds opened by a windows process (non python method, as the binary is a C++ based)

2) Is there any way to retrieve socket fd from the handle returned by the windows API SQLAllocHandle or SQLDriverConnect

Thanks

答:
You can't (AFAIK) and shouldn't (not supported) try to modify this on the client.  SQL Server has a server-side configuration setting that controls this:

Keep Alive

This parameter (in milliseconds) controls how often TCP attempts to verify that an idle connection is still intact by sending a KEEPALIVE packet. The default is 30000 milliseconds.

https://technet.microsoft.com/en-us/library/ms190771(v=sql.105).aspx


问:
Is possible send a array in Obj-c for a variable arguments function?
In python it is easy to build a dictionary or array and pass it unpacked to a function with variable parameters

I have this:

```<code>- (BOOL) executeUpdate:(NSString*)sql, ... {
</code>```

And the manual way is this:

```<code>[db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,
  @"hi'", // look!  I put in a ', and I'm not escaping it!
  [NSString stringWithFormat:@"number %d", i],
  [NSNumber numberWithInt:i],
  [NSDate date],
  [NSNumber numberWithFloat:2.2f]];
</code>```

But I can't hardcode the parameters I'm calling, I want:

```<code>NSMutableArray *values = [NSMutableArray array];

for (NSString *fieldName in props) {
  ..
  ..
  [values addObject : value]
}
[db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,??values];
</code>```

答:
I wanted to do the same thing.  I came up with the following, which works fine, given some constraints on the input variables.

```<code>NSArray* VarArgs(va_list ap)
{
  id obj;
  NSMutableArray* array = [NSMutableArray array];

  while ((obj = va_arg(ap, id))) {
    [array addObject:obj];
  }
  return array;
}

#define VarArgs2(_last_) ({ \
  va_list ap; \
  va_start(ap, _last_); \
  NSArray* __args = VarArgs(ap); \
  va_end(ap); \
  if (([__args count] == 1) && ([[__args objectAtIndex:0] isKindOfClass:[NSArray class]])) { \
    __args = [__args objectAtIndex:0]; \
  } \
__args; })
</code>```

Using the above, I can call the following with either an NSArray or with varargs.

```<code>// '...' must be objc objects with nil sentinel OR an NSArray with nil sentinel
- (void)someMethod:(NSString *)sql, ...
{
   NSArray *args = VarArgs2(sql);

   // Do stuff with args
}
</code>```

One more tip is to use the following in the prototype to have the compiler check for the nil sentinel to avoid potential bad things.  I got this out of the apple headers...

```<code>- (void)someMethod:(NSString *)sql, ... NS_REQUIRES_NIL_TERMINATION;
</code>```

OwnerDisplayName: mamcx

Body:
In python it is easy to build a dictionary or array and pass it unpacked to a function with variable parameters

I have this:

- (BOOL) executeUpdate:(NSString*)sql, ... {

And the manual way is this:

[db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,
  @"hi'", // look!  I put in a ', and I'm not escaping it!
  [NSString stringWithFormat:@"number %d", i],
  [NSNumber numberWithInt:i],
  [NSDate date],
  [NSNumber numberWithFloat:2.2f]];

But I can't hardcode the parameters I'm calling, I want:

NSMutableArray *values = [NSMutableArray array];

for (NSString *fieldName in props) {
  ..
  ..
  [values addObject : value]
}
[db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,??values];

Body:
I wanted to do the same thing.  I came up with the following, which works fine, given some constraints on the input variables.

NSArray* VarArgs(va_list ap)
{
  id obj;
  NSMutableArray* array = [NSMutableArray array];

  while ((obj = va_arg(ap, id))) {
    [array addObject:obj];
  }
  return array;
}

#define VarArgs2(_last_) ({ \
  va_list ap; \
  va_start(ap, _last_); \
  NSArray* __args = VarArgs(ap); \
  va_end(ap); \
  if (([__args count] == 1) && ([[__args objectAtIndex:0] isKindOfClass:[NSArray class]])) { \
    __args = [__args objectAtIndex:0]; \
  } \
__args; })

Using the above, I can call the following with either an NSArray or with varargs.

// '...' must be objc objects with nil sentinel OR an NSArray with nil sentinel
- (void)someMethod:(NSString *)sql, ...
{
   NSArray *args = VarArgs2(sql);

   // Do stuff with args
}

One more tip is to use the following in the prototype to have the compiler check for the nil sentinel to avoid potential bad things.  I got this out of the apple headers...

- (void)someMethod:(NSString *)sql, ... NS_REQUIRES_NIL_TERMINATION;

OwnerDisplayName: s-bug

LastEditorDisplayName: s-bug


问:
Silent exception,
I've encountered this weird issue of silent exceptions in 64 bit.
What is that cause this bahavior?
I would like to understand why does this occur and what is the recommended solution?

disappearing OnLoad exception

microsoft - silent exception

KB976038

on the main:

```<code>    try
    {
        Application.Run(new Form1());
    }
    catch
        (Exception ex)
    {
        MessageBox.Show("Error");
    }

private void Form1_Load(object sender, EventArgs e)
{
    throw new Exception("oh no!");
}
</code>```

答:
In order to load a form, your code will call into a kernel function to create the form's window, and this kernel function will in turn call back into your code by sending a message that invokes your OnLoad method. If you throw an exception in that method, the exception handling mechanism walks the call stack back to the kernel mode boundary.

On x86 an exception can go through this boundary and back to the original caller. On x64 it stops when it hits the boundary and cannot continue. In XP64 and Vista the exception was swallowed (ignored), while a 64-bit app with a manifest saying it is Win7-compatible will crash when this happens. To get the crashing behavior on other OSes or for 32-bit apps on 64-bit Win7, see KB976038.

This behavior will happen for any event handler that is invoked as a callback from kernel mode on x64.

Title: Silent exception,

Body:
I've encountered this weird issue of silent exceptions in 64 bit.
What is that cause this bahavior?
I would like to understand why does this occur and what is the recommended solution?

disappearing OnLoad exception

microsoft - silent exception

KB976038

on the main:

    try
    {
        Application.Run(new Form1());
    }
    catch
        (Exception ex)
    {
        MessageBox.Show("Error");
    }

private void Form1_Load(object sender, EventArgs e)
{
    throw new Exception("oh no!");
}


问:
How to increase the size of icons in jqgrid?
How should I increase the size of icons(add,delete..) in jqgrid?I have written following code in ui.jqgrid.css</p>

```<code>.ui-jqgrid .ui-jqgrid-pager .ui-pg-div  span.ui-icon,
.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div  span.ui-icon{float:left;margin: 2px; width:18px;}
.ui-jqgrid .ui-jqgrid-toppager {border-left: 0 none !important;border-right: 0 none !important; border-top: 0 none
!important; margin: 0 !important; padding: 0 !important; position: relative;white-space: nowrap;overflow: hidden;}
</code>```

答:
Free jqGrid supports vector based Font Awesome icons as alternative to raster icons of jQuery UI. To use Font Awesome you need just include the CSS of Font Awesome and to add iconSet: "fontAwesome" option. For example, https://jsfiddle.net/OlegKi/9f9exg91/1/ uses the following simple code

$("#grid1").jqGrid({
    colModel: [...],
    iconSet: "fontAwesome",
    ...
});
```

<p>which displays</p>

<p><img src="https://i.stack.imgur.com/Syba0.png" alt="enter image description here"></p>

<p>If you want for example increase the size of navigator icons in 1.5 of the standard size you can just add CSS rule</p>

<pre class="lang-css prettyprint-override"><code>.navtable .ui-pg-button {
    font-size: 150%;
}
</code>```

and get the navigator buttons

see https://jsfiddle.net/OlegKi/9f9exg91/2/. You can see that the navigator buttons are wrapped automatically. See the wiki article.

If you want in increase the size of all the buttons of the pager then you can use CSS rule

.ui-pg-table .ui-pg-button {
    font-size: 150%;
}
```

<p>alternatives. See https://jsfiddle.net/OlegKi/9f9exg91/3/, which displays</p>

<p><img src="https://i.stack.imgur.com/vU607.png" alt="enter image description here"></p>

<p>Free jqGrid supports additionally <code>iconsOverText: true</code> option, which allows to get the following look of icons:</p>

<p><img src="https://i.stack.imgur.com/aSZs8.png" alt="enter image description here"></p>

<p>see https://jsfiddle.net/OlegKi/9f9exg91/4/</p>

<p>In general you can customize the buttons in easy way like you need. For example you can go to some button generator page like this one create custom button and to copy the CSS styles to <code>.ui-jqgrid .navtable .ui-pg-button</code>. I did this and created the next demo https://jsfiddle.net/OlegKi/9f9exg91/6/, which displays the following navigator bars:</p>

<p><img src="https://i.stack.imgur.com/Tu7CO.png" alt="enter image description here"></p>

<p>Below you can find the CSS rules used in the last demo:</p>

<pre class="lang-css prettyprint-override"><code>.ui-jqgrid .navtable .ui-pg-button:not(.ui-state-hover) {
    background: #3498db;
    background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
    background-image: -moz-linear-gradient(top, #3498db, #2980b9);
    background-image: -ms-linear-gradient(top, #3498db, #2980b9);
    background-image: -o-linear-gradient(top, #3498db, #2980b9);
    background-image: linear-gradient(to bottom, #3498db, #2980b9);
    -webkit-border-radius: 8;
    -moz-border-radius: 8;
    border-radius: 8px;
    -webkit-box-shadow: 3px 3px 7px #666666;
    -moz-box-shadow: 3px 3px 7px #666666;
    box-shadow: 3px 3px 7px #666666;
    color: #ffffff;
    font-size: 14px;
    padding: 6px 6px 6px 6px;
    border: solid #0089de 1px;
    text-decoration: none;
}
.ui-jqgrid .navtable .ui-pg-button.ui-state-hover,
.ui-jqgrid .navtable .ui-pg-button:hover{
    background: #3cb0fd;
    background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
    background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
    background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
    background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
    background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
    padding: 6px 6px 6px 6px;
    font-size: 14px;
    text-decoration: none;
}
</code>```

I used additional pagerRightWidth: 100 option in the last demo to fix the right part of the pager and to provide more place for the navigator icons.

UPDATED: One can use top pager by usage of toppager: true instead of pager: true or to use both pagers. If one would replace .navtable in the above CSS rules to .ui-pg-table then the style will be applied to all buttons of the pager: https://jsfiddle.net/OlegKi/9f9exg91/9/

Body:
How should I increase the size of icons(add,delete..) in jqgrid?I have written following code in ui.jqgrid.css

.ui-jqgrid .ui-jqgrid-pager .ui-pg-div  span.ui-icon,
.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div  span.ui-icon{float:left;margin: 2px; width:18px;}
.ui-jqgrid .ui-jqgrid-toppager {border-left: 0 none !important;border-right: 0 none !important; border-top: 0 none
!important; margin: 0 !important; padding: 0 !important; position: relative;white-space: nowrap;overflow: hidden;}

Body:
Free jqGrid supports vector based Font Awesome icons as alternative to raster icons of jQuery UI. To use Font Awesome you need just include the CSS of Font Awesome and to add iconSet: "fontAwesome" option. For example, https://jsfiddle.net/OlegKi/9f9exg91/1/ uses the following simple code

$("#grid1").jqGrid({
    colModel: [...],
    iconSet: "fontAwesome",
    ...
});

which displays

If you want for example increase the size of navigator icons in 1.5 of the standard size you can just add CSS rule

.navtable .ui-pg-button {
    font-size: 150%;
}

and get the navigator buttons

see https://jsfiddle.net/OlegKi/9f9exg91/2/. You can see that the navigator buttons are wrapped automatically. See the wiki article.

If you want in increase the size of all the buttons of the pager then you can use CSS rule

.ui-pg-table .ui-pg-button {
    font-size: 150%;
}

alternatives. See https://jsfiddle.net/OlegKi/9f9exg91/3/, which displays

Free jqGrid supports additionally iconsOverText: true option, which allows to get the following look of icons:

see https://jsfiddle.net/OlegKi/9f9exg91/4/

In general you can customize the buttons in easy way like you need. For example you can go to some button generator page like this one create custom button and to copy the CSS styles to .ui-jqgrid .navtable .ui-pg-button. I did this and created the next demo https://jsfiddle.net/OlegKi/9f9exg91/6/, which displays the following navigator bars:

Below you can find the CSS rules used in the last demo:

.ui-jqgrid .navtable .ui-pg-button:not(.ui-state-hover) {
    background: #3498db;
    background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
    background-image: -moz-linear-gradient(top, #3498db, #2980b9);
    background-image: -ms-linear-gradient(top, #3498db, #2980b9);
    background-image: -o-linear-gradient(top, #3498db, #2980b9);
    background-image: linear-gradient(to bottom, #3498db, #2980b9);
    -webkit-border-radius: 8;
    -moz-border-radius: 8;
    border-radius: 8px;
    -webkit-box-shadow: 3px 3px 7px #666666;
    -moz-box-shadow: 3px 3px 7px #666666;
    box-shadow: 3px 3px 7px #666666;
    color: #ffffff;
    font-size: 14px;
    padding: 6px 6px 6px 6px;
    border: solid #0089de 1px;
    text-decoration: none;
}
.ui-jqgrid .navtable .ui-pg-button.ui-state-hover,
.ui-jqgrid .navtable .ui-pg-button:hover{
    background: #3cb0fd;
    background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
    background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
    background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
    background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
    background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
    padding: 6px 6px 6px 6px;
    font-size: 14px;
    text-decoration: none;
}

I used additional pagerRightWidth: 100 option in the last demo to fix the right part of the pager and to provide more place for the navigator icons.

UPDATED: One can use top pager by usage of toppager: true instead of pager: true or to use both pagers. If one would replace .navtable in the above CSS rules to .ui-pg-table then the style will be applied to all buttons of the pager: https://jsfiddle.net/OlegKi/9f9exg91/9/


问:
cytoscape.js angular2 typescript use
Have an angular4 application packed with Webpack.

want to use cytoscape.js. Need to use npm module for this: https://www.npmjs.com/package/ng2-cytoscape

I have done changes as in that page , only with a difference

```<code>import {NgCytoscapeModule} from "ng2-cytoscape";
</code>```

instead of "ng2-cytoscape/dist"; (which was giving compilation errors)

Then added the following lines to app.module.ts

```<code>import {NgCytoscapeModule}      from 'ng2-cytoscape';

@NgModule({
  imports: [
    NgCytoscapeModule
  ],
</code>```

Also , added the dependency to the package.json

```<code>"dependencies": {
    "ng2-cytoscape": "^0.2.0",
}
</code>```

This gives the following error:

```<code>compiler.es5.js:1540 Uncaught Error: Unexpected value 'NgCytoscapeModule' imported by the module 'AppModule'. Please add a @NgModule annotation.
at syntaxError (compiler.es5.js:1540)
</code>```

What is the reason? Is there another way to use cytoscape.js in Angular 2 - Typescript ?

答: Cytoscape does not have an official support package for Angular.  If you want to use Cytoscape, use the official cytoscape package and write your own Angular integration that suits your needs.

Title: cytoscape.js angular2 typescript use

Body:
Have an angular4 application packed with Webpack.

want to use cytoscape.js. Need to use npm module for this: https://www.npmjs.com/package/ng2-cytoscape

I have done changes as in that page , only with a difference

import {NgCytoscapeModule} from "ng2-cytoscape";

instead of "ng2-cytoscape/dist"; (which was giving compilation errors)

Then added the following lines to app.module.ts

import {NgCytoscapeModule}      from 'ng2-cytoscape';

@NgModule({
  imports: [
    NgCytoscapeModule
  ],

Also , added the dependency to the package.json

"dependencies": {
    "ng2-cytoscape": "^0.2.0",
}

This gives the following error:

compiler.es5.js:1540 Uncaught Error: Unexpected value 'NgCytoscapeModule' imported by the module 'AppModule'. Please add a @NgModule annotation.
at syntaxError (compiler.es5.js:1540)

What is the reason? Is there another way to use cytoscape.js in Angular 2 - Typescript ?


问:
How to include the logs from the discover page on a Kibana dashboard
I was looking through some sample dashboards and i came across this picture:

https://cdn-enterprise.discourse.org/elastic/uploads/default/original/3X/1/6/169b7101acc60136b3eb4003b11c094b619083c5.png

(last visualisation on the page)

I was wondering if anyone knows how i can include the logs that i can see on the discover page on the dashboard like this example?

Many thanks in advance.

答:
Including the answer I got on a different site

Go in the discover tab, on the top right you select "save"

Go back to the dashboard, select "add" on the top right

Lastly you select the "saved search" tab (next to the "Visualization" tab), you should see what you saved earlier :slight_smile:

Original question link: https://discuss.elastic.co/t/include-logs-on-the-dashboard/92243

Can confirm this solved my problem


问:
finding loop in linked list using HashMap in java
i am writing code for lop detection in linked list using hashmap. why it goes in infinite loop?</p>

```<code>boolean hasCycle(Node head) {
    HashMap<Integer,Node> map = new HashMap<Integer,Node>();
         //<Address,data>
    if(head == null || head.next == null)
        return false;
    Node p = head;
    while(p.next!=null)
    {
        if(map.containsValue(p.next))
        {
            return true;
        }
        else
        {
            map.put(p.data,p.next);
        }
        p = p.next;
    }
    return false;
}
</code>```

答:
Have you defined .equals() and .hashCode() on your Node class? if not, it defaults to ==, and if the HashMap makes a copy of your Node as it inserts or moves it in memory, and then your equivalence would fail, because == compares memory addresses.

assuming your node class is akin to

```<code>public class Node{
    public int data;
    public Node next;
}
</code>```

you could define them as

```<code>@Override
public int hashCode(){
    int nextData=next.data;
    return data^nextData;
}
@Override
public boolean equals(Object other){
    boolean equal=false;
    if(other!=null&&other instanceof Node){
        Node otherNode=(Node)other;
        if(otherNode.data==data){
            if(otherNode.next==null&&next==null){
                equal=true;
            }else if(otherNode.next!=null&&next!=null){
                if(otherNode.next.data==next.data){
                    equal=true;
                }
            }
        }
    }
    return equal;
}
</code>```

Body:
i am writing code for lop detection in linked list using hashmap. why it goes in infinite loop?

boolean hasCycle(Node head) {
    HashMap<Integer,Node> map = new HashMap<Integer,Node>();
         //<Address,data>
    if(head == null || head.next == null)
        return false;
    Node p = head;
    while(p.next!=null)
    {
        if(map.containsValue(p.next))
        {
            return true;
        }
        else
        {
            map.put(p.data,p.next);
        }
        p = p.next;
    }
    return false;
}

Body:
Have you defined .equals() and .hashCode() on your Node class? if not, it defaults to ==, and if the HashMap makes a copy of your Node as it inserts or moves it in memory, and then your equivalence would fail, because == compares memory addresses.

assuming your node class is akin to

public class Node{
    public int data;
    public Node next;
}

you could define them as

@Override
public int hashCode(){
    int nextData=next.data;
    return data^nextData;
}
@Override
public boolean equals(Object other){
    boolean equal=false;
    if(other!=null&&other instanceof Node){
        Node otherNode=(Node)other;
        if(otherNode.data==data){
            if(otherNode.next==null&&next==null){
                equal=true;
            }else if(otherNode.next!=null&&next!=null){
                if(otherNode.next.data==next.data){
                    equal=true;
                }
            }
        }
    }
    return equal;
}


问:
Installing packages R (Ubuntu)
I have a problem with R, I haven't experienced before. Before writing here I checked the forums but couldn't solved my problem. I saw somebody experiencing this problem.

First, I use Ubuntu 16.04 and R 3.4.1 (Single candle). But I can not install any packages. First it said the directory is not writeable and if I want to create a personal library?

lib = "/usr/local/lib/R/site-library"' is not writeable Would you like
  to use a personal library instead?  (y/n)

I couldn't :( I checked forums another option was changing permission, i coded:

1. cd /usr/local/lib/R

2. sudo chmod o+w site-library

3. ls -l but it didn't work.

When I want to download a package, it installs it at /tmp folder. And i can not use it, cause when i want to open it with "library()" it says there is no package like that. I copied the package from the /tmp folder and pasted it to the folder other packages are (i didn't installed them by myself, they were there) but still it doesn't recognize the package.
I didn't experienced this with my windows pc, and a friend with Ubuntu said he is usind R and Rstudio without problem. So what is wrong with mine :( ???

答:
The problem is that r or rstudio doesn't have permission to write inside theses directories.

You should change your R_LIBS for a local directory, take a look in /etc/R/Renviron.site and uncomment the R_LIBS line or define it if needed.

Check if a R folder exists in your home like this  ~/R/x86_64-pc-linux-gnu-library/3.4, it should be your R_LIBS address. If it doesn't exist you can create one like ~/R/library/ and define the same in Renviron.site.

More information, check here or help(Startup).

Title: Installing packages R (Ubuntu)


问:
UIDocumentInteractionController doesn't take into account navigation bar tint color
One of the screens in my app shows a preview of a local image and I have an action button in the top left corner that I'm using to present document interaction options:

```<code>- (IBAction)actionButtonTapped:(id)sender {
    self.interactionController = [UIDocumentInteractionController interactionControllerWithURL:self.attachmentLocalUrl];
    self.interactionController.delegate = self;
    [self.interactionController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
}
</code>```

This works well as it shows an action sheet with a list of options, including email to send the attachment by email. When I click the email button, it displays a preview of the email message with my image in it. But there is one thing that doesn't work. I have customized the appearance of my app so that the navigation bar has the same colors throughout the app. Here is the code I run first in my app delegate's didFinishLaunchingWithOptions:

```<code>[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
[UINavigationBar appearance].barTintColor = [UIColor blueColor];
[UINavigationBar appearance].tintColor = [UIColor whiteColor];
[UINavigationBar appearance].titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
</code>```

This works well for my own view controllers, but the email preview view controller displayed by UIDocumentInteractionController has its bar button items in blue instead of white. And since the other parameters are correctly applied, especially the blue background for the navigation bar, the Cancel and Send action buttons are almost invisible.

I have tried reproducing this in a simple project but I couldn't. So obviously I'm doing something in my app to interfere with the normal customization. But I can't figure out what. Any idea how I might debug that?

答:
Here is what perfectly worked for me:</p>

```<code>func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
    UINavigationBar.appearance().barTintColor = Colors.redColor()
    UINavigationBar.appearance().tintColor = UIColor.white
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: 14, weight: UIFontWeightBold)]
    return self
}
</code>```

Body:
One of the screens in my app shows a preview of a local image and I have an action button in the top left corner that I'm using to present document interaction options:

- (IBAction)actionButtonTapped:(id)sender {
    self.interactionController = [UIDocumentInteractionController interactionControllerWithURL:self.attachmentLocalUrl];
    self.interactionController.delegate = self;
    [self.interactionController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
}

This works well as it shows an action sheet with a list of options, including email to send the attachment by email. When I click the email button, it displays a preview of the email message with my image in it. But there is one thing that doesn't work. I have customized the appearance of my app so that the navigation bar has the same colors throughout the app. Here is the code I run first in my app delegate's didFinishLaunchingWithOptions:

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
[UINavigationBar appearance].barTintColor = [UIColor blueColor];
[UINavigationBar appearance].tintColor = [UIColor whiteColor];
[UINavigationBar appearance].titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};

This works well for my own view controllers, but the email preview view controller displayed by UIDocumentInteractionController has its bar button items in blue instead of white. And since the other parameters are correctly applied, especially the blue background for the navigation bar, the Cancel and Send action buttons are almost invisible.

I have tried reproducing this in a simple project but I couldn't. So obviously I'm doing something in my app to interfere with the normal customization. But I can't figure out what. Any idea how I might debug that?

Body:
Here is what perfectly worked for me:

func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
    UINavigationBar.appearance().barTintColor = Colors.redColor()
    UINavigationBar.appearance().tintColor = UIColor.white
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: 14, weight: UIFontWeightBold)]
    return self
}


问:
bash script to handle multiple files at once
I have files with multiple extension in a folder like .txt, .update, .text. The file names are like

out1.txt,
out1.text,
out1.update,

out2.txt,
out2.text,
out2.update

and so on....My command looks like this:

```<code>./script.pl out1.txt out1.text out1.update
</code>```

I would like to put this command in the loop for every file. I have tried to use a loop like:

```<code>for i in *.{txt,text,update}
</code>```

But it takes the full name including the extension so I couldn't figure out how to deduce the specific extension files in the command.

Thanks!

答:
```<code>ext=$(awk -F\. '{ print "."$NF }' <<< $i)
fil=$(basename -s $ext $i)
</code>```

use awk to extract the extension (second delimited piece of data using ".")
Use basename -s with the extension to the get the filename without the extension

Body:
I have files with multiple extension in a folder like .txt, .update, .text. The file names are like

out1.txt,
out1.text,
out1.update,

out2.txt,
out2.text,
out2.update

and so on....My command looks like this:

./script.pl out1.txt out1.text out1.update

I would like to put this command in the loop for every file. I have tried to use a loop like:

for i in *.{txt,text,update}

But it takes the full name including the extension so I couldn't figure out how to deduce the specific extension files in the command.

Thanks!

Body:
ext=$(awk -F\. '{ print "."$NF }' <<< $i)
fil=$(basename -s $ext $i)

use awk to extract the extension (second delimited piece of data using ".")
Use basename -s with the extension to the get the filename without the extension


问:
What code for a table with colors instead of values
I have the following table on python:

What I want to do is see the table in a nicer looking way, with the cells going from red to blue depending on their value, a bit like this:

Does anyone know how to do that?

I've done this so far but don't know what to put in the vars options to make it work, nor how to make the color dependant of the values.

```<code>import numpy as np

from bokeh.plotting import figure, show, output_file #outils graphiques

import pandas as pd
df = pd.read_excel("C:/Users/a873469/Documents/Bundles/Bundles mini.xlsx")
pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 200)
print df.iloc[:20, :20]

options=

colormap = ["#2166ac", "#67a9cf", "#d1e5f0", "#fddbc7", "#ef8a62", "#b2182b"]
xname = []
yname = []
color = []

color.append(colormap)

p = figure(title="Bundles", #table title
           x_axis_location="above", # x axis on top, hover tool
           x_range=list(reversed(options)), y_range=options) # definition of x et y

p.plot_width = 800 #table size
p.plot_height = 800
p.grid.grid_line_color = None # uncolored grid
p.axis.axis_line_color = None # uncolored axis
p.axis.major_tick_line_color = None #no tick lines on axis
p.axis.major_label_text_font_size = "5pt" #label police
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = np.pi/3 #label orientation

p.rect(0.9, 0.9, #rectangles
       color='colors', line_color=None) # rectangle color

output_file("bundles.html", title="bundles.py example") # fichier d'affichage

show(p) # show the plot'
</code>```

答:
So I was trying to convert sample df to have colors this way:

```<code>df = pd.DataFrame([[1.0, 0.76, 0.71, 0.39],
              [0.76, 0.76, 0.68, 0.38],
              [0.71, 0.68, 0.71, 0.39],
              [0.39, 0.38, 0.39, 0.39],
              [0.36, 0.32, 0.34, 0.20]], columns=['Compass', "GPS","radar","ADF"])

cm = sns.light_palette('green', as_cmap=True)

s = df.style.background_gradient(cmap=cm, low=0, high=1, axis=0)
s
</code>```

But it works only "per axis" so you need to select if you want to show highest in a row or in a column, and the result looks like that:

You can see that it only shows colors per column.

Unfortunatelly Pandas doesn't support grading the whole df but thanks to this guys ( pandas style background gradient both rows and colums ) it's actually possible to achieve it anyway:

```<code>import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import colors

def background_gradient(s, m, M, cmap='PuBu', low=0, high=0):
    rng = M - m
    norm = colors.Normalize(m - (rng * low),
                            M + (rng * high))
    normed = norm(s.values)
    c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
    return ['background-color: %s' % color for color in c]

df.style.apply(background_gradient,
               cmap='PuBu',
               m=df.min().min(),
               M=df.max().max(),
               low=0,
               high=0.2)
</code>```

And the final result looks much nicer:

Is that what you were looking for?

Body:
I have the following table on python:

What I want to do is see the table in a nicer looking way, with the cells going from red to blue depending on their value, a bit like this:

Does anyone know how to do that?

I've done this so far but don't know what to put in the vars options to make it work, nor how to make the color dependant of the values.

import numpy as np

from bokeh.plotting import figure, show, output_file #outils graphiques

import pandas as pd
df = pd.read_excel("C:/Users/a873469/Documents/Bundles/Bundles mini.xlsx")
pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 200)
print df.iloc[:20, :20]

options=

colormap = ["#2166ac", "#67a9cf", "#d1e5f0", "#fddbc7", "#ef8a62", "#b2182b"]
xname = []
yname = []
color = []

color.append(colormap)

p = figure(title="Bundles", #table title
           x_axis_location="above", # x axis on top, hover tool
           x_range=list(reversed(options)), y_range=options) # definition of x et y

p.plot_width = 800 #table size
p.plot_height = 800
p.grid.grid_line_color = None # uncolored grid
p.axis.axis_line_color = None # uncolored axis
p.axis.major_tick_line_color = None #no tick lines on axis
p.axis.major_label_text_font_size = "5pt" #label police
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = np.pi/3 #label orientation

p.rect(0.9, 0.9, #rectangles
       color='colors', line_color=None) # rectangle color

output_file("bundles.html", title="bundles.py example") # fichier d'affichage

show(p) # show the plot'

Body:
So I was trying to convert sample df to have colors this way:

df = pd.DataFrame([[1.0, 0.76, 0.71, 0.39],
              [0.76, 0.76, 0.68, 0.38],
              [0.71, 0.68, 0.71, 0.39],
              [0.39, 0.38, 0.39, 0.39],
              [0.36, 0.32, 0.34, 0.20]], columns=['Compass', "GPS","radar","ADF"])

cm = sns.light_palette('green', as_cmap=True)

s = df.style.background_gradient(cmap=cm, low=0, high=1, axis=0)
s

But it works only "per axis" so you need to select if you want to show highest in a row or in a column, and the result looks like that:

You can see that it only shows colors per column.

Unfortunatelly Pandas doesn't support grading the whole df but thanks to this guys ( pandas style background gradient both rows and colums ) it's actually possible to achieve it anyway:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import colors

def background_gradient(s, m, M, cmap='PuBu', low=0, high=0):
    rng = M - m
    norm = colors.Normalize(m - (rng * low),
                            M + (rng * high))
    normed = norm(s.values)
    c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
    return ['background-color: %s' % color for color in c]

df.style.apply(background_gradient,
               cmap='PuBu',
               m=df.min().min(),
               M=df.max().max(),
               low=0,
               high=0.2)

And the final result looks much nicer:

Is that what you were looking for?


问:
How can I check if the user char input is contained in 2 Strings?
The question seems confusing. The program does this: It asks the user for input in char form and then stores it in 2 variables. There are 2 Strings which I've already created. One contains the letters a-g and the other for the letters h-o. These are basically 2 routes which a user can go, but the user can't put for example "a" as start and "h" as destination since they are from a different String. He/She has to have the start and destination in the same String. If the start is and destination aren't in the same String, there will be an error.

This method I have looks as follows:

```<code>private void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    char start = ' ';
    char ziel = ' ';
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    while((a == 0 && b == 0) || (c == 0 && d ==0)){

        System.out.println("Put in a starting point please: ");
        start = in.next().charAt(0);

        while(start != 'a' && start != 'A' && start != 'b' && start != 'B' &&
              start != 'c' && start != 'C' && start != 'd' && start != 'D' &&
              start != 'e' && start != 'E' && start != 'f' && start != 'F' &&
              start != 'g' && start != 'G' && start != 'h' && start != 'H' &&
              start != 'i' && start != 'I' && start != 'j' && start != 'J' &&
              start != 'k' && start != 'K' && start != 'l' && start != 'L' &&
              start != 'm' && start != 'M' && start != 'n' && start != 'N' &&
              start != 'o' && start != 'O') {
            System.out.println("Put in a correct starting point please: ");
            start = in.next().charAt(0);
        }

        System.out.println("Put in a destination point please: ");
        ziel = in.next().charAt(0);

        while(ziel != 'a' && ziel != 'A' && ziel != 'b' && ziel != 'B' &&
              ziel != 'c' && ziel != 'C' && ziel != 'd' && ziel != 'D' &&
              ziel != 'e' && ziel != 'E' && ziel != 'f' && ziel != 'F' &&
              ziel != 'g' && ziel != 'G' && ziel != 'h' && ziel != 'H' &&
              ziel != 'i' && ziel != 'I' && ziel != 'j' && ziel != 'J' &&
              ziel != 'k' && ziel != 'K' && ziel != 'l' && ziel != 'L' &&
              ziel != 'm' && ziel != 'M' && ziel != 'n' && ziel != 'N' &&
              ziel != 'o' && ziel != 'O') {
            System.out.println("Put in a correct destination point please: ");
            ziel = in.next().charAt(0);
        }

        a = bereich1.indexOf(start);
        b = bereich2.indexOf(ziel);

        c = bereich2.indexOf(start);
        d = bereich1.indexOf(ziel);

    }
}
</code>```

I tried using .indexOf() today, which I have here with this while loop:

```<code>while((a == 0 && b == 0) || (c == 0 && d ==0)){
</code>```

And these variables:

```<code>a = bereich1.indexOf(start);
b = bereich2.indexOf(ziel);

c = bereich2.indexOf(start);
d = bereich1.indexOf(ziel);
</code>```

I just can't get it to work and it's been working my mind for a couple of days. Any help or pinpointing in the right direction is greatly appreciated. Please let me know if there is anything insufficient given by me or if you need any more information.

Thank you.

答:
You can replace : </p>

```<code>while(start != 'a' && start != 'A' && start != 'b' && start != 'B' &&
          start != 'c' && start != 'C' && start != 'd' && start != 'D' &&
          start != 'e' && start != 'E' && start != 'f' && start != 'F' &&
          start != 'g' && start != 'G' && start != 'h' && start != 'H' &&
          start != 'i' && start != 'I' && start != 'j' && start != 'J' &&
          start != 'k' && start != 'K' && start != 'l' && start != 'L' &&
          start != 'm' && start != 'M' && start != 'n' && start != 'N' &&
          start != 'o' && start != 'O') {
       System.out.println("Put in a correct starting point please: ");
       start = in.next().charAt(0);
}
</code>```

<p>By : </p>

```<code>//matches a letter between a and o in lower case or not
while (!start.matches("\\b[a-oA-O]\\b")) {
       System.out.println("Put in a correct starting point please: ");
       start = in.next().charAt(0);
}
</code>```

Body:
The question seems confusing. The program does this: It asks the user for input in char form and then stores it in 2 variables. There are 2 Strings which I've already created. One contains the letters a-g and the other for the letters h-o. These are basically 2 routes which a user can go, but the user can't put for example "a" as start and "h" as destination since they are from a different String. He/She has to have the start and destination in the same String. If the start is and destination aren't in the same String, there will be an error.

This method I have looks as follows:

private void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    char start = ' ';
    char ziel = ' ';
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    while((a == 0 && b == 0) || (c == 0 && d ==0)){

        System.out.println("Put in a starting point please: ");
        start = in.next().charAt(0);

        while(start != 'a' && start != 'A' && start != 'b' && start != 'B' &&
              start != 'c' && start != 'C' && start != 'd' && start != 'D' &&
              start != 'e' && start != 'E' && start != 'f' && start != 'F' &&
              start != 'g' && start != 'G' && start != 'h' && start != 'H' &&
              start != 'i' && start != 'I' && start != 'j' && start != 'J' &&
              start != 'k' && start != 'K' && start != 'l' && start != 'L' &&
              start != 'm' && start != 'M' && start != 'n' && start != 'N' &&
              start != 'o' && start != 'O') {
            System.out.println("Put in a correct starting point please: ");
            start = in.next().charAt(0);
        }

        System.out.println("Put in a destination point please: ");
        ziel = in.next().charAt(0);

        while(ziel != 'a' && ziel != 'A' && ziel != 'b' && ziel != 'B' &&
              ziel != 'c' && ziel != 'C' && ziel != 'd' && ziel != 'D' &&
              ziel != 'e' && ziel != 'E' && ziel != 'f' && ziel != 'F' &&
              ziel != 'g' && ziel != 'G' && ziel != 'h' && ziel != 'H' &&
              ziel != 'i' && ziel != 'I' && ziel != 'j' && ziel != 'J' &&
              ziel != 'k' && ziel != 'K' && ziel != 'l' && ziel != 'L' &&
              ziel != 'm' && ziel != 'M' && ziel != 'n' && ziel != 'N' &&
              ziel != 'o' && ziel != 'O') {
            System.out.println("Put in a correct destination point please: ");
            ziel = in.next().charAt(0);
        }

        a = bereich1.indexOf(start);
        b = bereich2.indexOf(ziel);

        c = bereich2.indexOf(start);
        d = bereich1.indexOf(ziel);

    }
}

I tried using .indexOf() today, which I have here with this while loop:

while((a == 0 && b == 0) || (c == 0 && d ==0)){

And these variables:

a = bereich1.indexOf(start);
b = bereich2.indexOf(ziel);

c = bereich2.indexOf(start);
d = bereich1.indexOf(ziel);

I just can't get it to work and it's been working my mind for a couple of days. Any help or pinpointing in the right direction is greatly appreciated. Please let me know if there is anything insufficient given by me or if you need any more information.

Thank you.

Body:
You can replace :

while(start != 'a' && start != 'A' && start != 'b' && start != 'B' &&
          start != 'c' && start != 'C' && start != 'd' && start != 'D' &&
          start != 'e' && start != 'E' && start != 'f' && start != 'F' &&
          start != 'g' && start != 'G' && start != 'h' && start != 'H' &&
          start != 'i' && start != 'I' && start != 'j' && start != 'J' &&
          start != 'k' && start != 'K' && start != 'l' && start != 'L' &&
          start != 'm' && start != 'M' && start != 'n' && start != 'N' &&
          start != 'o' && start != 'O') {
       System.out.println("Put in a correct starting point please: ");
       start = in.next().charAt(0);
}

By :

//matches a letter between a and o in lower case or not
while (!start.matches("\\b[a-oA-O]\\b")) {
       System.out.println("Put in a correct starting point please: ");
       start = in.next().charAt(0);
}


问:
Is there a way to make angular 2/4 material tab widths be based on the length of the label instead of cutting off?
I am using angular2 material, I have the issue where some of my tab titles are long, which cuts off the icon that is at the end of the title text. (a small x). In my code below, notice how some of the tabs do not have an x to the right due to the tabs cutting off. Is there some way to make it so that the tab is sized so that it displays the entire label?

I prefer not to do a limitTo or reduce the length of the tab title.

```<code><md-tab-group>
  <md-tab>
    <ng-template md-tab-label>
        Name of a Tab 1
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
  <md-tab>
    <ng-template md-tab-label>
        The naming of tab is so long 2
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
  <md-tab>
    <ng-template md-tab-label>
        Name of a Tab 3
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
  <md-tab>
    <ng-template md-tab-label>
        Name of a Tab 4
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
  <md-tab>
    <ng-template md-tab-label>
        Long Name Of Some Tab 5
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
  <md-tab>
    <ng-template md-tab-label>
        This is a special tab 6
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
</md-tab-group>
</code>```

I have a plunkr that illustrates my issue:
    https://plnkr.co/edit/sjrZAiKg3ZdAq8xvGuPp?p=preview

If this is not possible, that is an acceptable answer.

答:
To fix your problem, add the following code to your styles.css file on the root of your app:

```<code>.mat-tab-label {
    display: flex;
}
</code>```

This is a plunkr with the fix:

Angular 2 Material Demo for tab with close icon - Plunkr

Body:
I am using angular2 material, I have the issue where some of my tab titles are long, which cuts off the icon that is at the end of the title text. (a small x). In my code below, notice how some of the tabs do not have an x to the right due to the tabs cutting off. Is there some way to make it so that the tab is sized so that it displays the entire label?

I prefer not to do a limitTo or reduce the length of the tab title.

<md-tab-group>
  <md-tab>
    <ng-template md-tab-label>
        Name of a Tab 1
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
  <md-tab>
    <ng-template md-tab-label>
        The naming of tab is so long 2
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
  <md-tab>
    <ng-template md-tab-label>
        Name of a Tab 3
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
  <md-tab>
    <ng-template md-tab-label>
        Name of a Tab 4
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
  <md-tab>
    <ng-template md-tab-label>
        Long Name Of Some Tab 5
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
  <md-tab>
    <ng-template md-tab-label>
        This is a special tab 6
        <md-icon>close</md-icon>
    </ng-template>
    Content 1
  </md-tab>
</md-tab-group>

I have a plunkr that illustrates my issue:
    https://plnkr.co/edit/sjrZAiKg3ZdAq8xvGuPp?p=preview

If this is not possible, that is an acceptable answer.

Body:
To fix your problem, add the following code to your styles.css file on the root of your app:

.mat-tab-label {
    display: flex;
}

This is a plunkr with the fix:

Angular 2 Material Demo for tab with close icon - Plunkr


问:
BDD - Test pass on chrome but not on Phantomjs
I have a web app built by Django, front-end is built by React. I tried to test bdd with behave and selenium. I run a test with Chrome web driver and phantomjs one but the tests only passed using chrome. I captured a screenshot when it runs on phantom and saw that the page is not fully rendered. Please give some suggestions about this issue. Do I need do further configuration to test with phantomjs. Thank you. </p>

答:
This is a common problem with PhantomJS (the page not being fully rendered), and often isn't something that can be remedied with explicit/implicit waits. Add a long (5 second) sleep to your code and take another screenshot.

If the page is fully rendered, follow @Alex Lucaci's instructions for adding (ideally) explicit waits.

If the page still isn't fully rendered, PhantomJS just wont work for you in this case. Personally, I would advise against using PhantomJS at all, as it is problematic in a myriad of ways, but also because why would you test on a browser that literally no one uses as their actual browser?


问:
I can't see my changes in Windows Form Application
I am working on windows form app in C#. 1 week ago I created a form and I add some tools. Today I opened same application. Now, I add new button but when I run it I can't see. Previous version of the application is shown. For example, there was a DataGridView and I changed it with listView but when I run the program I still see the DataGridView. Why this is happening?</p>

答: Rebuild your project. Build - RebuildProjectName


问:
read and write in excel file with python
I am trying to read the cell of a excel file in python, change its value and save it. If I do not have the line from xlutils.copy import copy in code, it recognizes workbook.sheeets(), but otherwise it says

    AttributeError: 'Workbook' object has no attribute 'sheets'
```

<p>Here is my code:</p>

<pre class="lang-py prettyprint-override"><code>    from xlutils.copy import copy

    import xlrd
    st = xlwt.easyxf('pattern: pattern solid;')
    rb = xlrd.open_workbook('00-17.xlsx')

    workbook = copy(rb)
    for sheet in workbook.sheets():
        for row in range(sheet.nrows):

            current_value = sheet.cell(row,3).value
            if(current_value == '1' ) :
                st.pattern.pattern_fore_colour = 5

                for column in [0,2,3]:
                    value = sheet.cell(row, column).value

                    print value
                    sheet.write(row, column, value,st)
    workbook.save('1.xlsx')

</code>```

答:
I believe you may have to use load_workbook() method first. Check out the link Print Excel workbook using python it will probably help.

Can you try doing it with workbook = xlrd.open_workbook('00-17.xlsx') and remove the line workbook = copy(rb)?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to read the cell of a excel file in python, change its value and save it. If I do not have the line from xlutils.copy import copy in code, it recognizes workbook.sheeets(), but otherwise it says

    AttributeError: 'Workbook' object has no attribute 'sheets'

Here is my code:

    from xlutils.copy import copy

    import xlrd
    st = xlwt.easyxf('pattern: pattern solid;')
    rb = xlrd.open_workbook('00-17.xlsx')

    workbook = copy(rb)
    for sheet in workbook.sheets():
        for row in range(sheet.nrows):

            current_value = sheet.cell(row,3).value
            if(current_value == '1' ) :
                st.pattern.pattern_fore_colour = 5

                for column in [0,2,3]:
                    value = sheet.cell(row, column).value

                    print value
                    sheet.write(row, column, value,st)
    workbook.save('1.xlsx')


答:
You can use the contains() function to check if the either of the strings contain the input. From there you can determine which string the user started with and then check against that one to make sure they enter a destination in the same string.

```<code>private void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    char start = ' ';
    char ziel = ' ';

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    System.out.println("Put in a starting point please: ");
    start = in.next().charAt(0);

    // make sure the starting character exists in either string
    while(!bereich1.contains(start) && !bereich2.contains(start)) {
        System.out.println("Put in a correct starting point please: ");
        start = in.next().charAt(0);
    }

    // determine which string the starting character exists in
    String chosen = bereich1.contains(start) ? bereich1 : bereich2;

    System.out.println("Put in a destination point please: ");
    ziel = in.next().charAt(0);

    // make sure the ending character exists in the chosen string
    while(!chosen.contains(ziel)) {
        System.out.println("Put in a correct destination point please: ");
        ziel = in.next().charAt(0);
    }
}
</code>```

Title: How can I check if the user char input is contained in 2 Strings?

Body:
You can use the contains() function to check if the either of the strings contain the input. From there you can determine which string the user started with and then check against that one to make sure they enter a destination in the same string.

private void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    char start = ' ';
    char ziel = ' ';

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    System.out.println("Put in a starting point please: ");
    start = in.next().charAt(0);

    // make sure the starting character exists in either string
    while(!bereich1.contains(start) && !bereich2.contains(start)) {
        System.out.println("Put in a correct starting point please: ");
        start = in.next().charAt(0);
    }

    // determine which string the starting character exists in
    String chosen = bereich1.contains(start) ? bereich1 : bereich2;

    System.out.println("Put in a destination point please: ");
    ziel = in.next().charAt(0);

    // make sure the ending character exists in the chosen string
    while(!chosen.contains(ziel)) {
        System.out.println("Put in a correct destination point please: ");
        ziel = in.next().charAt(0);
    }
}


问:
Error in asp.net c# code (mysql database connection)
My code is to update a record if it already exists in database else insert as a new record.

My code is as follows:

```<code>protected void Button3_Click(object sender, EventArgs e)
    {

        OdbcConnection MyConnection = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
        MyConnection.Open();
        String MyString = "select fil_no,orderdate from temp_save where fil_no=? and orderdate=?";
        OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
        MyCmd.Parameters.AddWithValue("", HiddenField4.Value);
        MyCmd.Parameters.AddWithValue("", TextBox3.Text);
        using (OdbcDataReader MyReader4 = MyCmd.ExecuteReader())
        {
            //**
            if (MyReader4.Read())
            {

                    String MyString1 = "UPDATE temp_save SET order=? where fil_no=? AND orderdate=?";
                    OdbcCommand MyCmd1 = new OdbcCommand(MyString1, MyConnection);
                    MyCmd1.Parameters.AddWithValue("", Editor1.Content.ToString());
                    MyCmd1.Parameters.AddWithValue("", HiddenField1.Value);
                    MyCmd1.Parameters.AddWithValue("", TextBox3.Text);
                    MyCmd1.ExecuteNonQuery();
                }

            else
            {

                // set the SQL string
                String strSQL = "INSERT INTO temp_save (fil_no,order,orderdate) " +
                "VALUES (?,?,?)";

                // Create the Command and set its properties
                OdbcCommand objCmd = new OdbcCommand(strSQL, MyConnection);
                objCmd.Parameters.AddWithValue("", HiddenField4.Value);
                objCmd.Parameters.AddWithValue("", Editor1.Content.ToString());
                objCmd.Parameters.AddWithValue("", TextBox3.Text);

                // execute the command
                objCmd.ExecuteNonQuery();

            }

        }
    }
</code>```

I am getting the error as:

```<code>ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.51-community]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order,orderdate) VALUES ('04050040272009','      &' at line 1
</code>```

The datatype for fields in table temp_save are:

```<code>fil_no-->INT(15)( to store a 15 digit number)
order-->LONGTEXT(to store contents from HTMLEditor(ajax control))
orderdate-->DATE(to store date)
</code>```

Please help me to resolve my error.

答:
i would try brackets in case ... that's the way it works in ms sql server .. probablly the same in mySql </p>

```<code>String MyString1 = "UPDATE temp_save SET [order]=? where fill .... ";
</code>```

Body:
My code is to update a record if it already exists in database else insert as a new record.

My code is as follows:

protected void Button3_Click(object sender, EventArgs e)
    {

        OdbcConnection MyConnection = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
        MyConnection.Open();
        String MyString = "select fil_no,orderdate from temp_save where fil_no=? and orderdate=?";
        OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
        MyCmd.Parameters.AddWithValue("", HiddenField4.Value);
        MyCmd.Parameters.AddWithValue("", TextBox3.Text);
        using (OdbcDataReader MyReader4 = MyCmd.ExecuteReader())
        {
            //**
            if (MyReader4.Read())
            {

                    String MyString1 = "UPDATE temp_save SET order=? where fil_no=? AND orderdate=?";
                    OdbcCommand MyCmd1 = new OdbcCommand(MyString1, MyConnection);
                    MyCmd1.Parameters.AddWithValue("", Editor1.Content.ToString());
                    MyCmd1.Parameters.AddWithValue("", HiddenField1.Value);
                    MyCmd1.Parameters.AddWithValue("", TextBox3.Text);
                    MyCmd1.ExecuteNonQuery();
                }

            else
            {

                // set the SQL string
                String strSQL = "INSERT INTO temp_save (fil_no,order,orderdate) " +
                "VALUES (?,?,?)";

                // Create the Command and set its properties
                OdbcCommand objCmd = new OdbcCommand(strSQL, MyConnection);
                objCmd.Parameters.AddWithValue("", HiddenField4.Value);
                objCmd.Parameters.AddWithValue("", Editor1.Content.ToString());
                objCmd.Parameters.AddWithValue("", TextBox3.Text);

                // execute the command
                objCmd.ExecuteNonQuery();

            }

        }
    }

I am getting the error as:

ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.51-community]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order,orderdate) VALUES ('04050040272009','      &' at line 1

The datatype for fields in table temp_save are:

fil_no-->INT(15)( to store a 15 digit number)
order-->LONGTEXT(to store contents from HTMLEditor(ajax control))
orderdate-->DATE(to store date)

Please help me to resolve my error.

Body:
i would try brackets in case ... that's the way it works in ms sql server .. probablly the same in mySql

String MyString1 = "UPDATE temp_save SET [order]=? where fill .... ";


问:
How to limit floats generated by Quickcheck to a range?
I would like to generate random floats for Quickcheck that are limited to a certain range such as 0.0 to 1.0 for testing functions working on probabilities. I would like to be able to do something where this would be successful:</p>

```<code>quickcheck! {
    fn prop(x: f64, y: f64) -> bool {
        assert!(x <= 1.0);
        assert!(y <= 1.0);

        (x * y < x) && (x * y < y)
    }
}
</code>```

答:
Create a new type that represents your desired range, then implement quickcheck::Arbitrary for it:

```<code>#[macro_use]
extern crate quickcheck;

#[derive(Debug, Copy, Clone)]
struct Probability(f64);

impl quickcheck::Arbitrary for Probability {
    fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self {
        Probability(g.gen_range(0.0, 1.0))
    }
}

quickcheck! {
    fn prop(x: Probability, y: Probability) -> bool {
        let x = x.0;
        let y = y.0;

        assert!(x <= 1.0);
        assert!(y <= 1.0);

        (x * y < x) && (x * y < y)
    }
}
</code>```

Arbitrary is passed a type that implements quickcheck::Gen, which is a light wrapper on top of rand::Rng.

Note that Rng::gen_range has an exclusive upper bound, so this example isn't exactly what you want, but it shows the process.

Body:
I would like to generate random floats for Quickcheck that are limited to a certain range such as 0.0 to 1.0 for testing functions working on probabilities. I would like to be able to do something where this would be successful:

quickcheck! {
    fn prop(x: f64, y: f64) -> bool {
        assert!(x <= 1.0);
        assert!(y <= 1.0);

        (x * y < x) && (x * y < y)
    }
}

Body:
Create a new type that represents your desired range, then implement quickcheck::Arbitrary for it:

#[macro_use]
extern crate quickcheck;

#[derive(Debug, Copy, Clone)]
struct Probability(f64);

impl quickcheck::Arbitrary for Probability {
    fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self {
        Probability(g.gen_range(0.0, 1.0))
    }
}

quickcheck! {
    fn prop(x: Probability, y: Probability) -> bool {
        let x = x.0;
        let y = y.0;

        assert!(x <= 1.0);
        assert!(y <= 1.0);

        (x * y < x) && (x * y < y)
    }
}

Arbitrary is passed a type that implements quickcheck::Gen, which is a light wrapper on top of rand::Rng.

Note that Rng::gen_range has an exclusive upper bound, so this example isn't exactly what you want, but it shows the process.


问:
Python function scope
I have a question about the scope in python functions. I've included an example that demonstrates the issue I am having.

fun0 redefines the first entry in varible c's list. This change is reflected outside of fun0, even when I don't return any values from fun0.

fun1 redefines the variable c entirely, but the change isn't reflected outside of fun1. Similarly, fun2 redefines c, and the change isn't reflected outside of fun2.

My question is, why does fun0 modify val3 in the main function, while fun1 and fun2 don't modify val4 and val7, respectively?

```<code>def fun0(a, b, c):
    c[0] = a[0] + b[0]
    return

def fun1(a, b, c):
    c = a[0] + b[0]
    return

def fun2(a, b, c):
    c = a + b
    return

def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print val3

    val4 = []
    fun1(val1, val2, val4)
    print val4

    val5 = 1
    val6 = 1
    val7 = 0
    fun2(val5, val6, val7)
    print val7
    return

if __name__=='__main__':
    main()
</code>```

答: Technically when you pass an argument to a function you are passing a copy, not the original. Now there is a difference between passing a list and passing variable. A list holds a reference to other object while a variable holds a value. Therefore when passing a list even if it gets copied it still is referencing the same objects and can be changed within the function, but when passing a variable the copied object has nothing to do with the original. Hope this make sense.</p>

Title: Python function scope

Body:
I have a question about the scope in python functions. I've included an example that demonstrates the issue I am having.

fun0 redefines the first entry in varible c's list. This change is reflected outside of fun0, even when I don't return any values from fun0.

fun1 redefines the variable c entirely, but the change isn't reflected outside of fun1. Similarly, fun2 redefines c, and the change isn't reflected outside of fun2.

My question is, why does fun0 modify val3 in the main function, while fun1 and fun2 don't modify val4 and val7, respectively?

def fun0(a, b, c):
    c[0] = a[0] + b[0]
    return

def fun1(a, b, c):
    c = a[0] + b[0]
    return

def fun2(a, b, c):
    c = a + b
    return

def main():
    val1 = ['one']
    val2 = ['two']
    val3 = ['']
    fun0(val1, val2, val3)
    print val3

    val4 = []
    fun1(val1, val2, val4)
    print val4

    val5 = 1
    val6 = 1
    val7 = 0
    fun2(val5, val6, val7)
    print val7
    return

if __name__=='__main__':
    main()


问:
Double Clicking a shell script on Mac
i have a small script that runs a jar file :

```<code>#!/bin/bash

prefix="foo";
name=`ls ${prefix}*.jar`;
echo $name;
java -jar $name prop1.properties prop2.properties
</code>```

when i run it in the terminal using ./myscript.sh, it works fine and the jar file executes, but when i rename it in myscript.command and double click it, i have this error :

```<code>ls: foo*.jar : No such file or directory
</code>```

I saw that apparently a .command file opens a terminal at the root directory, so I tried finding the directory containing myscript.command using that :

```<code>dir = 'find <dir> -maxdepth 1 -type d -name '*myDirContainingJar*' -print -quit'
cd $dir
</code>```

but dir is just blank, any ideas ???

答: The problem with your script is that it runs with a different working directory than you tested it with. When you do ls something in a script, the script looks in the current working directory (where you cded last in case you're in a terminal), not in the directory the script is in. In general, when writing scripts like this you should use the full path of the file you're referring to or figure out the directory of the script and point to the file relative to that. One solution works in Bash, but it might not in the shell you're using.

Title: Double Clicking a shell script on Mac

Body:
i have a small script that runs a jar file :

#!/bin/bash

prefix="foo";
name=`ls ${prefix}*.jar`;
echo $name;
java -jar $name prop1.properties prop2.properties

when i run it in the terminal using ./myscript.sh, it works fine and the jar file executes, but when i rename it in myscript.command and double click it, i have this error :

ls: foo*.jar : No such file or directory

I saw that apparently a .command file opens a terminal at the root directory, so I tried finding the directory containing myscript.command using that :

dir = 'find <dir> -maxdepth 1 -type d -name '*myDirContainingJar*' -print -quit'
cd $dir

but dir is just blank, any ideas ???


问:
QUndoStack remove specific command
How can I remove a specific command from a QUndoStack?

This command can be given by its index or pointer.

答:
If you are using Qt 5.9, the QUndoStack::command(int index) and QUndoCommand::setObsolete(bool obsolete) functions are probably what you are looking for. The relevant docs from the QUndoStack::redo() command provide the explanation for how an obsoleted command is handled:

If QUndoCommand::isObsolete() returns true for the current command, then the command will be deleted from the stack. Additionally, if the clean index is greater than or equal to the current command index, then the clean index is reset.

Title: QUndoStack remove specific command


问:
Node.js Lambda Function "response is invalid" Amazon Alexa
UPDATE: I had a mistake on my http request endpoint. I had not set the appropriate authentication options so that fixed a lot of errors possibly this specific one.

My question is similar to one here:

Node.js Lambda function returns "The response is invalid" back to Alexa Service Simulator from REST call

However the solution to that question does not solve my problem. So I make an http request call to an xsjs service in Hana cloud. I am getting the 'response is invalid' error message. I can't see why. Here is my function:

```<code> // Create a web request and handle the response.
function httpGet(query, callback) {

    console.log("/n QUERY: "+ query);

    var host = 'datacloudyd070518trial.hanatrial.ondemand.com';
    var path = '/LocationInformation/getLocationInfo.xsjs?location=';
    var hostname = 'https://' + host + path + query;

    var auth = 'user1:D1anafer';

    var req = http.request({'hostname': hostname,
                            'auth': auth
                        }, (res) => {

    var body = '';

        res.on('data', (d) => {
            body += JSON.stringify(d);
        });

        res.on('end', function () {
            callback(body);
        });

    });

    req.end();

    req.on('error', (e) => {
        console.error(e);
    });

}
</code>```

And the function that calls it:

```<code>'getNewsIntent': function () {

    //self = this;

    httpGet(location, function (response) {

        // Parse the response into a JSON object ready to be formatted.
        //var output = JSON.parse(response);
        //output = output['change'];
        var output = response;

        var cardTitle = location;
        var cardContent = output;

        alexa.emit(':tellWithCard', output, cardTitle, cardContent);

    });

},
</code>```

Thank You
-Diana

答:
Inside your AWS account go to your Lambda function and click on the monitoring tab, where you should see "View Logs in Cloudwatch" in the right hand corner. If you click that link and you should see the errors that are being produced.

You can also use console.log() to log any information being returned from your REST api, which will be logged in cloudwatch and can help you see where your errors are.

Body:
UPDATE: I had a mistake on my http request endpoint. I had not set the appropriate authentication options so that fixed a lot of errors possibly this specific one.

My question is similar to one here:

Node.js Lambda function returns "The response is invalid" back to Alexa Service Simulator from REST call

However the solution to that question does not solve my problem. So I make an http request call to an xsjs service in Hana cloud. I am getting the 'response is invalid' error message. I can't see why. Here is my function:

 // Create a web request and handle the response.
function httpGet(query, callback) {

    console.log("/n QUERY: "+ query);

    var host = 'datacloudyd070518trial.hanatrial.ondemand.com';
    var path = '/LocationInformation/getLocationInfo.xsjs?location=';
    var hostname = 'https://' + host + path + query;

    var auth = 'user1:D1anafer';

    var req = http.request({'hostname': hostname,
                            'auth': auth
                        }, (res) => {

    var body = '';

        res.on('data', (d) => {
            body += JSON.stringify(d);
        });

        res.on('end', function () {
            callback(body);
        });

    });

    req.end();

    req.on('error', (e) => {
        console.error(e);
    });

}

And the function that calls it:

'getNewsIntent': function () {

    //self = this;

    httpGet(location, function (response) {

        // Parse the response into a JSON object ready to be formatted.
        //var output = JSON.parse(response);
        //output = output['change'];
        var output = response;

        var cardTitle = location;
        var cardContent = output;

        alexa.emit(':tellWithCard', output, cardTitle, cardContent);

    });

},

Thank You
-Diana


问:
How can I download all images in single click(Download all) by using PHP
If I click that Download All I need to download all that image to my local system

```<code><div>
  <img src='image1.jpg'/>
  <img src='image2.jpg'/>
  <img src='image3.jpg'/>
  <button> Download All </button>
</div>
</code>```

Give me some solution for this

答: You can just left click on the website and select 'Save as..' (in Chrome) /  'save page as' (in Firefox). You will get all the images in that page in a folder. You do not have to use any scripts or any CLI.</p>

Body:
If I click that Download All I need to download all that image to my local system

  <button> Download All </button>

Give me some solution for this


问:
How do I extend this mergeWords function to any number of strings?
Following is the mergeWords function.

```<code>mergeWords [] [] = []
mergeWords [] (y:ys) = y:'\n':(mergeWords [] ys)
mergeWords (x:xs) [] = x:'\n':(mergeWords xs [])
mergeWords (x:xs) (y:ys) = x:y:'\n':(mergeWords xs ys)
</code>```

If applied on mergeWords "hello" "world" it gives

```<code>"hw\neo\nlr\nll\nod\n"
</code>```

I can't figure out how to extend this to list of strings. Like applying it to 3 strings should first take first character of each of the strings and then put a '\n' and then the second character and so on.

答:
The puzzle is effectively to merge a list of words, a character at a time, into lines with trailing newline characters.

```<code>mergeWords :: [String] -> String
</code>```

We need to take a list like

```<code>[ "hello"
, "jim"
, "nice"
, "day"
]
</code>```

and rearrange it into the lists of things at a given position

```<code>[ "hjnd"
, "eiia"
, "lmcy"
, "le"
, "o"
]
</code>```

That's what the library function transpose does.

And then we need to make a single string which treats those as lines, separated by newlines. Which is what unlines does.

So

```<code>mergeWords = unlines . transpose
</code>```

and we're done.

Body:
Following is the mergeWords function.

mergeWords [] [] = []
mergeWords [] (y:ys) = y:'\n':(mergeWords [] ys)
mergeWords (x:xs) [] = x:'\n':(mergeWords xs [])
mergeWords (x:xs) (y:ys) = x:y:'\n':(mergeWords xs ys)

If applied on mergeWords "hello" "world" it gives

"hw\neo\nlr\nll\nod\n"

I can't figure out how to extend this to list of strings. Like applying it to 3 strings should first take first character of each of the strings and then put a '\n' and then the second character and so on.

Body:
The puzzle is effectively to merge a list of words, a character at a time, into lines with trailing newline characters.

mergeWords :: [String] -> String

We need to take a list like

[ "hello"
, "jim"
, "nice"
, "day"
]

and rearrange it into the lists of things at a given position

[ "hjnd"
, "eiia"
, "lmcy"
, "le"
, "o"
]

That's what the library function transpose does.

And then we need to make a single string which treats those as lines, separated by newlines. Which is what unlines does.

So

mergeWords = unlines . transpose

and we're done.


问:
How to print the time with AM/PM format in iPhone?
I want to print the time from date picker but with the AM/PM. I can print the time, but it never prints the AM/PM. How can I do this?</p>

答:
You can set your DateFormatter amSymbol and pmSymbol as follow:

Xcode 8.3 • Swift 3.1

```<code>let formatter = DateFormatter()
formatter.dateFormat = "h:mm a 'on' MMMM dd, yyyy"
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"

let dateString = formatter.string(from: Date())
print(dateString)   // "4:44 PM on June 23, 2016\n"
</code>```

Edit:
Objective C Code

```<code>NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.timeZone = [NSTimeZone systemTimeZone];
df.AMSymbol = @"AM";
df.PMSymbol = @"PM";
df.dateFormat = "h:mm a 'on' MMMM dd, yyyy"
NSString *stringDate = [df stringFromDate:dateFromString];
</code>```

Ref link:
https://stackoverflow.com/a/31469237/2905967

Body:
You can set your DateFormatter amSymbol and pmSymbol as follow:

Xcode 8.3 • Swift 3.1

let formatter = DateFormatter()
formatter.dateFormat = "h:mm a 'on' MMMM dd, yyyy"
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"

let dateString = formatter.string(from: Date())
print(dateString)   // "4:44 PM on June 23, 2016\n"

Edit:
Objective C Code

NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.timeZone = [NSTimeZone systemTimeZone];
df.AMSymbol = @"AM";
df.PMSymbol = @"PM";
df.dateFormat = "h:mm a 'on' MMMM dd, yyyy"
NSString *stringDate = [df stringFromDate:dateFromString];

Ref link:
https://stackoverflow.com/a/31469237/2905967


问:
Prevent expansion of wildcards in non-quoted python script argument when running in UNIX environment
I have a python script that I'd like to supply with an argument (usually) containing wildcards, referring to a series of files that I'd like to do stuff with. Example here:

```<code>#!/usr/bin/env python

import argparse
import glob

parser = argparse.ArgumentParser()
parser.add_argument('-i', action="store", dest="i")
results = parser.parse_args()
print 'argument i is: ', results.i
list_of_matched_files = glob.glob(results.i)
</code>```

In this case, everything works great if the user adds quotes to the passed argument like so:

```<code>./test_script.py -i "foo*.txt"
</code>```

...but often times the users forget to add quotes to the argument and are stumped when the list only contains the first match because UNIX already expanded the list and argparse only then gets the first list element.

Is there a way (within the script) to prevent UNIX from expanding the list before passing it to python? Or maybe even just to test if the argument doesn't contain quotes and then warn the user?

答:
You can disable the expansion using set -f from the command line. (re-enable with set +f).

As jwodder correctly says though, this happens before the script is run, so the only way I can think of to do this is to wrap it with a shell script that disables expansion temporarily, runs the python script, and re-enables expansion. Preventing UNIX from expanding the list before passing it to python is not possible.

Body:
I have a python script that I'd like to supply with an argument (usually) containing wildcards, referring to a series of files that I'd like to do stuff with. Example here:

#!/usr/bin/env python

import argparse
import glob

parser = argparse.ArgumentParser()
parser.add_argument('-i', action="store", dest="i")
results = parser.parse_args()
print 'argument i is: ', results.i
list_of_matched_files = glob.glob(results.i)

In this case, everything works great if the user adds quotes to the passed argument like so:

./test_script.py -i "foo*.txt"

...but often times the users forget to add quotes to the argument and are stumped when the list only contains the first match because UNIX already expanded the list and argparse only then gets the first list element.

Is there a way (within the script) to prevent UNIX from expanding the list before passing it to python? Or maybe even just to test if the argument doesn't contain quotes and then warn the user?


问:
how to get the previous 3 months in php
how to get the previous 3 months in php ex(If i say DEC.. It should display the previous 3 months i.e., OCT NOV DEC)</p>

答:
You can use the strtotime function like this:

```<code>echo date('M', strtotime('-3 month'));
</code>```

So you specify previous dates with minus sign.

```<code>echo date('M', strtotime('0 month'));
echo date('M', strtotime('-1 month'));
echo date('M', strtotime('-2 month'));
echo date('M', strtotime('-3 month'));
</code>```

Results:

```<code>Dec
Nov
Oct
Sep
</code>```

You can do the same if you are using a loop like this:

```<code>for ($i = -3; $i <= 0; $i++){
  echo date('M', strtotime("$i month"));
}
</code>```

Results:

```<code>Sep
Oct
Nov
Dec
</code>```

Check out the documentation too see many other friendly date and time keywords strtotime supports:

http://php.net/manual/en/function.strtotime.php

Title: how to get the previous 3 months in php

Body:
You can use the strtotime function like this:

echo date('M', strtotime('-3 month'));

So you specify previous dates with minus sign.

echo date('M', strtotime('0 month'));
echo date('M', strtotime('-1 month'));
echo date('M', strtotime('-2 month'));
echo date('M', strtotime('-3 month'));

Results:

Dec
Nov
Oct
Sep

You can do the same if you are using a loop like this:

for ($i = -3; $i <= 0; $i++){
  echo date('M', strtotime("$i month"));
}

Results:

Sep
Oct
Nov
Dec

Check out the documentation too see many other friendly date and time keywords strtotime supports:

http://php.net/manual/en/function.strtotime.php


问:
Android Developer Dashboard national/regional version
As many of you may know, Google has provided us with a nice Dashboard that shows us the current distribution of active Android devices along certain characteristics, such as platform version or screen size.

It would be nice to have some similar information, but counting devices only in a specific region or country. For example, I am a Hungarian developer currently working on applications that are almost certainly only useful for people living here, in Hungary. Thus, I don't need to know the world's statistics, only the Hungarian subset - which would be slightly different due to lesser and later availability of the devices and general economical reasons.

So far I could not find such statistics, so I ask you, have you ever stumbled upon something like that? Or shall I write to Google and ask for this seemingly not too complicated feature?

答:
It would be awesome if we had this from Google.  There are a couple of sites/blogs that occasionally post info that can give you an idea.  Device Atlas uses "mobile web data" - who knows what that means exactly but their numbers seem reasonable.

https://deviceatlas.com/blog/android-versions-market-share-2017

You can replace the "2017" with "2016" to get last year's report.  Maybe they will have more in the future.