问:
Losslessly Compress PDF Generated from PostScript
I am generating multiple EPS files, which contain several PostScript drawing commands that are not necessarily encoded efficiently.  The first update in the answer to this question describes similar inefficiencies.

Each of my EPS files are around 18 MB, and the resulting PDF files are around 3 MB.  I am generating the PDF files using epstopdf, which enables some sort of compression by default.

Are there any suggestions for how to further reduce the resulting PDF file sizes  without changing the quality (e.g. rasterizing the vector graphics)?

I tried reducing the precision of the coordinates from 8 digits past the decimal to 3.  This reduced the EPS file sizes to about 14 MB, but, counter-intuitively, the PDF file sizes slightly increased.

Update 1: The EPS files contain several occurrences of the sample code below for different coordinates and colors.

```<code>newpath
1 setlinejoin
1 setlinecap
<<
/BBox [322      384.0417      615.0087      651.9958]
/Domain [322      384.0417      615.0087      651.9958]
/ShadingType 6
/ColorSpace [/DeviceRGB]
/DataSource
[
0
   350.00000000    651.99583594
   336.00000000    645.75890880
   336.00000000    645.75890880
   322.00000000    639.52198166
   339.17140372    627.26533984
   339.17140372    627.26533984
   356.34280743    615.00869803
   370.19224806    621.16169097
   370.19224806    621.16169097
   384.04168868    627.31468392
   367.02084434    639.65525993
   367.02084434    639.65525993
0.23047     0.29688        0.75
0.23047     0.29688        0.75
0.41081     0.54141     0.93366
0.41112     0.54178     0.93388
]
>>
gsave
322      615.0087      62.04169      36.98714 rectclip
shfill
grestore
</code>```

Update 2: I have been able to reduce the PDF file sizes by about 15% by using pdftocairo, followed by gs -dCompatibilityLevel=1.4 -dPDFSETTINGS=/default -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dDetectDuplicateImages=true -sOutputFile=out.pdf in_.pdf.

答:
PostScript is a programming language and PDF is not, so often you can actually create a smaller PostScript program than the resulting PDF file.

The 'inefficiencies' you mention in your EPS program, and the precision of the input numbers, are completely irrelevant to the size of the PDF file. The operators in PDF are not the same names as the operators in PostScript, so a 'moveto' in PostScript does not simply get translitereated into a 'moveto' in the resulting PDF file. The precision of numbers in the output PDF file is not tied to the precision of the numbers in the input.

In addition, PostScript interpreters often use a fixed precision arithmetic (Ghostscript for example uses 24:8), so (eg) 1.5 on the input may not be produced as 1.5 on the output, it may instead become 1.49999999.

So the result of this, basically, is that nobody can tell why your PDF files are as large as they are without seeing them. I would suggest that a 6:1 reduction in size is pretty reasonable personally. If you post a representative example somewhere its possible someone could look at it and might be able to offer some suggestions, but without seeing the content its not really possible to tell.

NB rendering the content would most likely increase the size of the PDF file, unless you render at a really low resolution.

EDIT

The supplied example is simply a shading dictionary, the PDF file will contain almost exactly the same data for that particular construct. Its already about as compact as you could expect, I very much doubt it this is the sort of thing occupying 18MB of source, that would be an enormous amount of shadings. There is no realistic way to make that smaller, and rendering it to a bitmap (even at very low resolution) would actually make it larger.

Its entirely possible the EPS contains things like a bitmap preview, which will, of course, be removed when creating a PDF. It may also (depending on the creating application) contain the original document, stored as comments, which will also be removed when creating a PDF file. Without seeing the original EPS its not really possible to suggest much.

I'm afraid posting little bits of the file isn't going to help really.

Body:
I am generating multiple EPS files, which contain several PostScript drawing commands that are not necessarily encoded efficiently.  The first update in the answer to this question describes similar inefficiencies.

Each of my EPS files are around 18 MB, and the resulting PDF files are around 3 MB.  I am generating the PDF files using epstopdf, which enables some sort of compression by default.

Are there any suggestions for how to further reduce the resulting PDF file sizes  without changing the quality (e.g. rasterizing the vector graphics)?

I tried reducing the precision of the coordinates from 8 digits past the decimal to 3.  This reduced the EPS file sizes to about 14 MB, but, counter-intuitively, the PDF file sizes slightly increased.

Update 1: The EPS files contain several occurrences of the sample code below for different coordinates and colors.

newpath
1 setlinejoin
1 setlinecap
<<
/BBox [322      384.0417      615.0087      651.9958]
/Domain [322      384.0417      615.0087      651.9958]
/ShadingType 6
/ColorSpace [/DeviceRGB]
/DataSource
[
0
   350.00000000    651.99583594
   336.00000000    645.75890880
   336.00000000    645.75890880
   322.00000000    639.52198166
   339.17140372    627.26533984
   339.17140372    627.26533984
   356.34280743    615.00869803
   370.19224806    621.16169097
   370.19224806    621.16169097
   384.04168868    627.31468392
   367.02084434    639.65525993
   367.02084434    639.65525993
0.23047     0.29688        0.75
0.23047     0.29688        0.75
0.41081     0.54141     0.93366
0.41112     0.54178     0.93388
]
>>
gsave
322      615.0087      62.04169      36.98714 rectclip
shfill
grestore

Update 2: I have been able to reduce the PDF file sizes by about 15% by using pdftocairo, followed by gs -dCompatibilityLevel=1.4 -dPDFSETTINGS=/default -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dDetectDuplicateImages=true -sOutputFile=out.pdf in_.pdf.


来源: stackexchange

问:
Why is coldfusion outputting these values as floating point decimals?
I'm experiencing difficulties with a jwt token, turns out it's because coldfusion is converting an int to a float. I'm not sure where the problem is or how to fix it.

Token timestamp and expiration:

```<code><cfset TimeStamp = '#VAL( int( getTickCount() / 1000 ) )#' >
<cfset Exp = '#VAL( int( (getTickCount() / 1000)+43200 ) )#' >

    <cfscript>
        Variables.payload                = StructNew();
        Variables.payload[ "nbf" ]       = "#TimeStamp#";
        Variables.payload[ "exp" ]       = "#Exp#";
        Variables.result                 = JWT.encode( payload, Variables.secretKey);
     </cfscript>
</code>```

The JWT.Encode call looks like this:

```<code><cffunction name="encode" access="public" returntype="String">
    <!--- ****************** Arguments ************************ --->
    <cfargument name="payload" type="any" required="true">
    <cfargument name="key" type="string" required="true">
    <cfargument name="algo" type="string" required="false" default="HS256">
    <!--- ****************** /Arguments *********************** --->

    <!--- define our variables here  --->
    <cfset var currentTime = getCurrentUtcTime()>
    <cfset var header = createObject("java", "java.util.LinkedHashMap").init() /> <!--- StructNew doesnt work because coldfusion 8 orders the keys --->
    <cfset var claims = createObject("java", "java.util.LinkedHashMap").init() /> <!--- StructNew doesnt work because coldfusion 8 orders the keys --->
    <cfset var segments = ArrayNew(1)>

    <!---
        creation of first segment of our JWT: the header
    --->
    <cfset header[ "typ" ] = "JWT">
    <cfset header[ "alg" ] = "HS256">
    <!--- add header an json with base64 encoding to segment array --->
    <cfset arrayAppend( segments, replace( toBase64( serializeJSON( header ) ), "=", "", "all" ) )>

    <!---
        creation of the middle segment: the claims set
    --->
    <cfset claims = Arguments.payload>
    <!---
        escape forward slashes in generated JSON
    --->
    <cfset claimsJson = replace(  serializeJSON( claims ), "/", "\/", "all" )>

    <!--- add header and json with base64 encoding (with padding REMOVED!) to segment array --->
    <cfset arrayAppend( segments, replace( toBase64( claimsJson ), "=", "", "all" ) )>

    <!---
        create the last segment: the signature
    --->
    <cfset signingInput = ArrayToList( segments, "." )>
    <cfset signature = sign( signingInput, Arguments.key, Arguments.algo )>

    <!---
        add signature as last the element to our string
    --->
    <cfreturn ListAppend( signingInput, signature, ".")>

</cffunction>
</code>```

Run through a base64 decoder, I get something like exp":1.498696809E9,"nbf":1.498653609E9

答:
Get Nathan Mische's JSONUtil.cfc. Then replace the line

```<code><cfset claimsJson = replace(  serializeJSON( claims ), "/", "\/", "all" )>
</code>```

with

```<code><cfset jsonTool = createobject("component","jsonutil")>
<cfset claimsJson = replace(jsonTool.serializeJSON(claims,false,true), "/", "\/", "all" )>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm experiencing difficulties with a jwt token, turns out it's because coldfusion is converting an int to a float. I'm not sure where the problem is or how to fix it.

Token timestamp and expiration:

<cfset TimeStamp = '#VAL( int( getTickCount() / 1000 ) )#' >
<cfset Exp = '#VAL( int( (getTickCount() / 1000)+43200 ) )#' >

    <cfscript>
        Variables.payload                = StructNew();
        Variables.payload[ "nbf" ]       = "#TimeStamp#";
        Variables.payload[ "exp" ]       = "#Exp#";
        Variables.result                 = JWT.encode( payload, Variables.secretKey);
     </cfscript>

The JWT.Encode call looks like this:

<cffunction name="encode" access="public" returntype="String">

    <cfargument name="payload" type="any" required="true">
    <cfargument name="key" type="string" required="true">
    <cfargument name="algo" type="string" required="false" default="HS256">

    <cfset var currentTime = getCurrentUtcTime()>
    <cfset var header = createObject("java", "java.util.LinkedHashMap").init() />
    <cfset var claims = createObject("java", "java.util.LinkedHashMap").init() />
    <cfset var segments = ArrayNew(1)>

    <cfset header[ "typ" ] = "JWT">
    <cfset header[ "alg" ] = "HS256">

    <cfset arrayAppend( segments, replace( toBase64( serializeJSON( header ) ), "=", "", "all" ) )>

    <cfset claims = Arguments.payload>

    <cfset claimsJson = replace(  serializeJSON( claims ), "/", "\/", "all" )>

    <cfset arrayAppend( segments, replace( toBase64( claimsJson ), "=", "", "all" ) )>

    <cfset signingInput = ArrayToList( segments, "." )>
    <cfset signature = sign( signingInput, Arguments.key, Arguments.algo )>

    <cfreturn ListAppend( signingInput, signature, ".")>

</cffunction>

Run through a base64 decoder, I get something like exp":1.498696809E9,"nbf":1.498653609E9

Body:
Get Nathan Mische's JSONUtil.cfc. Then replace the line

<cfset claimsJson = replace(  serializeJSON( claims ), "/", "\/", "all" )>

with

<cfset jsonTool = createobject("component","jsonutil")>
<cfset claimsJson = replace(jsonTool.serializeJSON(claims,false,true), "/", "\/", "all" )>


问:
Get highest value of X rows
I'm looking for a function to calculate the highest value for the prior X periods on an XTS object. The function would return a vector with such values.

I would believe there are multiple ways to calculate this. Surprisingly I could not find this covered in a prior SO question. I am hoping there is a package with a function already defined for this. If there is none maybe someone knows how to tackle it.

The example below shows how the vector with the highest values of the last 3 periods would look like for XTS object XTS1.

```<code>library('xts')
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))

#DESIRED OUTPUT
                     [,1]   GetHighest(3)
2014-10-22 08:45:00   12              NA
2014-10-22 09:00:00    7              12
2014-10-22 09:15:00    7              12
2014-10-22 09:30:00   22              12
2014-10-22 09:45:00   24              22
2014-10-22 10:00:00   30              24
2014-10-22 10:15:00   26              30
2014-10-22 10:30:00   23              30
2014-10-22 10:45:00   27              30
2014-10-22 11:00:00   30              27
</code>```

答:
You could use rollapply from zoo.

So it would look something like this:

```<code>GetHighest_3 = rollapply(data = XTS1, width = 3, FUN = max)
</code>```

Then combine it:

```<code>cbind(XTS1, GetHighest_3)
</code>```

The only probelm I see, is that it will probably return NA for the first 2 values, not only the first value, since it has a width of 3.

I wasn't able to test the code, since I don't have access to R right now, so there might be some misspelling.

Title: Get highest value of X rows

Body:
I'm looking for a function to calculate the highest value for the prior X periods on an XTS object. The function would return a vector with such values.

I would believe there are multiple ways to calculate this. Surprisingly I could not find this covered in a prior SO question. I am hoping there is a package with a function already defined for this. If there is none maybe someone knows how to tackle it.

The example below shows how the vector with the highest values of the last 3 periods would look like for XTS object XTS1.

library('xts')
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))

#DESIRED OUTPUT
                     [,1]   GetHighest(3)
2014-10-22 08:45:00   12              NA
2014-10-22 09:00:00    7              12
2014-10-22 09:15:00    7              12
2014-10-22 09:30:00   22              12
2014-10-22 09:45:00   24              22
2014-10-22 10:00:00   30              24
2014-10-22 10:15:00   26              30
2014-10-22 10:30:00   23              30
2014-10-22 10:45:00   27              30
2014-10-22 11:00:00   30              27

Body:
You could use rollapply from zoo.

So it would look something like this:

GetHighest_3 = rollapply(data = XTS1, width = 3, FUN = max)

Then combine it:

cbind(XTS1, GetHighest_3)

The only probelm I see, is that it will probably return NA for the first 2 values, not only the first value, since it has a width of 3.

I wasn't able to test the code, since I don't have access to R right now, so there might be some misspelling.


问:
How does one test item membership in an unordered sequence (C++)?
I've used python for a long time, and I'm just beginning to use C++

In python, if one has a set or a dictionary it is relatively easy to get a boolean value indicating whether or not a particular item is in that sequence using the in keyword.
i.e.

```<code>a = set(2,4,3)
if 4 in a
print "yes, 4 is in a, thank you for asking!"
</code>```

it's much more efficient than doing this:

```<code>a = [2,3,4]
for number in a
>if number == 4
>>return "yes, 4 is in a, thank you for asking!"
</code>```

is there a way to do make a membership test simple and efficient in cpp or do you always have to iterate through some ordered sequence?

答: std::find can determine whether or not an element exists in any unordered container or sequence.  If the sequence is unordered and not stored in a specialized container designed for lookups, it's unlikely you're going to do any better than O(N).

ContentLicense: CC BY-SA 2.5

Body:
I've used python for a long time, and I'm just beginning to use C++

In python, if one has a set or a dictionary it is relatively easy to get a boolean value indicating whether or not a particular item is in that sequence using the in keyword.
i.e.

a = set(2,4,3)
if 4 in a
print "yes, 4 is in a, thank you for asking!"

it's much more efficient than doing this:

a = [2,3,4]
for number in a
>if number == 4
>>return "yes, 4 is in a, thank you for asking!"

is there a way to do make a membership test simple and efficient in cpp or do you always have to iterate through some ordered sequence?


问:
access a value of a column of an n-uplet in django
I need help, please.

I've got an SQL database and my model name is: "Image" which has an integer model field "size"

I want to select the value of the size of the last image on my database, I tried this on SQL and it works:

```<code>select size from app_image where id = (select max(id) as maxenreg from app_image);
</code>```

But when i use this on my view :

```<code>var = Image.objects.raw('select size from app_image where id = (select max(id) as maxenreg from app_image)')
</code>```

it didn't give the same result.
Is there any query set of Django equivalent to that or any other solution to get this value?

答:
```<code>i = Image.objects.values('size').order_by('-id')[:1]
size = i['size']
print(size)
</code>```

try this

Body:
I need help, please.

I've got an SQL database and my model name is: "Image" which has an integer model field "size"

I want to select the value of the size of the last image on my database, I tried this on SQL and it works:

select size from app_image where id = (select max(id) as maxenreg from app_image);

But when i use this on my view :

var = Image.objects.raw('select size from app_image where id = (select max(id) as maxenreg from app_image)')

it didn't give the same result.
Is there any query set of Django equivalent to that or any other solution to get this value?

Body:
i = Image.objects.values('size').order_by('-id')[:1]
size = i['size']
print(size)

try this


问:
Get SIM MSISDN & IMSI number in Windows Phone Application
Is it possible to get the SIM MSISDN & IMSI number in windows Phone app development?

I have gone through some of the Q/A but they all are asked a long time ago.

答:
You could get SIM MSISDN & IMSI number in Windows Phone Application. Please notice that you should manually edit your application Package.appxmanifest as follows:

```<code><Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
    xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
    xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
    xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
    IgnorableNamespaces="uap mp rescap">

......

<Capabilities>
    <rescap:Capability Name="cellularDeviceIdentity" />
</Capabilities>
</code>```

The cellularDeviceIdentity capability allows apps to access cellular identification data.
  Anyone may request access to these capabilities for store submission.

You could use MobileBroadbandModem class to get all CurrentDeviceInformation, and the following is core codes.

```<code>using Windows.Networking.NetworkOperators;

......

public IReadOnlyList<SimCard> GetSimCards()
{
    var results = new List<SimCard>();

    var modem = MobileBroadbandModem.GetDefault();
    if (modem == null)
    {
        return results.AsReadOnly();
    }

    var account = modem.CurrentAccount;
    if (account == null)
    {
        return results.AsReadOnly();
    }
    var simCard = new SimCard();
    simCard.ICCID = account.CurrentDeviceInformation.SimIccId;
    simCard.IMSI = account.CurrentDeviceInformation.SubscriberId;
    simCard.MSISDN = modem.DeviceInformation.TelephoneNumbers;

    simCard.MCC = ExtractMCC(simCard.IMSI);
    simCard.MNC = ExtractMNC(simCard.IMSI);
    simCard.MSID = ExtractMSID(simCard.IMSI);

    results.Add(simCard);

    return results.AsReadOnly();
}
</code>```

I have uploaded code sample to git hub. Please check!

Body:
You could get SIM MSISDN & IMSI number in Windows Phone Application. Please notice that you should manually edit your application Package.appxmanifest as follows:

<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
    xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
    xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
    xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
    IgnorableNamespaces="uap mp rescap">

......

<Capabilities>
    <rescap:Capability Name="cellularDeviceIdentity" />
</Capabilities>

The cellularDeviceIdentity capability allows apps to access cellular identification data.
  Anyone may request access to these capabilities for store submission.

You could use MobileBroadbandModem class to get all CurrentDeviceInformation, and the following is core codes.

using Windows.Networking.NetworkOperators;

......

public IReadOnlyList<SimCard> GetSimCards()
{
    var results = new List<SimCard>();

    var modem = MobileBroadbandModem.GetDefault();
    if (modem == null)
    {
        return results.AsReadOnly();
    }

    var account = modem.CurrentAccount;
    if (account == null)
    {
        return results.AsReadOnly();
    }
    var simCard = new SimCard();
    simCard.ICCID = account.CurrentDeviceInformation.SimIccId;
    simCard.IMSI = account.CurrentDeviceInformation.SubscriberId;
    simCard.MSISDN = modem.DeviceInformation.TelephoneNumbers;

    simCard.MCC = ExtractMCC(simCard.IMSI);
    simCard.MNC = ExtractMNC(simCard.IMSI);
    simCard.MSID = ExtractMSID(simCard.IMSI);

    results.Add(simCard);

    return results.AsReadOnly();
}

I have uploaded code sample to git hub. Please check!


问:
how to pass list of ids to mysql delete query from NodeJs
i need to do a multiple row delete query with the where clause in list (id1,id2..)
But since we don't have lists in JS i'm having a problem with passing the parameters to the query.This is my code:

```<code> let list =[1,2,..];
 let Query = 'DELETE FROM Table WHERE id IN (?)';
 connection.query(Query,list, function (err, result) {
     `enter code here`
 };
</code>```

when i pass it this way and after logging the mysql server to a Logfile i see that it actually passes only the first id.

PS : i tried without the parentheses around ? and also doing a Array.join on the list but both didn't work.

答:
Read in document of https://github.com/mysqljs/mysql#performing-queries (if you use this lib to connect mysql)</p>

```<code> let list =[1,2,..];
 let Query = 'DELETE FROM Table WHERE id IN (?)';
 // values param need is a array of value to binding to "?"
 // you can try [list.toString()] if the block above not working
 connection.query(Query,[list], function (err, result) {
     `enter code here`
 };
</code>```

Body:
i need to do a multiple row delete query with the where clause in list (id1,id2..)
But since we don't have lists in JS i'm having a problem with passing the parameters to the query.This is my code:

 let list =[1,2,..];
 let Query = 'DELETE FROM Table WHERE id IN (?)';
 connection.query(Query,list, function (err, result) {
     `enter code here`
 };

when i pass it this way and after logging the mysql server to a Logfile i see that it actually passes only the first id.

PS : i tried without the parentheses around ? and also doing a Array.join on the list but both didn't work.

Body:
Read in document of https://github.com/mysqljs/mysql#performing-queries (if you use this lib to connect mysql)

 let list =[1,2,..];
 let Query = 'DELETE FROM Table WHERE id IN (?)';
 // values param need is a array of value to binding to "?"
 // you can try [list.toString()] if the block above not working
 connection.query(Query,[list], function (err, result) {
     `enter code here`
 };


问:
Input from file in C, data types
thanks in advance for taking the time to read through my question...

```<code>/* Binary search for use with Gen_window.comp */
#include <stdio.h>

int main()
{
  char line[1000];
  double sig, E;

  FILE *fp, *fopen();
  fp = fopen("sig_data", "r");

  if (fp==NULL){
        printf("Error opening file!");
  }
  else {
        printf("Processing file...");
  }

  while( (fgets(line, 25, fp) != NULL) ){
        fscanf(fp, "%lf\t%lf", &E, &sig);
        printf("\nThe energy is: %lf eV\nThe corresponding cross section is: %lf barns\n",E, sig);
  }

}
</code>```

Numbers in the file are of the format X.XXXXXX+X or X.XXXXXX-X accordingly.  Does C have a way to specify this as input?  Is it a bother that there is no 'e'.  I cannot find any documentation that tells about inputing exponential, only returning exponential...

I do not need it to print that exact format, any other exponential format would be fine.

I realize there should be some specifiers and precision in my %lf, or maybe it should be %e, but I have tried everything that makes sense to me, so I am basically leaving it blank.

Thanks for your help.

答:
How about using strtok and strtod, it should do it for you quite nicely.  Using sscanf or fscanf very error prone.  See below:

```<code>const char* insertE(char* out, const char* src)
{
    char* p = out;
    while (*src) {
        if (*src == '+' || *src == '-') {
            *p++ = 'e';
        }
        *p++ = *src++;
    }
    return out;
}
.
.
.
char line[1000];
char tmp[100];
double sig, E;
FILE *fp;
char* end;

fp = fopen("sig_data", "r");
if (fp==NULL){
    printf("Error opening file!");
    return;
}
else {
    printf("Processing file...");
    while(! feof(fp) && (fgets(line, 1000, fp) != NULL) ) {
        E = strtod(insertE(tmp, strtok(line, "\t")), &end);
        sig = strtod(insertE(tmp, strtok(NULL, "\t")), &end);
        printf("\nThe energy is: %lf eV\nThe corresponding cross section is: %lf barns\n", E, sig);
    }
    fclose(fp);
}
</code>```

This comes with a notice that this code assumes the input file is formatted exactly correctly.

Title: Input from file in C, data types

Body:
thanks in advance for taking the time to read through my question...

/* Binary search for use with Gen_window.comp */
#include <stdio.h>

int main()
{
  char line[1000];
  double sig, E;

  FILE *fp, *fopen();
  fp = fopen("sig_data", "r");

  if (fp==NULL){
        printf("Error opening file!");
  }
  else {
        printf("Processing file...");
  }

  while( (fgets(line, 25, fp) != NULL) ){
        fscanf(fp, "%lf\t%lf", &E, &sig);
        printf("\nThe energy is: %lf eV\nThe corresponding cross section is: %lf barns\n",E, sig);
  }

}

Numbers in the file are of the format X.XXXXXX+X or X.XXXXXX-X accordingly.  Does C have a way to specify this as input?  Is it a bother that there is no 'e'.  I cannot find any documentation that tells about inputing exponential, only returning exponential...

I do not need it to print that exact format, any other exponential format would be fine.

I realize there should be some specifiers and precision in my %lf, or maybe it should be %e, but I have tried everything that makes sense to me, so I am basically leaving it blank.

Thanks for your help.

Body:
How about using strtok and strtod, it should do it for you quite nicely.  Using sscanf or fscanf very error prone.  See below:

const char* insertE(char* out, const char* src)
{
    char* p = out;
    while (*src) {
        if (*src == '+' || *src == '-') {
            *p++ = 'e';
        }
        *p++ = *src++;
    }
    return out;
}
.
.
.
char line[1000];
char tmp[100];
double sig, E;
FILE *fp;
char* end;

fp = fopen("sig_data", "r");
if (fp==NULL){
    printf("Error opening file!");
    return;
}
else {
    printf("Processing file...");
    while(! feof(fp) && (fgets(line, 1000, fp) != NULL) ) {
        E = strtod(insertE(tmp, strtok(line, "\t")), &end);
        sig = strtod(insertE(tmp, strtok(NULL, "\t")), &end);
        printf("\nThe energy is: %lf eV\nThe corresponding cross section is: %lf barns\n", E, sig);
    }
    fclose(fp);
}

This comes with a notice that this code assumes the input file is formatted exactly correctly.


问:
How to set up Spark cluster on laptop?
I am completely new at Spark and try to run a tutorial example, which counts the number of lines containing 'a' and 'b' in a text file in the local file system.

I am running it with SparkContext with master = "local", i.e. Spark is running in the same JVM. Now I would like to try it in "cluster mode".

So I would like to run a Spark cluster of a cluster manager and two worker nodes locally on my Mac laptop. What is the easiest way to do that ?

答:
Quoting the official documentation about Spark Standalone Mode:

```<code>./sbin/start-master.sh

./sbin/start-slave.sh <master-spark-URL>
</code>```

In other words, you should start the standalone Master first (using ./sbin/start-master.sh) followed by starting one or more standalone Workers (using ./sbin/start-slave.sh).

Quoting the docs again:

Once you have started a worker, look at the master's web UI (http://localhost:8080 by default)

You're done. Congrats!

Title: How to set up Spark cluster on laptop?

Body:
Quoting the official documentation about Spark Standalone Mode:

./sbin/start-master.sh

./sbin/start-slave.sh <master-spark-URL>

In other words, you should start the standalone Master first (using ./sbin/start-master.sh) followed by starting one or more standalone Workers (using ./sbin/start-slave.sh).

Quoting the docs again:

Once you have started a worker, look at the master's web UI (http://localhost:8080 by default)

You're done. Congrats!


问:
Unity Android build crashes with JNI ERROR (app bug): accessed stale local reference 0x200001 (index 0 in a table of size 0)
After building an Android app with Unity I noticed that on a specific device it would crash. After looking in the logs I found the following line:

```<code>JNI ERROR (app bug): accessed stale local reference 0x200001 (index 0 in a table of size 0)
</code>```

This was the issue that caused the app to crash and prompt the user with a window saying "Unfortunately, [App Name] has crashed".

答: The answer to my issue was quite weird. The device's time was set dramatically wrong (7 years in the past). After setting the correct time on the device the issue was solved.</p>

Body:
After building an Android app with Unity I noticed that on a specific device it would crash. After looking in the logs I found the following line:

JNI ERROR (app bug): accessed stale local reference 0x200001 (index 0 in a table of size 0)

This was the issue that caused the app to crash and prompt the user with a window saying "Unfortunately, [App Name] has crashed".


问:
MVC Caching for all users vs local cache
Is the following possible:

Cache list to be available for all users

If one item of the list is modified then re-Cache the list

Other scenario

Cache list in user browser

If on item of the list is modified, refresh all other users versions

I'm very confused with all the built in cache objects available in .NET

答:
Ok, without seeing your code it's hard to fully verify if I'm on the right track here but...

Re: Cache for all users:

You could use OutputCache on an/the action that returns your list.

```<code>[OutputCache(Duration=3600, VaryByParam="refreshCache", Location=OutputCacheLocation.Server, NoStore=true)]
public ActionResult GetTheList(bool refreshCache=false)
{
    return Content("")
}
</code>```

OutputCacheLocation.Server means the cache would be stored on the server...this can also be set to Client (cache in browser).

VaryByParam="refreshCache" if you pass refreshCache=true it will refresh the list on the server.

Duration the amount of seconds the item will be cached for.

Apologies if I'm misunderstanding the requirements...if so, please post some code examples of what you have so far...

More info on OutputCache: https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs

Body:
Ok, without seeing your code it's hard to fully verify if I'm on the right track here but...

Re: Cache for all users:

You could use OutputCache on an/the action that returns your list.

[OutputCache(Duration=3600, VaryByParam="refreshCache", Location=OutputCacheLocation.Server, NoStore=true)]
public ActionResult GetTheList(bool refreshCache=false)
{
    return Content("")
}

OutputCacheLocation.Server means the cache would be stored on the server...this can also be set to Client (cache in browser).

VaryByParam="refreshCache" if you pass refreshCache=true it will refresh the list on the server.

Duration the amount of seconds the item will be cached for.

Apologies if I'm misunderstanding the requirements...if so, please post some code examples of what you have so far...

More info on OutputCache: https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs


问:
converting xmlDocument object data to pdf
```<code>       XmlDocument doc = new XmlDocument();

        string a=textBox1.Text;
        doc.LoadXml(a.Substring(a.IndexOf(Environment.NewLine)));

        XmlWriterSettings settings = new XmlWriterSettings();

        settings.Indent = true;

        XmlWriter writer = XmlWriter.Create("data.xml", settings);
        doc.Save(writer);
</code>```

In the above code converts  textbox content to xml file.Now I required to process each element of the xmlDocument object(doc) and need to create pdf.

string in my textbox is like

Hello

and my Xml file data.xml is saved in debug folder of the project
now my pdf should contain a table with one row and one cell which contains "Hello" in it.
Could Any one help me to do this.I am very New to programming.

答:
This is a rather vague question, I don't know what kind of content the "data.xml" can have and how it should be mapped to a PDF file.

You mentioned "Hello" as an example, but that cannot be loaded as XmlDocument...

Nevertheless, here is a small sample that will hopefully get you started (for creating a PDF file I used GemBox.Document):

```<code>string a = @"
<table>
  <row>
    <cell>Hello 1-1</cell>
    <cell>Hello 1-2</cell>
  </row>
  <row>
    <cell>Hello 2-1</cell>
    <cell>Hello 2-2</cell>
  </row>
</table>";

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(a.Substring(a.IndexOf(Environment.NewLine)));

XmlWriterSettings settings = new XmlWriterSettings() {  Indent = true };
XmlWriter writer = XmlWriter.Create("data.xml", settings);
xmlDocument.Save(writer);

ComponentInfo.SetLicense("FREE-LIMITED-KEY");
DocumentModel pdfDocument = new DocumentModel();

Table table = new Table(pdfDocument);
table.TableFormat.PreferredWidth = new TableWidth(100, TableWidthUnit.Percentage);
pdfDocument.Sections.Add(new Section(pdfDocument, table));

foreach (XmlNode xmlRow in xmlDocument.SelectNodes("/table/row"))
{
    TableRow row = new TableRow(pdfDocument);
    table.Rows.Add(row);

    foreach (XmlNode xmlCell in xmlRow.SelectNodes(".//cell"))
        row.Cells.Add(
            new TableCell(pdfDocument,
                new Paragraph(pdfDocument, xmlCell.InnerText)));
}

pdfDocument.Save("sample.pdf");
</code>```

Also here is the resulting "sample.pdf":

Body:
       XmlDocument doc = new XmlDocument();

        string a=textBox1.Text;
        doc.LoadXml(a.Substring(a.IndexOf(Environment.NewLine)));

        XmlWriterSettings settings = new XmlWriterSettings();

        settings.Indent = true;

        XmlWriter writer = XmlWriter.Create("data.xml", settings);
        doc.Save(writer);

In the above code converts  textbox content to xml file.Now I required to process each element of the xmlDocument object(doc) and need to create pdf.

string in my textbox is like

Hello

and my Xml file data.xml is saved in debug folder of the project
now my pdf should contain a table with one row and one cell which contains "Hello" in it.
Could Any one help me to do this.I am very New to programming.

Body:
This is a rather vague question, I don't know what kind of content the "data.xml" can have and how it should be mapped to a PDF file.

You mentioned "Hello" as an example, but that cannot be loaded as XmlDocument...

Nevertheless, here is a small sample that will hopefully get you started (for creating a PDF file I used GemBox.Document):

string a = @"
<table>
  <row>
    <cell>Hello 1-1</cell>
    <cell>Hello 1-2</cell>
  </row>
  <row>
    <cell>Hello 2-1</cell>
    <cell>Hello 2-2</cell>
  </row>
</table>";

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(a.Substring(a.IndexOf(Environment.NewLine)));

XmlWriterSettings settings = new XmlWriterSettings() {  Indent = true };
XmlWriter writer = XmlWriter.Create("data.xml", settings);
xmlDocument.Save(writer);

ComponentInfo.SetLicense("FREE-LIMITED-KEY");
DocumentModel pdfDocument = new DocumentModel();

Table table = new Table(pdfDocument);
table.TableFormat.PreferredWidth = new TableWidth(100, TableWidthUnit.Percentage);
pdfDocument.Sections.Add(new Section(pdfDocument, table));

foreach (XmlNode xmlRow in xmlDocument.SelectNodes("/table/row"))
{
    TableRow row = new TableRow(pdfDocument);
    table.Rows.Add(row);

    foreach (XmlNode xmlCell in xmlRow.SelectNodes(".//cell"))
        row.Cells.Add(
            new TableCell(pdfDocument,
                new Paragraph(pdfDocument, xmlCell.InnerText)));
}

pdfDocument.Save("sample.pdf");

Also here is the resulting "sample.pdf":


问:
duplicate entry: com/google/android/gms/internal/zzqv.class Android Studio
In my project i have implemented play-services-games,first I have tried to add

 compile 'com.google.android.gms:play-services:10.0.1'

but i got into some troubles and the solutions that i found was to compile only the needed library
compile 'com.google.android.gms:play-services-games:10.0.1'

and all was great but when I've tried to add play-services-ads things got messy,I have added

compile 'com.google.android.gms:play-services-ads:10.0.1'

Now i get

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
  com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/internal/zzqv.class

Here is my build.gradle

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

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "com.apps.fightersam"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile name: 'unity-ads', ext: 'aar'
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.google.android.gms:play-services-games:10.0.1'
    compile 'com.google.android.gms:play-services-ads:10.0.1'

    compile project(':BaseGameUtils')
}
repositories {
    flatDir {
        dirs 'libs'
    }
}
</code>```

答:
I was using the latest version of FirebaseUI 2.0.0 which seemed to be incompatible with google-services:3.0.0. Therefore I downgraded FirebaseUI version to 1.2.0 and added the following code to Project level build.gradle:</p>

```<code>allprojects {
    repositories {
        jcenter()

        // Add the following
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}
</code>```

Body:
In my project i have implemented play-services-games,first I have tried to add

 compile 'com.google.android.gms:play-services:10.0.1'

but i got into some troubles and the solutions that i found was to compile only the needed library
compile 'com.google.android.gms:play-services-games:10.0.1'

and all was great but when I've tried to add play-services-ads things got messy,I have added

compile 'com.google.android.gms:play-services-ads:10.0.1'

Now i get

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
  com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/internal/zzqv.class

Here is my build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "com.apps.fightersam"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile name: 'unity-ads', ext: 'aar'
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.google.android.gms:play-services-games:10.0.1'
    compile 'com.google.android.gms:play-services-ads:10.0.1'

    compile project(':BaseGameUtils')
}
repositories {
    flatDir {
        dirs 'libs'
    }
}

Body:
I was using the latest version of FirebaseUI 2.0.0 which seemed to be incompatible with google-services:3.0.0. Therefore I downgraded FirebaseUI version to 1.2.0 and added the following code to Project level build.gradle:

allprojects {
    repositories {
        jcenter()

        // Add the following
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}


问:
Get only products with images using Amazon Product API
Is it possible with the Amazon Product API to return items from Amazon that have images using ItemSearch and ignore products that do not have images?

http://docs.aws.amazon.com/AWSECommerceService/latest/DG/ItemSearch.html

答:
The Amazon Product API does not allow us to filter the search results. It only allows searching a given index by keywords.

To only get results with images, you will have to write code that discards results with no images.


问:
Topmost View swallows touch events because overlapping
So here's my layout structure:

```<code>- RelativeLayout (full screen)
  - FrameLayout (full screen)
  - Button (in the middle of the screen)
  - RecyclerView (align parent bottom but with very big padding top to
    capture the scrolling also in the top of the screen, so it's basically acting like a full screen `RecyclerView`)
</code>```

So yes, the views are overlapping each other.

As of the reason the RecyclerView is the topmost view, it captures all the touch events on screen, and swallows them, preventing any touches to "go through it" to the underlying views below it. (Note: by underlying views, I don't mean to the RecyclerView's children but the other rootview's children)

I've read tons of stackoverflow posts regarding propagating touch events and preventing swallowing touch events, etc, and even though it seems pretty straightforward task to accomplish, I couldn't achieve the following effect:

I want my RecyclerView to capture the touch event, so it will scroll or whatever. but I want the rootView to think as that the RecyclerView didn't capture the event, and continue pass it to its other children (rootview'
s children).

Here's What I've tried to do:

1.  Overriding dispatchTouchEvent of the RecyclerView to do its logic and return false to act as it didn't dispatch its touch event so the rootview will keep iterating for touch through its child views.

```<code>@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    super.dispatchTouchEvent(ev);
    return false;
}
</code>```

What happened:

The RecyclerView still functions but still swallows all touch events (just the same as before)

2. Overriding onTouchEvent of the RecyclerView to do its logic and return false. (Note: I know it doesn't seem as it would be the solution but I tried)

```<code>@Override
public boolean onTouchEvent(MotionEvent e) {
    super.onTouchEvent(e);
    return false;
}
</code>```

What happened:

Same result as in #1

I've made some more tweaks with the same idea, but they didn't work as well, so I'm kinda clueless right now and would love for help of you fellows!

答:
I'm not sure how efficient/valid/nice solution is this, but this is what comes to my mind: what if you listen for touch events in the root view (RelativeLayout in your case), and dispatch the touch event to all the children of that layout except for the RecyclerView?

```<code>public class MyRelativeLayout extends RelativeLayout {
    ...

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final boolean intercept = super.onInterceptTouchEvent(ev);

        // getChildCount() - 1, because `RecyclerView` is the last child
        for (int i = 0, size = getChildCount() - 1; i < size; i++) {
            View v = getChildAt(i);
            v.dispatchTouchEvent(MotionEvent.obtain(ev));
        }

        return intercept;
    }
}
</code>```

This seems like it should work.

Body:
So here's my layout structure:

- RelativeLayout (full screen)
  - FrameLayout (full screen)
  - Button (in the middle of the screen)
  - RecyclerView (align parent bottom but with very big padding top to
    capture the scrolling also in the top of the screen, so it's basically acting like a full screen `RecyclerView`)

So yes, the views are overlapping each other.

As of the reason the RecyclerView is the topmost view, it captures all the touch events on screen, and swallows them, preventing any touches to "go through it" to the underlying views below it. (Note: by underlying views, I don't mean to the RecyclerView's children but the other rootview's children)

I've read tons of stackoverflow posts regarding propagating touch events and preventing swallowing touch events, etc, and even though it seems pretty straightforward task to accomplish, I couldn't achieve the following effect:

I want my RecyclerView to capture the touch event, so it will scroll or whatever. but I want the rootView to think as that the RecyclerView didn't capture the event, and continue pass it to its other children (rootview'
s children).

Here's What I've tried to do:

1.  Overriding dispatchTouchEvent of the RecyclerView to do its logic and return false to act as it didn't dispatch its touch event so the rootview will keep iterating for touch through its child views.

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    super.dispatchTouchEvent(ev);
    return false;
}

What happened:

The RecyclerView still functions but still swallows all touch events (just the same as before)

2. Overriding onTouchEvent of the RecyclerView to do its logic and return false. (Note: I know it doesn't seem as it would be the solution but I tried)

@Override
public boolean onTouchEvent(MotionEvent e) {
    super.onTouchEvent(e);
    return false;
}

What happened:

Same result as in #1

I've made some more tweaks with the same idea, but they didn't work as well, so I'm kinda clueless right now and would love for help of you fellows!

Body:
I'm not sure how efficient/valid/nice solution is this, but this is what comes to my mind: what if you listen for touch events in the root view (RelativeLayout in your case), and dispatch the touch event to all the children of that layout except for the RecyclerView?

public class MyRelativeLayout extends RelativeLayout {
    ...

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final boolean intercept = super.onInterceptTouchEvent(ev);

        // getChildCount() - 1, because `RecyclerView` is the last child
        for (int i = 0, size = getChildCount() - 1; i < size; i++) {
            View v = getChildAt(i);
            v.dispatchTouchEvent(MotionEvent.obtain(ev));
        }

        return intercept;
    }
}

This seems like it should work.


问:
Defining keys using push method in JavaScript
I'm developing a simple shopping cart solution in JavaScript (Ionic 2 / Angular).

In PHP I just do the following:

```<code><?php
$cart = array(
    48131 => array(
        'size' => 'STANDART',
        'qty' => 1,
    )
);

print_r($cart);
</code>```

And the 48131 is the index, so after I can easily delete it (since I know that the key is 48131).

This is my JavaScript code (an example):

```<code>function addToCart() {
    this.cart = [];

    this.cart.push({
        id: this.id,
        size: this.size,
        qty: this.qty
    });

    console.log(this.cart);
}
</code>```

And this is what I get -

It looks like the push method just adds another key, starting from 0 (which I guess is normal). I've tried many things, I can't do it right... Can someone help?

答:
Cart on angular side should have an object. And take an item into it something like this:
var cart = {};
cart[id] = {prop1: val1, prop2: val2};</p>

Body:
I'm developing a simple shopping cart solution in JavaScript (Ionic 2 / Angular).

In PHP I just do the following:

<?php
$cart = array(
    48131 => array(
        'size' => 'STANDART',
        'qty' => 1,
    )
);

print_r($cart);

And the 48131 is the index, so after I can easily delete it (since I know that the key is 48131).

This is my JavaScript code (an example):

function addToCart() {
    this.cart = [];

    this.cart.push({
        id: this.id,
        size: this.size,
        qty: this.qty
    });

    console.log(this.cart);
}

And this is what I get -

It looks like the push method just adds another key, starting from 0 (which I guess is normal). I've tried many things, I can't do it right... Can someone help?


问:
turning a windows service into a web app core service?
I have a windows service which allows incoming and outgoing connections to a UDP port that is using Lidgren UDP networking library.

I've been really wanting to change this to use .net core for some of the obvious cross platform benefits and other benefits like deployment and scaling within Microsoft's Azure Cloud.

It seems the only easy way to do this is to use the Web Core app which is not really what im doing(Its not handling http requests).

I've done tons of googling to figure out how to handle this situation and the only thing i have found is a library called WindowsService for .net core but that just allows me to convert a 462 app to .net core and continue using windows service which is not ideal.

TLDR; Can anyone shed some light on how i can convert a windows service which is handling UDP Traffic into a deployable application for azure?

答:
I've been really wanting to change this to use .net core for some of the obvious cross platform benefits

Before changing to .NET Core, you need to confirm whether all the dependent assemblies support .NET Core.

Can anyone shed some light on how i can convert a windows service which is handling UDP Traffic into a deployable application for azure?

There are multi services which support windows service on Azure. Based on your description, you could choose Azure VM scale sets, Azure Cloud Service and Azure Service Fabric to host your windows service. All of these services could listen on an UDP port to get/send a message from/to client.

You don't need to modify your code if you choose Azure VM scale sets. You can also package your Windows Service to a executable file and deploy it to Cloud Service or Service Fabric. You could also check following document to check the differences between Cloud Service and Service Fabric.


问:
Define Prefix for Auto Increment in MySQL
I have the string like this: POyyyymm0000

At the current time: when i am inputting, it will be PO2017070001

And i input again it will be PO2017070002

And in the next month it will be PO2017080001

The question is how to insert PO[thecurrentyear][thecurrentmonth][autoincrement, start from 0000 to 9999]

答:
You can use date() and rand() to achieve this

Just like this

```<code>$id='PO'.date('Ymd').rand(0000,9999);
</code>```

It will produce output as

Modified:-

For unique key you can use time() like this

```<code>$id='PO'.date('Ymd').time(); //o/p is "PO201707061499326403"
</code>```

It will never repeat the same id.

Body:
You can use date() and rand() to achieve this

Just like this

$id='PO'.date('Ymd').rand(0000,9999);

It will produce output as

Modified:-

For unique key you can use time() like this

$id='PO'.date('Ymd').time(); //o/p is "PO201707061499326403"

It will never repeat the same id.


问:
Read contents of an Excel file using PowerShell and store it in a SQL Server database
I am trying to write the contents of an Excel file (on tab 5) to a database but it keeps failing.

Here is my code:

```<code> $dir = "\\server\files\"
    $latest = Get-ChildItem -Path $dir | Where-Object {$_.name -like "*Data Notes*"} | Sort-Object LastWriteTime -Descending | Select-Object -First 1
    Write-Output "The latest file is: $latest"
    Write-SqlTableData -ServerInstance "sql server" -DatabaseName "sql5" -SchemaName dbo -TableName Temptable100 -InputData $latest.FullName -Force
</code>```

The table gets created fine but its empty. Can anyone please help me??

I have attached the contents of the Excel file here:

答:
All I needed was to store the information in a data variable and then use the Write-SQLTableData to store the information in a database. See below:</p>

```<code>Write-SqlTableData -ServerInstance "instance" -DatabaseName "db1" -SchemaName dbo -TableName TableName -InputData $DataTable -Force
</code>```

Body:
I am trying to write the contents of an Excel file (on tab 5) to a database but it keeps failing.

Here is my code:

 $dir = "\\server\files\"
    $latest = Get-ChildItem -Path $dir | Where-Object {$_.name -like "*Data Notes*"} | Sort-Object LastWriteTime -Descending | Select-Object -First 1
    Write-Output "The latest file is: $latest"
    Write-SqlTableData -ServerInstance "sql server" -DatabaseName "sql5" -SchemaName dbo -TableName Temptable100 -InputData $latest.FullName -Force

The table gets created fine but its empty. Can anyone please help me??

I have attached the contents of the Excel file here:

Body:
All I needed was to store the information in a data variable and then use the Write-SQLTableData to store the information in a database. See below:

Write-SqlTableData -ServerInstance "instance" -DatabaseName "db1" -SchemaName dbo -TableName TableName -InputData $DataTable -Force


问:
Want to Sort an array by ascending but Zero should be at Last
I am doing a php application for a sports event in some cases the minimum value scored is the winner. Like if there is 100mt running event then the winner is the fastest running. Winner has the minimum time taken to complete the race.

But what i am facing that when someone is absent or quit before finish then we are providing score ZERO. In that case when we are going to sort then the First Place will be the ZERO. But that should be at last.

Below is my code in javascript

```<code>var sorted = $(".result").sort(function (ib1, ib2) {
  return parseFloat($(ib2).val()) - parseFloat($(ib1).val());
});

// Result Names
$('#result_first').val($("#participant"+$(sorted.get(9)).data("section")).val());
$('#result_second').val($("#participant"+$(sorted.get(8)).data("section")).val());
$('#result_third').val($("#participant"+$(sorted.get(7)).data("section")).val());
$('#result_fourth').val($("#participant"+$(sorted.get(6)).data("section")).val());
$('#result_fifth').val($("#participant"+$(sorted.get(5)).data("section")).val());
$('#result_sixth').val($("#participant"+$(sorted.get(4)).data("section")).val());
$('#result_seventh').val($("#participant"+$(sorted.get(3)).data("section")).val());
$('#result_eighth').val($("#participant"+$(sorted.get(2)).data("section")).val());
$('#result_ninth').val($("#participant"+$(sorted.get(1)).data("section")).val());
$('#result_tenth').val($("#participant"+$(sorted.get(0)).data("section")).val());

// Result Numbers
$('#result_first_no').val($(sorted.get(9)).val());
$('#result_second_no').val($(sorted.get(8)).val());
$('#result_third_no').val($(sorted.get(7)).val());
$('#result_fourth_no').val($(sorted.get(6)).val());
$('#result_fifth_no').val($(sorted.get(5)).val());
$('#result_sixth_no').val($(sorted.get(4)).val());
$('#result_seventh_no').val($(sorted.get(3)).val());
$('#result_eighth_no').val($(sorted.get(2)).val());
$('#result_ninth_no').val($(sorted.get(1)).val());
$('#result_tenth_no').val($(sorted.get(0)).val());
</code>```

Please help me to sort these values and the ZERO values should be last.

答:
```<code>$(".result").sort(function (ib1, ib2) {
    ib1 = parseFloat($(ib1).val()); ib2 = parseFloat($(ib2).val());
    return (ib1 * ib2 === 0) ? ((ib1 === ib2) ? (0) : ((ib1 === 0) ? -1 : 1)) : (ib2 - ib1);
});
</code>```

If ib1 is 0, then it is "greater" than ib2. Otherwise, if their product is 0 (so ib2 is 0), then ib1 is "smaller" than ib2. If none of them is 0, then your initial logic is applied.

Body:
I am doing a php application for a sports event in some cases the minimum value scored is the winner. Like if there is 100mt running event then the winner is the fastest running. Winner has the minimum time taken to complete the race.

But what i am facing that when someone is absent or quit before finish then we are providing score ZERO. In that case when we are going to sort then the First Place will be the ZERO. But that should be at last.

Below is my code in javascript

var sorted = $(".result").sort(function (ib1, ib2) {
  return parseFloat($(ib2).val()) - parseFloat($(ib1).val());
});

// Result Names
$('#result_first').val($("#participant"+$(sorted.get(9)).data("section")).val());
$('#result_second').val($("#participant"+$(sorted.get(8)).data("section")).val());
$('#result_third').val($("#participant"+$(sorted.get(7)).data("section")).val());
$('#result_fourth').val($("#participant"+$(sorted.get(6)).data("section")).val());
$('#result_fifth').val($("#participant"+$(sorted.get(5)).data("section")).val());
$('#result_sixth').val($("#participant"+$(sorted.get(4)).data("section")).val());
$('#result_seventh').val($("#participant"+$(sorted.get(3)).data("section")).val());
$('#result_eighth').val($("#participant"+$(sorted.get(2)).data("section")).val());
$('#result_ninth').val($("#participant"+$(sorted.get(1)).data("section")).val());
$('#result_tenth').val($("#participant"+$(sorted.get(0)).data("section")).val());

// Result Numbers
$('#result_first_no').val($(sorted.get(9)).val());
$('#result_second_no').val($(sorted.get(8)).val());
$('#result_third_no').val($(sorted.get(7)).val());
$('#result_fourth_no').val($(sorted.get(6)).val());
$('#result_fifth_no').val($(sorted.get(5)).val());
$('#result_sixth_no').val($(sorted.get(4)).val());
$('#result_seventh_no').val($(sorted.get(3)).val());
$('#result_eighth_no').val($(sorted.get(2)).val());
$('#result_ninth_no').val($(sorted.get(1)).val());
$('#result_tenth_no').val($(sorted.get(0)).val());

Please help me to sort these values and the ZERO values should be last.

Body:
$(".result").sort(function (ib1, ib2) {
    ib1 = parseFloat($(ib1).val()); ib2 = parseFloat($(ib2).val());
    return (ib1 * ib2 === 0) ? ((ib1 === ib2) ? (0) : ((ib1 === 0) ? -1 : 1)) : (ib2 - ib1);
});

If ib1 is 0, then it is "greater" than ib2. Otherwise, if their product is 0 (so ib2 is 0), then ib1 is "smaller" than ib2. If none of them is 0, then your initial logic is applied.


问:
angular 2 filter BehaviorSubject
i try to filter a BehaviorSubject in Angular 2. The commissions object in the service will get data via a http request. But because it's instanced with "null" there is an error at the filter code line.

The error:

Cannot read property '0' of null

at .filter((commission: Commission[], index) => commission[index]._id === this.commissionid)

Here ist the code:

commissionService:

```<code>public commissions: Subject<Commission[]> = new BehaviorSubject<Commission[]>(null);
</code>```

in the component:

```<code>  ngOnInit() {
    this.commissionService.commissions
        .filter((commission: Commission[], index) => commission[index]._id === this.commissionid)
        .subscribe(data => {console.log(data); })
  }
</code>```

Is it possible at all that this filter will work if I change the this.commissionid? Thanks!

答:
You want to have a single object from your subject, so use rxjs first operator. http://reactivex.io/documentation/operators/first.html

```<code>init_obj(id) {
    this.commissionService.commissions
        .first(c => c._id === id)
        .subscribe(data => {
            this.commission = data;
        })
}
</code>```

Title: angular 2 filter BehaviorSubject

Body:
i try to filter a BehaviorSubject in Angular 2. The commissions object in the service will get data via a http request. But because it's instanced with "null" there is an error at the filter code line.

The error:

Cannot read property '0' of null

at .filter((commission: Commission[], index) => commission[index]._id === this.commissionid)

Here ist the code:

commissionService:

public commissions: Subject<Commission[]> = new BehaviorSubject<Commission[]>(null);

in the component:

  ngOnInit() {
    this.commissionService.commissions
        .filter((commission: Commission[], index) => commission[index]._id === this.commissionid)
        .subscribe(data => {console.log(data); })
  }

Is it possible at all that this filter will work if I change the this.commissionid? Thanks!

Body:
You want to have a single object from your subject, so use rxjs first operator. http://reactivex.io/documentation/operators/first.html

init_obj(id) {
    this.commissionService.commissions
        .first(c => c._id === id)
        .subscribe(data => {
            this.commission = data;
        })
}


问:
How to hide hierarchy grid toolbar custom button in kendo grid?
Here is my hierarchy grid toolbar.

I put new button in toolbar and that id is CustomButton.

I want to hide that button onclick but when ajax call is success.

I tried $("#CustomButton").remove(); And Also $("#CustomButton").hide(); This code through my button is not hide.

How to hide that button?

```<code>toolbar: [{ name: "create", text: "@T("Admin.Common.AddNewRecord")" },{ name: "add_user", template: '<a class="k-button" id="CustomButton" onclick="oleuminvoiceDocketSubmit()">Send invoice to customer</a>'}],

//Custom Toolbar Button Click
function oleuminvoiceDocketSubmit()
{
        $.ajax({
            dataType: "json",
            type: "POST",
            url: "@(Url.Action("Abc", "Def"))",
            data: {
                'id':InvoiceId,
                'selectedid':selectedIds,
                'method':'Ground'
            },
            success: function (response) {

            },
          });
}
</code>```

答:
Give Id attribute to custom button:

```<code>toolbar: [{ name: "create", id : "btnTest"}]
</code>```

On success function use this id like below:

```<code>success: function (response) {
    $("#btnTest").hide();
},
</code>```

Body:
Here is my hierarchy grid toolbar.

I put new button in toolbar and that id is CustomButton.

I want to hide that button onclick but when ajax call is success.

I tried $("#CustomButton").remove(); And Also $("#CustomButton").hide(); This code through my button is not hide.

How to hide that button?

toolbar: [{ name: "create", text: "@T("Admin.Common.AddNewRecord")" },{ name: "add_user", template: 'Send invoice to customer'}],

//Custom Toolbar Button Click
function oleuminvoiceDocketSubmit()
{
        $.ajax({
            dataType: "json",
            type: "POST",
            url: "@(Url.Action("Abc", "Def"))",
            data: {
                'id':InvoiceId,
                'selectedid':selectedIds,
                'method':'Ground'
            },
            success: function (response) {

            },
          });
}

Body:
Give Id attribute to custom button:

toolbar: [{ name: "create", id : "btnTest"}]

On success function use this id like below:

success: function (response) {
    $("#btnTest").hide();
},


问:
Generating C++ code at runtime, compiling and running it
is there a multiplatform c++ compiler that could be linked into any software ?

Lets say I want to generate c++ code at runtime, compile it and run it.
I'm looking for a compact solution (bunch of classes), preferably LGPL/BSD licence :)

As far as I know it can be done in Java and c#. What about c++ ?

答:
When we looked into scripting we chose AngelScript because of the similarity with C++.
V8 is great but it's certainly limited to some platforms, AngelScript is a lot easier to compile with and probably to learn (if you came from C++) and it has a zlib license.
http://www.angelcode.com/angelscript/</p>

ContentLicense: CC BY-SA 4.0


问:
Using Google Apps Scripts to generate shareable links of new files
I recently discovered this Google Apps Scripts feature and am wondering if my issue can be addressed by using that.

Let's say I have a machine generating new files (screenshots or videos taken from a capture card) that are being saved in a folder that is sync'd to my Google Drive. What I would like to do is somehow automatically generate a shareable link for each NEW file that gets added and send it to an email address (may or may not be a Gmail address).

Is this something that I can use Google Apps Scripts for? I tried looking into batch files first but I can't generate the shareable link automatically (or couldn't figure out how).

I don't have any code yet, just looking at potential approaches.

Thanks in advance!

答:
Yes almost everything is possible in GAS. However, you are likely to find better answers when you post some code that you have tried yourself before asking the answer here.

However, if the machine automatically saves the files in a folder in google drive you can scan that folder with a script and find the links. Attach a trigger to it with a, for example, 5 minute interval and write those links on a spreadsheet.

an example:

```<code>function links(){
var sheet = SpreadsheetApp.getActive.getActiveSpreadsheet();
var folder = DriveApp.getFolderById('put google folder id here');
var files = folder.getFiles();
 while (files.hasNext()) {
   var file = files.next();
   var vals = file.getUrl();
   sheet.getRange(your range you want to paste the link).setValues(vals);
 }
}
</code>```

This will find the links of all the files in the folder and paste that onto a google spreadsheet where the code is linked to.
Use that spreadsheet as a database and send an email by using that database.

Body:
Yes almost everything is possible in GAS. However, you are likely to find better answers when you post some code that you have tried yourself before asking the answer here.

However, if the machine automatically saves the files in a folder in google drive you can scan that folder with a script and find the links. Attach a trigger to it with a, for example, 5 minute interval and write those links on a spreadsheet.

an example:

function links(){
var sheet = SpreadsheetApp.getActive.getActiveSpreadsheet();
var folder = DriveApp.getFolderById('put google folder id here');
var files = folder.getFiles();
 while (files.hasNext()) {
   var file = files.next();
   var vals = file.getUrl();
   sheet.getRange(your range you want to paste the link).setValues(vals);
 }
}

This will find the links of all the files in the folder and paste that onto a google spreadsheet where the code is linked to.
Use that spreadsheet as a database and send an email by using that database.


问:
how to prevent the openTip message box from disappearing when the mouse cursor leave the target html element
As described in the title, I need to keep the message tooltip created with opentip always showing. But by default, the message box will disappear when the mouse cursor leaves the HTML element that the message box attached to.

Please help modify the code below( or visit https://jsfiddle.net/671ptukx/ to edit the code directly) to achieve the effect as stated above.
Thank you very much in advance.

```<code>var myOpentip = new Opentip($("#targetTag"),"Need to prevent this tooltip message from disappearing when mouse leaves the \"Example Text\" area",{target:"#targetTag", tipJoint: "top" ,background:"wheat",showOn: 'creation'});
</code>```

答:
var myOpentip = new Opentip($("#targetTag"),"Need to prevent this tooltip message from disappearing when mouse leaves the \"Example Text\" area",{target:"#targetTag", tipJoint: "top" ,background:"wheat",showOn: 'creation',

    target: true,
    fixed: true,
    hideTrigger: "closeButton"});```

Use this script or check the updated fiddle ,https://jsfiddle.net/Hema_Nandagopal/671ptukx/2/

Body:
As described in the title, I need to keep the message tooltip created with opentip always showing. But by default, the message box will disappear when the mouse cursor leaves the HTML element that the message box attached to.

Please help modify the code below( or visit https://jsfiddle.net/671ptukx/ to edit the code directly) to achieve the effect as stated above.
Thank you very much in advance.

var myOpentip = new Opentip($("#targetTag"),"Need to prevent this tooltip message from disappearing when mouse leaves the \"Example Text\" area",{target:"#targetTag", tipJoint: "top" ,background:"wheat",showOn: 'creation'});

Body:
var myOpentip = new Opentip($("#targetTag"),"Need to prevent this tooltip message from disappearing when mouse leaves the \"Example Text\" area",{target:"#targetTag", tipJoint: "top" ,background:"wheat",showOn: 'creation',

    target: true,
    fixed: true,
    hideTrigger: "closeButton"});

Use this script or check the updated fiddle ,https://jsfiddle.net/Hema_Nandagopal/671ptukx/2/


问:
Kendo grid time field parsing
I need to parse a time(time only) field in kendo.

search results following code,

```<code>'#= kendo.toString(kendo.parseDate(dateCreated), 'MM/dd/yyyy HH:mm tt')#'
</code>```

Since I could get only time from database, above formatting method wont work for this instance.

15:10:00

above is the time format im getting from DB side. How could i parse this time in following format

03:10 PM

答:
You could use the "t" specifier in order to extract the time in the desired format:

```<code>kendo.toString(dateCreated, "t");
</code>```

Here is a Dojo example to demonstrate the above in action.

Title: Kendo grid time field parsing

Body:
I need to parse a time(time only) field in kendo.

search results following code,

'#= kendo.toString(kendo.parseDate(dateCreated), 'MM/dd/yyyy HH:mm tt')#'

Since I could get only time from database, above formatting method wont work for this instance.

15:10:00

above is the time format im getting from DB side. How could i parse this time in following format

03:10 PM

Body:
You could use the "t" specifier in order to extract the time in the desired format:

kendo.toString(dateCreated, "t");

Here is a Dojo example to demonstrate the above in action.


问:
Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development
I am rather new to Rails, and I am attempting to run an app from my console. When I open up the site, however, I see this error message. Does anyone have any insight on what it means?

When I try running "rails db:migrate RAILS_ENV=development" I just get:

```<code>Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development
</code>```

When I try running just "rails db:migrate" or "rake db:migrate" I get:

```<code>ArgumentError: wrong number of arguments (0 for 1)
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:600:in `migrate'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:573:in `check_pending!'
</code>```

Thank you so much!

答:
Goto your app folder and run below mention command:</p>

```<code>bin/rails db:migrate RAILS_ENV=development
</code>```

Body:
I am rather new to Rails, and I am attempting to run an app from my console. When I open up the site, however, I see this error message. Does anyone have any insight on what it means?

When I try running "rails db:migrate RAILS_ENV=development" I just get:

Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development

When I try running just "rails db:migrate" or "rake db:migrate" I get:

ArgumentError: wrong number of arguments (0 for 1)
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:600:in `migrate'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-5.0.1/lib/active_record/migration.rb:573:in `check_pending!'

Thank you so much!

Body:
Goto your app folder and run below mention command:

bin/rails db:migrate RAILS_ENV=development


问:
Fork GitHub to AzureDevOps?
This 2014 post indicates there was no native support for Forking from GitHub to AzureDevOps Git - a situation which does not seem to be changed. Is it still necessary to create a middleman to moderate changes from GitHub before pushing them into an AzureDevOps project? If so, does AzureDevOps Git Repo become the Origin? If so, can someone explain why?</p>

答:
it is very simple,in AzureDevOps the project you want to clone the repository or create a new team project, click code tab. Click  repository menu in Code Tab (it is on the top left side) and select Import repository.

Pick the right SourceType GIT/TFVS
Add the URL probably your github repository URL (but it can be any)
if it is publicly accessible this is it,
otherwise Check  Requires authorization provide username, Password or PAT and Name the new repository in AzureDevOps and done.

Title: Fork GitHub to AzureDevOps?


问:
Vertical spacing in Matplotlib latex fractions
I have created fractional values for my x tick labels, but the fractions look a little cramped to me. Is there a way to increase the vertical spacing?

```<code>import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.set_xlim(0, 10)
ax.set_xticklabels(
    ['$\\frac{{{0}}}{{{1}}}$'.format('M', x) for x in ax.get_xticks()],
    fontsize=12)

plt.show()
</code>```

答:
Using \dfrac might do the trick. However, we would need to modify the preamble.

```<code>import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
plt.rc('text.latex', preamble=r'\usepackage{amsmath}')
fig, ax = plt.subplots()

ax.set_xlim(0, 10)
ax.set_xticklabels(
    ['$\\dfrac{{{0}}}{{{1}}}$'.format('M', x) for x in ax.get_xticks()],
    fontsize=12)
</code>```

Some more information here: How to write your own LaTeX preamble in Matplotlib?

Body:
I have created fractional values for my x tick labels, but the fractions look a little cramped to me. Is there a way to increase the vertical spacing?

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.set_xlim(0, 10)
ax.set_xticklabels(
    ['$\\frac{{{0}}}{{{1}}}$'.format('M', x) for x in ax.get_xticks()],
    fontsize=12)

plt.show()

Body:
Using \dfrac might do the trick. However, we would need to modify the preamble.

import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
plt.rc('text.latex', preamble=r'\usepackage{amsmath}')
fig, ax = plt.subplots()

ax.set_xlim(0, 10)
ax.set_xticklabels(
    ['$\\dfrac{{{0}}}{{{1}}}$'.format('M', x) for x in ax.get_xticks()],
    fontsize=12)

Some more information here: How to write your own LaTeX preamble in Matplotlib?


问:
Apply function to each cell in DataFrame that depends on the column name in pandas
How can I apply function to each cell in a DataFrame that depends on the column name?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow depending on the column name:

```<code>import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)
</code>```

returns:

```<code>               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06
</code>```

Instead, I want the function that I applied to each cell to use the column name of the current cell as an argument.

I don't want to have to loop myself over each column, like:

```<code>def format2(cell_value, column_name):
    return '{0}_{1:.2f}'.format(column_name, cell_value)

for column_name in frame.columns.values:
    print('column_name: {0}'.format(column_name))
    frame[column_name]=frame[column_name].apply(format2, args=(column_name))
print(frame)
</code>```

Returns:

```<code>              b        d        e
Utah     b_1.62  d_-0.61  e_-0.53
Ohio    b_-1.07   d_0.87  e_-2.30
Texas    b_1.74  d_-0.76   e_0.32
Oregon  b_-0.25   d_1.46  e_-2.06
</code>```

(This is just one example. The functions I want to apply on the cells may do more than just appending the column name)

答:
I bit improved another answer, axis=0 is by default so can be omit:

```<code>a = frame.apply(lambda x: x.apply(format2,args=(x.name)))
print (a)
              b        d        e
Utah     b_1.62  d_-0.61  e_-0.53
Ohio    b_-1.07   d_0.87  e_-2.30
Texas    b_1.74  d_-0.76   e_0.32
Oregon  b_-0.25   d_1.46  e_-2.06
</code>```

Body:
How can I apply function to each cell in a DataFrame that depends on the column name?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow depending on the column name:

import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)

returns:

               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06

Instead, I want the function that I applied to each cell to use the column name of the current cell as an argument.

I don't want to have to loop myself over each column, like:

def format2(cell_value, column_name):
    return '{0}_{1:.2f}'.format(column_name, cell_value)

for column_name in frame.columns.values:
    print('column_name: {0}'.format(column_name))
    frame[column_name]=frame[column_name].apply(format2, args=(column_name))
print(frame)

Returns:

              b        d        e
Utah     b_1.62  d_-0.61  e_-0.53
Ohio    b_-1.07   d_0.87  e_-2.30
Texas    b_1.74  d_-0.76   e_0.32
Oregon  b_-0.25   d_1.46  e_-2.06

(This is just one example. The functions I want to apply on the cells may do more than just appending the column name)

Body:
I bit improved another answer, axis=0 is by default so can be omit:

a = frame.apply(lambda x: x.apply(format2,args=(x.name)))
print (a)
              b        d        e
Utah     b_1.62  d_-0.61  e_-0.53
Ohio    b_-1.07   d_0.87  e_-2.30
Texas    b_1.74  d_-0.76   e_0.32
Oregon  b_-0.25   d_1.46  e_-2.06


问:
Laravel Route issues with Route order in web.php
I have problem with routes in Laravel, I'm following one tutorial and we have this routes listed in web.php file

```<code>Route::get('/home', 'HomeController@index')->name('home');
Route::get('/blog', 'BlogController@index')->name('blog');
Route::get('/blog/create', 'BlogController@create');
Route::post('/blog/store', 'BlogController@store');
Route::get('/blog/{id}', 'BlogController@show');
Route::get('/blog/{id}/edit', 'BlogController@edit');
Route::patch('/blog/{id}', 'BlogController@update');
Route::delete('/blog/{id}', 'BlogController@destroy');
Route::get('/blog/bin', 'BlogController@bin');
</code>```

Problem is in the last route to blog/bin, it is not working if I keep it down below however in tutorial we have moved it to top of other routes and then it's working fine, instructor said that there is some conflict in routes and that that last route need to be at top in order to work but didn't explain at all why ? Can anybody explain in little more details, as I'm really just started with Laravel...

答:
You can't define a type on a route paramater. So Laravel is guessing that you parameter can be a Integer or even a String.

Based on that, If you try to access /blog/bin. Laravel will try to use the route /blog/{id} with "bin" in id param.

Here a better answer than mine : https://laracasts.com/discuss/channels/laravel/order-of-routes-being-applied

Body:
I have problem with routes in Laravel, I'm following one tutorial and we have this routes listed in web.php file

Route::get('/home', 'HomeController@index')->name('home');
Route::get('/blog', 'BlogController@index')->name('blog');
Route::get('/blog/create', 'BlogController@create');
Route::post('/blog/store', 'BlogController@store');
Route::get('/blog/{id}', 'BlogController@show');
Route::get('/blog/{id}/edit', 'BlogController@edit');
Route::patch('/blog/{id}', 'BlogController@update');
Route::delete('/blog/{id}', 'BlogController@destroy');
Route::get('/blog/bin', 'BlogController@bin');

Problem is in the last route to blog/bin, it is not working if I keep it down below however in tutorial we have moved it to top of other routes and then it's working fine, instructor said that there is some conflict in routes and that that last route need to be at top in order to work but didn't explain at all why ? Can anybody explain in little more details, as I'm really just started with Laravel...


问:
PHP: MYSQLI Change Order By Style

Hi, i want to get data from chat table like this:

```<code>6
7
8
</code>```

My Code show like this:

```<code>8
7
6
</code>```

Code:

```<code>"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"
</code>```

答:
```<code>SELECT * FROM `chat`
WHERE `chat-code` = 'vm1mxo3dpi9gzuo'
AND (`user_1` = '1' OR `user_2` = '1')
ORDER BY id LIMIT 3 OFFSET 5
</code>```

Try above query.

Title: PHP: MYSQLI Change Order By Style

Body:
Hi, i want to get data from chat table like this:

6
7
8

My Code show like this:

8
7
6

Code:

"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"

Body:
SELECT * FROM `chat`
WHERE `chat-code` = 'vm1mxo3dpi9gzuo'
AND (`user_1` = '1' OR `user_2` = '1')
ORDER BY id LIMIT 3 OFFSET 5

Try above query.


问:
Vue.js app no errors but white page
I'm trying to learn Vue.
I read this tutorial and I'm trying to split it in single file components using the standard vue-cli webpack template. I don't have any error in console but the page is white, and I cannot understand why.

This is my main.js file

```<code>import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false
window.axios = require('axios');

const NYTBaseUrl = "https://api.nytimes.com/svc/topstories/v2/";
const ApiKey = "18e1540d187c4b46bae767782750f9fd";
const SECTIONS = "home, arts, automobiles, books, business, fashion, food, health, insider, magazine, movies, national, nyregion, obituaries, opinion, politics, realestate, science, sports, sundayreview, technology, theater, tmagazine, travel, upshot, world";

function buildUrl (url) {
  return NYTBaseUrl + url + ".json?api-key=" + ApiKey
}

const vm = new Vue({
  el: '#app',
  data: {
    results: [],
    sections: SECTIONS.split(', '), // create an array of the sections
    section: 'home', // set default section to 'home'
    loading: true,
    title: ''
  },
  mounted () {
    this.getPosts('home');
  },
  methods: {
    getPosts(section) {
      let url = buildUrl(section);
      axios.get(url).then((response) => {
        this.loading = false;
        this.results = response.data.results;
        let title = this.section !== 'home' ? "Top stories in '"+ this.section + "' today" : "Top stories today";
        this.title = title + "(" + response.data.num_results+ ")";
      }).catch((error) => { console.log(error); });
    }
  }
});
</code>```

And this is the App.vue file

```<code><template>
  <div id="app">
    <h1>Test</h1>
    <product-list></product-list>
  </div>
</template>

<script>
import Products from './components/Products'

export default {
  name: 'app',
  components: {
    Products
  }
}
</script>

<style lang="sass" >
  @import '~bulma/sass/utilities/initial-variables.sass'
  @import "~bulma/sass/utilities/_all"
  @import "~bulma/sass/base/_all"
  @import "~bulma/sass/grid/columns"
  @import "~bulma/sass/components/_all"
</style>
</code>```

I also create a Products.vue file in the components folder

```<code><template id="product-list">
  <section>
    <div class="row" v-for="posts in processedPosts">
      <div class="columns large-3 medium-6" v-for="post in posts">
        <div class="card">
        <div class="card-divider">
        {{ post.title }}
        </div>
        <a :href="post.url" target="_blank"><img :src="post.image_url"></a>
        <div class="card-section">
          <p>{{ post.abstract }}</p>
        </div>
      </div>
      </div>
    </div>
  </section>

</template>

Vue.component('Products', {
  props: ['results'],
  template: "#product-list",
  computed: {
    processedPosts() {
      let posts = this.results;

      // Add image_url attribute
      posts.map(post => {
        let imgObj = post.multimedia.find(media => media.format === "superJumbo");
        post.image_url = imgObj ? imgObj.url : "http://placehold.it/300x200?text=N/A";
      });

      // Put Array into Chunks
      let i, j, chunkedArray = [],
        chunk = 4;
      for (i = 0, j = 0; i < posts.length; i += chunk, j++) {
        chunkedArray[j] = posts.slice(i, i + chunk);
      }
      return chunkedArray;
    }
  }
});
</code>```

Everything looks fine for me (except for the window.axios = require('axios'); that I don't understand why is not present in the original tutorial) but the page is blank and also the  tag I add for debug is not present in the DOM.

Edit

Looks like the code is not compiled.

My page source code is

```<code><body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  <script type="text/javascript" src="/app.js"></script>

</body>
</code>```

** Edit 2 **

I understand the problem. This is my index.html.

答:
Next time to debug your code - first you should take a look at browser console for errors.

You can see full code of this tutorial here - https://github.com/sitepoint-editors/vuejs-news
Just make sure you write code like it's shown on github files.

Title: Vue.js app no errors but white page

Body:
I'm trying to learn Vue.
I read this tutorial and I'm trying to split it in single file components using the standard vue-cli webpack template. I don't have any error in console but the page is white, and I cannot understand why.

This is my main.js file

import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false
window.axios = require('axios');

const NYTBaseUrl = "https://api.nytimes.com/svc/topstories/v2/";
const ApiKey = "18e1540d187c4b46bae767782750f9fd";
const SECTIONS = "home, arts, automobiles, books, business, fashion, food, health, insider, magazine, movies, national, nyregion, obituaries, opinion, politics, realestate, science, sports, sundayreview, technology, theater, tmagazine, travel, upshot, world";

function buildUrl (url) {
  return NYTBaseUrl + url + ".json?api-key=" + ApiKey
}

const vm = new Vue({
  el: '#app',
  data: {
    results: [],
    sections: SECTIONS.split(', '), // create an array of the sections
    section: 'home', // set default section to 'home'
    loading: true,
    title: ''
  },
  mounted () {
    this.getPosts('home');
  },
  methods: {
    getPosts(section) {
      let url = buildUrl(section);
      axios.get(url).then((response) => {
        this.loading = false;
        this.results = response.data.results;
        let title = this.section !== 'home' ? "Top stories in '"+ this.section + "' today" : "Top stories today";
        this.title = title + "(" + response.data.num_results+ ")";
      }).catch((error) => { console.log(error); });
    }
  }
});

And this is the App.vue file

<template>

Test

    <product-list></product-list>

</template>

I also create a Products.vue file in the components folder

<template id="product-list">

        {{ post.title }}

{{ post.abstract }}

</template>

Vue.component('Products', {
  props: ['results'],
  template: "#product-list",
  computed: {
    processedPosts() {
      let posts = this.results;

      // Add image_url attribute
      posts.map(post => {
        let imgObj = post.multimedia.find(media => media.format === "superJumbo");
        post.image_url = imgObj ? imgObj.url : "http://placehold.it/300x200?text=N/A";
      });

      // Put Array into Chunks
      let i, j, chunkedArray = [],
        chunk = 4;
      for (i = 0, j = 0; i < posts.length; i += chunk, j++) {
        chunkedArray[j] = posts.slice(i, i + chunk);
      }
      return chunkedArray;
    }
  }
});

Everything looks fine for me (except for the window.axios = require('axios'); that I don't understand why is not present in the original tutorial) but the page is blank and also the  tag I add for debug is not present in the DOM.

Edit

Looks like the code is not compiled.

My page source code is

** Edit 2 **

I understand the problem. This is my index.html.


问:
php form action not reading php variable
It is working when I use page name but not working when I am using page name in php variable.

```<code><?php $action_page = "page2.php"; ?>
<form action="<?php $action_page; ?>" method="post">

</form>
</code>```

Unable to get it where I am wrong.

答:
You need add echo before the variable-

```<code><?php $action_page = "page2.php"; ?>
<form action="<?php echo  $action_page ?>" method="post">
</form>
</code>```

Body:
It is working when I use page name but not working when I am using page name in php variable.

<?php $action_page = "page2.php"; ?>
<form action="<?php $action_page; ?>" method="post">

</form>

Unable to get it where I am wrong.

Body:
You need add echo before the variable-

<?php $action_page = "page2.php"; ?>
<form action="<?php echo  $action_page ?>" method="post">
</form>


问:
xpages register a anonymous user to names.nsf with login name and email
Case: Create a web application to register user through the Name.nsf on the server.

userA

userB

means there have 2 database related.

First database: Anonymous(web) allow to key in there information through the database.

Second database: Names.nsf

First database with "full" access user must be allow to create a user in the names nsf or create an email address for user!

Question

Do i just need to link the names.nsf in server view ($VIMPeopleByLastName) and create document of those web-user?

答:
I found solution using notes agent to update it. I not sure xpages javascript way of writing it. Below is my script of using NotesRegistration : RegisterNewUser</p>

```<code>Option Public
Option Declare

Sub Initialize
'   this agent use on [register] button locate on [request form] xpages

Dim s As New NotesSession, db As NotesDatabase, a As NotesAgent
Dim doc As NotesDocument
Set db = s.Currentdatabase
Set a = s.Currentagent
Set doc = s.Documentcontext     '   uidoc

Dim certid As String 'full path of cert id
Dim certpasswd As String
Dim OU As String
Dim lastname As String
Dim firstname As String
Dim middleinit As String
Dim usrIdpath As String
Dim mailsvr As String
Dim mailfile As String
Dim userpasswd As String
Dim internetpath As String

Dim depvw As NotesView, depdoc As NotesDocument
Set depvw = db.Getview("Department sort by dept")
Set depdoc = depvw.Getdocumentbykey(doc.Dept(0), True)
If Not depdoc Is Nothing Then
    certid = depdoc.IdPath(0)                                       '   full path of cert id
    certpasswd = depdoc.IdPassword(0)                               '   Cert id password(password)
    OU = depdoc.Dept(0)                                             '   Application (department to register)
    lastname= doc.SelectMail(0)                                     '   current document selected mail (person)
    firstname = ""      '                                            [din't used]
    middleinit = ""                                                 '   [din't used]
    usrIdpath = depdoc.DptIdStor(0) +doc.SelectMail(0)+ ".id"       '   user path
    mailsvr = depdoc.MailSvr(0)                                     '   mail svr
    mailfile = depdoc.MailLocation(0)+doc.SelectMail(0)             '   Mail\person
    userpasswd= depdoc.UserPassword(0)                              '   User password
    internetpath = doc.SelectMail(0)+depdoc.InternetPath(0)         '   mail address

End If

Dim reg As New NotesRegistration
Dim dt As Variant
dt = DateNumber(Year(Today)+1, Month(Today), Day(Today))

reg.RegistrationServer = mailsvr        '"CN=ServerOne/O=dev"
reg.CreateMailDb = True                 '
reg.CertifierIDFile = certid            '"C:\IBM\Domino\data\office.id"
reg.Expiration = dt
reg.IDType = ID_HIERARCHICAL
reg.MinPasswordLength = 1               ' password strength
reg.IsNorthAmerican = True
reg.OrgUnit = OU                        '"Application"
reg.RegistrationLog = "log.nsf"
reg.UpdateAddressBook = True
reg.StoreIDInAddressBook = True
reg.MailInternetAddress =  internetpath '"person@devsv1.pcs.com.my"

Call reg.RegisterNewUser(lastname, _    ' last name
usridpath, _                            '"C:\IBM\Domino\data\ +name+.id"    ' file to be created
mailsvr, _                              '"CN=ServerOne/O=dev"               ' mail server
firstname, _                            '                                   ' first name
middleInit, _                           '                                   ' middle initial
certpasswd, _                           '"office"                           ' certifier password
"", _                                   ' location field
"", _                                   ' comment field
mailfile, _                             '"mail\person.nsf"                 ' mail file
"", _                                   ' Forwarding domain
userpasswd, _                           '"password", _                   ' user password
NOTES_DESKTOP_CLIENT)                   ' user type

End Sub
</code>```

Body:
I found solution using notes agent to update it. I not sure xpages javascript way of writing it. Below is my script of using NotesRegistration : RegisterNewUser

Option Public
Option Declare

Sub Initialize
'   this agent use on [register] button locate on [request form] xpages

Dim s As New NotesSession, db As NotesDatabase, a As NotesAgent
Dim doc As NotesDocument
Set db = s.Currentdatabase
Set a = s.Currentagent
Set doc = s.Documentcontext     '   uidoc

Dim certid As String 'full path of cert id
Dim certpasswd As String
Dim OU As String
Dim lastname As String
Dim firstname As String
Dim middleinit As String
Dim usrIdpath As String
Dim mailsvr As String
Dim mailfile As String
Dim userpasswd As String
Dim internetpath As String

Dim depvw As NotesView, depdoc As NotesDocument
Set depvw = db.Getview("Department sort by dept")
Set depdoc = depvw.Getdocumentbykey(doc.Dept(0), True)
If Not depdoc Is Nothing Then
    certid = depdoc.IdPath(0)                                       '   full path of cert id
    certpasswd = depdoc.IdPassword(0)                               '   Cert id password(password)
    OU = depdoc.Dept(0)                                             '   Application (department to register)
    lastname= doc.SelectMail(0)                                     '   current document selected mail (person)
    firstname = ""      '                                            [din't used]
    middleinit = ""                                                 '   [din't used]
    usrIdpath = depdoc.DptIdStor(0) +doc.SelectMail(0)+ ".id"       '   user path
    mailsvr = depdoc.MailSvr(0)                                     '   mail svr
    mailfile = depdoc.MailLocation(0)+doc.SelectMail(0)             '   Mail\person
    userpasswd= depdoc.UserPassword(0)                              '   User password
    internetpath = doc.SelectMail(0)+depdoc.InternetPath(0)         '   mail address

End If

Dim reg As New NotesRegistration
Dim dt As Variant
dt = DateNumber(Year(Today)+1, Month(Today), Day(Today))

reg.RegistrationServer = mailsvr        '"CN=ServerOne/O=dev"
reg.CreateMailDb = True                 '
reg.CertifierIDFile = certid            '"C:\IBM\Domino\data\office.id"
reg.Expiration = dt
reg.IDType = ID_HIERARCHICAL
reg.MinPasswordLength = 1               ' password strength
reg.IsNorthAmerican = True
reg.OrgUnit = OU                        '"Application"
reg.RegistrationLog = "log.nsf"
reg.UpdateAddressBook = True
reg.StoreIDInAddressBook = True
reg.MailInternetAddress =  internetpath '"person@devsv1.pcs.com.my"

Call reg.RegisterNewUser(lastname, _    ' last name
usridpath, _                            '"C:\IBM\Domino\data\ +name+.id"    ' file to be created
mailsvr, _                              '"CN=ServerOne/O=dev"               ' mail server
firstname, _                            '                                   ' first name
middleInit, _                           '                                   ' middle initial
certpasswd, _                           '"office"                           ' certifier password
"", _                                   ' location field
"", _                                   ' comment field
mailfile, _                             '"mail\person.nsf"                 ' mail file
"", _                                   ' Forwarding domain
userpasswd, _                           '"password", _                   ' user password
NOTES_DESKTOP_CLIENT)                   ' user type

End Sub