问:
How can I get the result of a request after executing the request using c++ builder XE6 and Firebird?
After connecting to a Firebird database with C++ builder, I cannot get a result from a simple select request.

I have some confusion about a lot of members of classes:

```<code>void __fastcall TForm2::btn1Click(TObject *Sender)
{  TSQLConnection   co = new TSQLConnection(this);
   Base_Firebird *fb = new Base_Firebird()  ;
   bool  bl = fb->Connecter(co);
   String sqlstring = "select nom_action from T_ACTION where CLE_ACTION=6 ";
   if (bl)
      TSQLQuery *req = new TSQLQuery(NULL) ;
   req->SQLConnection = co ;
   req->SQL->Add(sqlstring);
   req->Open() ;
  }
</code>```

My problem is here after opening the TSQLQuery, I don't know how I can get the result and execute the command.

答:
Read Embarcadero's documentation.  There are whole chapters on how to work the SQL components you are using, including:

How To Perform Database Procedures

Navigating Datasets

Using dbExpress

Using dbExpress Components Index

Using TSQLQuery

Data.SqlExpr.TSQLQuery

For example:

```<code>void __fastcall TForm2::btn1Click(TObject *Sender)
{
    TSQLConnection *co = new TSQLConnection(NULL);
    Base_Firebird *fb = new Base_Firebird();
    if (fb->Connecter(co))
    {
        TSQLQuery *req = new TSQLQuery(NULL);
        req->SQLConnection = co;
        req->SQL->Text = "select nom_action from T_ACTION where CLE_ACTION=6";
        req->Open();
        while (!req->Eof)
        {
            // use req->Fields as needed...
            req->Next();
        }
        delete req;
    }
    delete fb;
    delete co;
}
</code>```

Body:
After connecting to a Firebird database with C++ builder, I cannot get a result from a simple select request.

I have some confusion about a lot of members of classes:

void __fastcall TForm2::btn1Click(TObject *Sender)
{  TSQLConnection   co = new TSQLConnection(this);
   Base_Firebird *fb = new Base_Firebird()  ;
   bool  bl = fb->Connecter(co);
   String sqlstring = "select nom_action from T_ACTION where CLE_ACTION=6 ";
   if (bl)
      TSQLQuery *req = new TSQLQuery(NULL) ;
   req->SQLConnection = co ;
   req->SQL->Add(sqlstring);
   req->Open() ;
  }

My problem is here after opening the TSQLQuery, I don't know how I can get the result and execute the command.

Body:
Read Embarcadero's documentation.  There are whole chapters on how to work the SQL components you are using, including:

How To Perform Database Procedures

Navigating Datasets

Using dbExpress

Using dbExpress Components Index

Using TSQLQuery

Data.SqlExpr.TSQLQuery

For example:

void __fastcall TForm2::btn1Click(TObject *Sender)
{
    TSQLConnection *co = new TSQLConnection(NULL);
    Base_Firebird *fb = new Base_Firebird();
    if (fb->Connecter(co))
    {
        TSQLQuery *req = new TSQLQuery(NULL);
        req->SQLConnection = co;
        req->SQL->Text = "select nom_action from T_ACTION where CLE_ACTION=6";
        req->Open();
        while (!req->Eof)
        {
            // use req->Fields as needed...
            req->Next();
        }
        delete req;
    }
    delete fb;
    delete co;
}


来源: stackexchange

问:
FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri()) return null on Facebook
I've developed an mvc 5 application using nopcommerce and i use facebook login using External callback it was working but now it is not working and i can't find out actual problem. And using this below code

this.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

and it's returning me always null and authentication status failed i searched on web an do every thing and followed that steps but still i can't login with facebook.

My code is like this in FacebookProviderAuthorizer.cs

```<code>private AuthorizeState VerifyAuthentication(string returnUrl)
{
   var authResult = DotNetOpenAuth.AspNet.Clients.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

   if (authResult.IsSuccessful)
   {
   }
}
</code>```

And then write Call back method

```<code>private Uri GenerateLocalCallbackUri()
{
    string url = string.Format("{0}plugins/externalauthFacebook/logincallback/", _webHelper.GetStoreLocation());
    return new Uri(url);
}
</code>```

Then generate service login url

```<code>private Uri GenerateServiceLoginUrl()
{
   //code copied from DotNetOpenAuth.AspNet.Clients.FacebookClient file
   var builder = new UriBuilder("https://www.facebook.com/dialog/oauth");
   var args = new Dictionary<string, string>();
   args.Add("client_id", _facebookExternalAuthSettings.ClientKeyIdentifier);
   args.Add("redirect_uri", GenerateLocalCallbackUri().AbsoluteUri);
   args.Add("response_type", "token");
   args.Add("scope", "email");
   AppendQueryArgs(builder, args);
   return builder.Uri;
}
</code>```

答:
We ran into this same issue on Monday, 3/27/2017, when Facebook discontinued support for their Graph API v2.2.

We are also using DotNetOpenAuth, which was originally installed via Nuget. The source code is available at the link below:

https://github.com/DotNetOpenAuth/DotNetOpenAuth

Specifically, we discovered that our code was utilizing the 4.3 branch which contains the source code for the DotNetOpenAuth.AspNet.DLL. Upon inspecting the source, we discovered the problem is with this snippet of code from DotNetOpenAuth.AspNet\Clients\OAuth2\FacebookClient.cs, located within the QueryAccessToken method:

```<code>using (WebClient client = new WebClient()) {
     string data = client.DownloadString(builder.Uri);
     if (string.IsNullOrEmpty(data)) {
          return null;
     }

     var parsedQueryString = HttpUtility.ParseQueryString(data);
     return parsedQueryString["access_token"];
}
</code>```

The issue, specifically, is the ParseQueryString call. Starting with v2.3 of the API, the data is no longer returned as an HTML query string, but in standard JSON format.

To fix this, we created our own custom class inheriting OAuth2Client and imported most of the same code from FacebookClient.cs. We then replaced the above code snippet with code that parses the JSON response to extract the access_token, and returns that instead. You can see an example of how to do this in the same FacebookClient class, within the GetUserData method:

```<code>FacebookGraphData graphData;
var request =
    WebRequest.Create(
        "https://graph.facebook.com/me?access_token=" +
             MessagingUtilities.EscapeUriDataStringRfc3986(accessToken));
using (var response = request.GetResponse()) {
     using (var responseStream = response.GetResponseStream()) {
        graphData = JsonHelper.Deserialize<FacebookGraphData>(responseStream);
     }
}
</code>```

The only other change was to register our custom class in place of the FacebookClient class so the OAuth callback uses it to handle the post from Facebook's API. Once we did this, everything worked smoothly again.

ContentLicense: CC BY-SA 3.0

Body:
I've developed an mvc 5 application using nopcommerce and i use facebook login using External callback it was working but now it is not working and i can't find out actual problem. And using this below code

this.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

and it's returning me always null and authentication status failed i searched on web an do every thing and followed that steps but still i can't login with facebook.

My code is like this in FacebookProviderAuthorizer.cs

private AuthorizeState VerifyAuthentication(string returnUrl)
{
   var authResult = DotNetOpenAuth.AspNet.Clients.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

   if (authResult.IsSuccessful)
   {
   }
}

And then write Call back method

private Uri GenerateLocalCallbackUri()
{
    string url = string.Format("{0}plugins/externalauthFacebook/logincallback/", _webHelper.GetStoreLocation());
    return new Uri(url);
}

Then generate service login url

private Uri GenerateServiceLoginUrl()
{
   //code copied from DotNetOpenAuth.AspNet.Clients.FacebookClient file
   var builder = new UriBuilder("https://www.facebook.com/dialog/oauth");
   var args = new Dictionary<string, string>();
   args.Add("client_id", _facebookExternalAuthSettings.ClientKeyIdentifier);
   args.Add("redirect_uri", GenerateLocalCallbackUri().AbsoluteUri);
   args.Add("response_type", "token");
   args.Add("scope", "email");
   AppendQueryArgs(builder, args);
   return builder.Uri;
}

Body:
We ran into this same issue on Monday, 3/27/2017, when Facebook discontinued support for their Graph API v2.2.

We are also using DotNetOpenAuth, which was originally installed via Nuget. The source code is available at the link below:

https://github.com/DotNetOpenAuth/DotNetOpenAuth

Specifically, we discovered that our code was utilizing the 4.3 branch which contains the source code for the DotNetOpenAuth.AspNet.DLL. Upon inspecting the source, we discovered the problem is with this snippet of code from DotNetOpenAuth.AspNet\Clients\OAuth2\FacebookClient.cs, located within the QueryAccessToken method:

using (WebClient client = new WebClient()) {
     string data = client.DownloadString(builder.Uri);
     if (string.IsNullOrEmpty(data)) {
          return null;
     }

     var parsedQueryString = HttpUtility.ParseQueryString(data);
     return parsedQueryString["access_token"];
}

The issue, specifically, is the ParseQueryString call. Starting with v2.3 of the API, the data is no longer returned as an HTML query string, but in standard JSON format.

To fix this, we created our own custom class inheriting OAuth2Client and imported most of the same code from FacebookClient.cs. We then replaced the above code snippet with code that parses the JSON response to extract the access_token, and returns that instead. You can see an example of how to do this in the same FacebookClient class, within the GetUserData method:

FacebookGraphData graphData;
var request =
    WebRequest.Create(
        "https://graph.facebook.com/me?access_token=" +
             MessagingUtilities.EscapeUriDataStringRfc3986(accessToken));
using (var response = request.GetResponse()) {
     using (var responseStream = response.GetResponseStream()) {
        graphData = JsonHelper.Deserialize<FacebookGraphData>(responseStream);
     }
}

The only other change was to register our custom class in place of the FacebookClient class so the OAuth callback uses it to handle the post from Facebook's API. Once we did this, everything worked smoothly again.


问:
mips64el-linux-android-g++: error: unrecognized command line option '-mfpu=neon'
I am trying to run a NDK and OpenCV related project. The project builds errorless. But when i run the application I get the error:

mips64el-linux-android-g++: error: unrecognized command line option '-mfpu=neon'

My Application.mk file looks like this:

```<code>APP_STL := gnustl_shared
APP_CPPFLAGS := -frtti -fexceptions

# NEON
APP_CFLAGS += -mfpu=neon
APP_ABI := armeabi-v7a
APP_PLATFORM := android-18
APP_OPTIM := debug
APP_MODULES := nVisoDemo-1.1
NDK_TOOLCHAIN_VERSION := 4.9
HAVE_LIB_CEVA := false # CUSTOM VARIABLE USED (NOT ANYMORE) IN Android.mk
</code>```

Android.mk:

```<code># Freeimage
include $(CLEAR_VARS)
LOCAL_MODULE := libfreeimage
LOCAL_ARM_NEON := true
#LOCAL_SRC_FILES := $(NVISO_LIBS_DIR)/libfreeimage-3.14.so
LOCAL_SRC_FILES := D:/Siddharth/StudioProjects/OpenCVDemo/nvsdk/src/main/jni/Framework/nviso/libs/armeabi-v7a/libfreeimage-3.14.so
include $(PREBUILT_SHARED_LIBRARY)
</code>```

I tried to remove APP_CFLAGS += -mfpu=neon from application.mk file but then it gives all the compilation errors in cpp files..

Also to mention that the above code works flawlessly in Eclipse...but the problem is coming in Android Studio only

Any help would be appreciated..Thanks in advance..

答:
By default you'll build for every NDK ABI: arm5, arm7, arm64, mips, mips64, x86, and x86_64, but -mfpu=neon is only valid for arm7 and arm64.

In general for cases like this you need to protect architecture specific flags by testing against TARGET_ARCH_ABI, but for NEON support there's a flag just for this:

```<code>LOCAL_ARM_NEON := true
</code>```

Add that to each of your modules in your Android.mk.

Body:
I am trying to run a NDK and OpenCV related project. The project builds errorless. But when i run the application I get the error:

mips64el-linux-android-g++: error: unrecognized command line option '-mfpu=neon'

My Application.mk file looks like this:

APP_STL := gnustl_shared
APP_CPPFLAGS := -frtti -fexceptions

# NEON
APP_CFLAGS += -mfpu=neon
APP_ABI := armeabi-v7a
APP_PLATFORM := android-18
APP_OPTIM := debug
APP_MODULES := nVisoDemo-1.1
NDK_TOOLCHAIN_VERSION := 4.9
HAVE_LIB_CEVA := false # CUSTOM VARIABLE USED (NOT ANYMORE) IN Android.mk

Android.mk:

# Freeimage
include $(CLEAR_VARS)
LOCAL_MODULE := libfreeimage
LOCAL_ARM_NEON := true
#LOCAL_SRC_FILES := $(NVISO_LIBS_DIR)/libfreeimage-3.14.so
LOCAL_SRC_FILES := D:/Siddharth/StudioProjects/OpenCVDemo/nvsdk/src/main/jni/Framework/nviso/libs/armeabi-v7a/libfreeimage-3.14.so
include $(PREBUILT_SHARED_LIBRARY)

I tried to remove APP_CFLAGS += -mfpu=neon from application.mk file but then it gives all the compilation errors in cpp files..

Also to mention that the above code works flawlessly in Eclipse...but the problem is coming in Android Studio only

Any help would be appreciated..Thanks in advance..

Body:
By default you'll build for every NDK ABI: arm5, arm7, arm64, mips, mips64, x86, and x86_64, but -mfpu=neon is only valid for arm7 and arm64.

In general for cases like this you need to protect architecture specific flags by testing against TARGET_ARCH_ABI, but for NEON support there's a flag just for this:

LOCAL_ARM_NEON := true

Add that to each of your modules in your Android.mk.


问:
Html linked to another html
I am creating a navigation bar on my pages and im having trouble moving from one html doc to another. Its weird to word so i drew a picture ( pic )
Both html documents are within the same folder and i have cleared the cache just in case. The problem is i can move from 'mainpage' to 'about' page but not in reverse. Any tips or comments?

Folder of files

Main page

```<code><div class="icon-menu">
    <i class="fa fa-bars"></i> Menu
</div>

<div class="menu">
    <div class="icon-close">
        <img src="images/close_icon.png">
    </div>

    <nav>
        <ul>
            <li><a href="mainpage.html">Home</a></li>
            <li><a href="about.html">About</a></li>
        </ul>
    </nav>
</div>
</code>```

About page

```<code><div class="menu">
    <div class="icon-close">
        <img src="images/close_icon.png">
    </div>
    <nav>
        <ul>
            <li><a href="mainpage.html">Home</a></li>
            <li><a href="about.html">About</a></li>
            <li><a href="map.html">Map</a></li>
            <li><a href="help.html">Help</a></li>
        </ul>
    </nav>
</div>
</code>```

答:
It should work fine. Possible errors are that filename of mainpage may have an error or if you are using any framework, it may produce some error.
This code is working fine in plain html without any css or js. So provide more information in case.  </p>

Title: Html linked to another html

Body:
I am creating a navigation bar on my pages and im having trouble moving from one html doc to another. Its weird to word so i drew a picture ( pic )
Both html documents are within the same folder and i have cleared the cache just in case. The problem is i can move from 'mainpage' to 'about' page but not in reverse. Any tips or comments?

Folder of files

Main page

     Menu

Home

About

About page

Home

About

Map

Help


问:
Exception when adding a PdfFormField to a big PDF
I am adding a PdfTextFormField over a Table cell using a custom renderer, as per the iText7 example code in CreateFormInTable.java. This works initially, until I create a Table on page 3 or later of the PDF, at which point I'm getting an exception:

```<code>Caused by: java.lang.NullPointerException
at com.itextpdf.kernel.pdf.PdfDictionary.get(PdfDictionary.java:552)
at com.itextpdf.kernel.pdf.PdfDictionary.getAsArray(PdfDictionary.java:156)
at com.itextpdf.kernel.pdf.PdfPage.getAnnotations(PdfPage.java:746)
at ...pdf.annot.PdfAnnotation.getPage(PdfAnnotation.java:435)
at ...forms.fields.PdfFormField.regenerateField(PdfFormField.java:1761)
at ...forms.fields.PdfFormField.setValue(PdfFormField.java:1038)
at ...forms.fields.PdfFormField.setValue(PdfFormField.java:999)
at ...forms.fields.PdfFormField.setValue(PdfFormField.java:994)
etc.
</code>```

It seems fairly easy to reproduce, and I can provide a full code sample if you want, but a simple way to see the problem is to insert:

```<code>for (int i=1; i < 2; i++)  // Change 2 to 3 and you get an NPE
{
    Paragraph  para = new Paragraph("Page "+ i);
    doc.add( para );
    doc.add( new AreaBreak( AreaBreakType.NEXT_PAGE ) );
}
</code>```

straight after the Document constructor in the aforementioned iText7 Java sample file at:

http://developers.itextpdf.com/examples/form-examples/clone-create-fields-table#2350-createformintable.java

I've tested it on 7.0.1 and 7.0.2, with same result.

答:
Well, currently some of the form-related functionality requires the whole PDF document structure to be in memory to operate. This means that no object can be flushed. But layout's DocumentRenderer flushes the pages when possible. The problem reproduces only for three or more pages because there is a small "window" of unflushed pages.

This is indeed not mentioned in the sample and can be improved in the future. In the current version, to get the desired PDF, you can set the Document to operate in "postpone flushing" mode using the following constructor:

```<code>Document doc = new Document(pdfDoc, PageSize.A4, false);
</code>```

Body:
I am adding a PdfTextFormField over a Table cell using a custom renderer, as per the iText7 example code in CreateFormInTable.java. This works initially, until I create a Table on page 3 or later of the PDF, at which point I'm getting an exception:

Caused by: java.lang.NullPointerException
at com.itextpdf.kernel.pdf.PdfDictionary.get(PdfDictionary.java:552)
at com.itextpdf.kernel.pdf.PdfDictionary.getAsArray(PdfDictionary.java:156)
at com.itextpdf.kernel.pdf.PdfPage.getAnnotations(PdfPage.java:746)
at ...pdf.annot.PdfAnnotation.getPage(PdfAnnotation.java:435)
at ...forms.fields.PdfFormField.regenerateField(PdfFormField.java:1761)
at ...forms.fields.PdfFormField.setValue(PdfFormField.java:1038)
at ...forms.fields.PdfFormField.setValue(PdfFormField.java:999)
at ...forms.fields.PdfFormField.setValue(PdfFormField.java:994)
etc.

It seems fairly easy to reproduce, and I can provide a full code sample if you want, but a simple way to see the problem is to insert:

for (int i=1; i < 2; i++)  // Change 2 to 3 and you get an NPE
{
    Paragraph  para = new Paragraph("Page "+ i);
    doc.add( para );
    doc.add( new AreaBreak( AreaBreakType.NEXT_PAGE ) );
}

straight after the Document constructor in the aforementioned iText7 Java sample file at:

http://developers.itextpdf.com/examples/form-examples/clone-create-fields-table#2350-createformintable.java

I've tested it on 7.0.1 and 7.0.2, with same result.

Body:
Well, currently some of the form-related functionality requires the whole PDF document structure to be in memory to operate. This means that no object can be flushed. But layout's DocumentRenderer flushes the pages when possible. The problem reproduces only for three or more pages because there is a small "window" of unflushed pages.

This is indeed not mentioned in the sample and can be improved in the future. In the current version, to get the desired PDF, you can set the Document to operate in "postpone flushing" mode using the following constructor:

Document doc = new Document(pdfDoc, PageSize.A4, false);


问:
Using rbind to merge all columns in data frame
I have the following data frame

```<code>> mydata
X1  X2  X3  X4  X5  X6
1   1   1   1   1   1
1   0   0   0   0   1
1   1   0   0   0   0
1   0   1   1   1   0
1   1   0   1   1   1
1   0   1   0   1   0
1   1   0   1   1   0
</code>```

I would like to merge all the columns from this dataframe. I can accomplish this by specifying all the columns like this.

```<code>rbind(mydata$X1,ydata$X2,ydata$X3,ydata$X4,ydata$X5,ydata$X6)
</code>```

What is the best way to merge all the columns in a data frame without having to specify each column? I tried

```<code>bind(mydata)
</code>```

but it doesn't work.

答:
tidyr's gather does exactly that:

```<code>tidyr::gather(mydata)
</code>```

If you then want to get rid of the "key" column, dplyr::select(mydata, value) will do the trick (or simply, mydata$value if you don't want to keep it as a dataframe)

Body:
I have the following data frame

> mydata
X1  X2  X3  X4  X5  X6
1   1   1   1   1   1
1   0   0   0   0   1
1   1   0   0   0   0
1   0   1   1   1   0
1   1   0   1   1   1
1   0   1   0   1   0
1   1   0   1   1   0

I would like to merge all the columns from this dataframe. I can accomplish this by specifying all the columns like this.

rbind(mydata$X1,ydata$X2,ydata$X3,ydata$X4,ydata$X5,ydata$X6)

What is the best way to merge all the columns in a data frame without having to specify each column? I tried

bind(mydata)

but it doesn't work.

Body:
tidyr's gather does exactly that:

tidyr::gather(mydata)

If you then want to get rid of the "key" column, dplyr::select(mydata, value) will do the trick (or simply, mydata$value if you don't want to keep it as a dataframe)


问:
Using izip over second dimension of numpy array
I have the following:

```<code>for i in xrange(n):
    label = labels[i]
    frame = data[:, i]
    dostuff()
</code>```

Where data is a 2-D numpy array.  I'd like to rewrite it using izip.

```<code>for label, frame in izip(labels, ???):
    dostuff()
</code>```

What do I replace ??? with to get this to work?

答:
You could use:

```<code>  ??? = numpy.transpose(data)
</code>```

EDIT: remove second version. Since transpose doesn't copy the array like I assumed there is no reason to anything as crazy as I was doing.

Body:
I have the following:

for i in xrange(n):
    label = labels[i]
    frame = data[:, i]
    dostuff()

Where data is a 2-D numpy array.  I'd like to rewrite it using izip.

for label, frame in izip(labels, ???):
    dostuff()

What do I replace ??? with to get this to work?

Body:
You could use:

  ??? = numpy.transpose(data)

EDIT: remove second version. Since transpose doesn't copy the array like I assumed there is no reason to anything as crazy as I was doing.

ContentLicense: CC BY-SA 2.5


问:
Docusign API limits and violations
I want to make the below three calls one by one immediately  from my app. All are get calls to Docusign and all are  different urls but same envelope id .

Is it possible to do make below three calls immediately from my app or we need to make call after 15 minutes.. for go live?

Calls:

```<code>baseUrl + "/envelopes/" + envelopeId+ "/documents/combined";

baseUrl+"/envelopes/"+envelopeId+"/recipients/1/tabs";

baseUrl + "/envelopes/" + envelopeId + "/documents/certificate";
</code>```

答:
You are referring to API Rule #2 which states

You may not exceed 1 GET request per unique envelope endpoint per 15 minutes.

The 3 requests should be fine, even though it's the same envelope it is still unique (different) endpoints.  Even when you get the documents for instance, the first request is made against the .../combined endpoint whereas the third is made against .../certificate endpoint.

The good thing here is that you can now validate your transactions in self-service fashion using the automated API Go Live process.  Note that this is only accessible through developer sandbox accounts, not live production accounts.

Title: Docusign API limits and violations

Body:
I want to make the below three calls one by one immediately  from my app. All are get calls to Docusign and all are  different urls but same envelope id .

Is it possible to do make below three calls immediately from my app or we need to make call after 15 minutes.. for go live?

Calls:

baseUrl + "/envelopes/" + envelopeId+ "/documents/combined";

baseUrl+"/envelopes/"+envelopeId+"/recipients/1/tabs";

baseUrl + "/envelopes/" + envelopeId + "/documents/certificate";


问:
Unable to print string concatenated with list
I have a script that scraps a list of IPs from a router. The final output should look like this:

```<code>if net ~ [
12.5.161.0/24,
12.9.242.0/24,
12.11.215.0/24,
12.17.239.0/24,
.... etc etc
216.248.237.0/24,
216.248.238.0/24,
216.248.239.0/24,
216.251.224.0/19,
216.253.79.0/24
] then {
    accept;
} else {
    reject;
}
</code>```

I've gotten to the point where i can get the list of IPs in the right format, ie

```<code>12.5.161.0/24,
12.9.242.0/24,
12.11.215.0/24,
12.17.239.0/24,
.... etc etc
216.248.237.0/24,
216.248.238.0/24,
216.248.239.0/24,
216.251.224.0/19,
216.253.79.0/24
</code>```

The prb I run into is stringing together the str at the beginning with all of my IPs as one batch in the middle and the 4 line str at the end.

So far I have:

```<code>routes = get_bird_routes(args.s)
prefixes = parse_routes(routes, args.p)
dropped = drop_prefixes(prefixes, args.d)
for p in dropped:

  lines = [   "if net ~ [",      str(p),    "] then {",  "    accept;",   "} else {",   "    reject;",       "}\n"  ]
  print "\n".join(lines)
</code>```

but this gives me

```<code>if net ~ [
199.89.247.0/24
] then {
    accept;
} else {
    reject;
}

if net ~ [
192.149.228.0/24
] then {
    accept;
} else {
    reject;
}

if net ~ [
206.180.165.0/24
] then {
    accept;
} else {
    reject;
}
</code>```

instead of all my IPs together and the str at the beg and at the end only. I tried to see what type(p) was (before i set it to str(p)) and it came back unicode. Looking at the document, I didnt get a clear understanding of what I was doing wrong. Newish to python still, any help appreciated!!

答:
You should be joining dropped, not looping over it.

```<code>dropped_lines = ",\n".join(dropped)
lines = [ "if net ~ [", dropped_lines, "] then {",  "    accept;",   "} else {",   "    reject;",       "}\n"  ]
print "\n".join(lines)
</code>```

Body:
I have a script that scraps a list of IPs from a router. The final output should look like this:

if net ~ [
12.5.161.0/24,
12.9.242.0/24,
12.11.215.0/24,
12.17.239.0/24,
.... etc etc
216.248.237.0/24,
216.248.238.0/24,
216.248.239.0/24,
216.251.224.0/19,
216.253.79.0/24
] then {
    accept;
} else {
    reject;
}

I've gotten to the point where i can get the list of IPs in the right format, ie

12.5.161.0/24,
12.9.242.0/24,
12.11.215.0/24,
12.17.239.0/24,
.... etc etc
216.248.237.0/24,
216.248.238.0/24,
216.248.239.0/24,
216.251.224.0/19,
216.253.79.0/24

The prb I run into is stringing together the str at the beginning with all of my IPs as one batch in the middle and the 4 line str at the end.

So far I have:

routes = get_bird_routes(args.s)
prefixes = parse_routes(routes, args.p)
dropped = drop_prefixes(prefixes, args.d)
for p in dropped:

  lines = [   "if net ~ [",      str(p),    "] then {",  "    accept;",   "} else {",   "    reject;",       "}\n"  ]
  print "\n".join(lines)

but this gives me

if net ~ [
199.89.247.0/24
] then {
    accept;
} else {
    reject;
}

if net ~ [
192.149.228.0/24
] then {
    accept;
} else {
    reject;
}

if net ~ [
206.180.165.0/24
] then {
    accept;
} else {
    reject;
}

instead of all my IPs together and the str at the beg and at the end only. I tried to see what type(p) was (before i set it to str(p)) and it came back unicode. Looking at the document, I didnt get a clear understanding of what I was doing wrong. Newish to python still, any help appreciated!!

Body:
You should be joining dropped, not looping over it.

dropped_lines = ",\n".join(dropped)
lines = [ "if net ~ [", dropped_lines, "] then {",  "    accept;",   "} else {",   "    reject;",       "}\n"  ]
print "\n".join(lines)


问:
Should I use arial-label or a label element that is visually hidden
I am creating a search form that has two elements an input field and a button. The input field does not have an label associated with it.

To make the field more accessible I can add Search and visually hide it so it will e.g. be accessible for screenreaders.

I could also add aria-label="search" to the input field and leave the input field without an label.

I have tested with "Voice Over" on a Mac and I get the same result/output. My question is are these approaches equivalent? Or is one approach better than the other one?

Here is a pen.

答:
I believe that aria-label="search" is the correct approach, as it produces cleaner markup (i.e. no unnecessary label tag) and no need for CSS to set visibility of the label - like in this example.

I believe visually hiding a label using CSS is a somewhat 'hacky' way to approach the problem, whereas ARIA is the standard for accessible markup, so it should be the obvious choice for situations like this.

On the other hand, it would be worth ensuring all browsers you intend to support can use ARIA correctly, and if not, it may be worth using the label approach to ensure compatibility across all browsers. Although, I think the support these days is pretty good, so that should not be a common scenario.


问:
Update jsonb column
I'm trying to update user facts inside of a column in a Postrgres db in the form designated here.

jsonb currently in data column and waiting to be updated:

data = { "type1" : ["value1", "value2"], "type2" : ["value3"], "type3" : ["value4"] }

jsonb that is sent up to db:

new_jsonb = { "type1" : ["value7", "value8"], "type3" : ["value6"]}

how the jsonb should look after it updates:

updated_jsonb = { "type1: ["value7", "value8"], "type2": ["value3"], "type3": ["value6"] }

The basic rules when comparing the value originally in the dataset, with the one we want to update it with are:

if the new_jsonb that's being passed up contains keys that aren't in the current data jsonb, then those keys get added with their values.

if the new_jsonb that's being passed up contains keys that are in the current data jsonb, then those keys all just replace the old keys.

This post did a useful job outlining the general use for the jsonb_set function, but I'm having trouble going through and making the comparison within the arrays. Specifically specifying the path parameter.

So basically where I'm stuck is not knowing what path to specify for this to happen. What I have is UPDATE table_name SET data = jsonb_set(data {don't know what path should be}, new) WHERE customer_id = $customerId. The new_jsonb that's passed up, won't always pass up the key-value pairs in the same order.

答:
Use the concatenate operator:

```<code>UPDATE table_name
SET data = data || $newData
WHERE customer_id = $customerId;
</code>```

Example:

```<code>SELECT
    '{ "type1": ["value1", "value2"], "type2": ["value3"], "type3": ["value4"] }'::jsonb ||
    '{ "type1": ["value7", "value8"], "type3": ["value6"]}'::jsonb as result

                                  result
---------------------------------------------------------------------------
 {"type1": ["value7", "value8"], "type2": ["value3"], "type3": ["value6"]}
(1 row)
</code>```

Title: Update jsonb column

Body:
Use the concatenate operator:

UPDATE table_name
SET data = data || $newData
WHERE customer_id = $customerId;

Example:

SELECT
    '{ "type1": ["value1", "value2"], "type2": ["value3"], "type3": ["value4"] }'::jsonb ||
    '{ "type1": ["value7", "value8"], "type3": ["value6"]}'::jsonb as result

                                  result
---------------------------------------------------------------------------
 {"type1": ["value7", "value8"], "type2": ["value3"], "type3": ["value6"]}
(1 row)


问:
force download using readfile not working
this is an index.php

```<code><form action="verify.php" method="post" target="_blank">
        <input name="filename" type="hidden" value="media.mp4"><p></p>
        <input name="filesize" type="hidden" value="10 MB">
        <div align="center">
            <input alt="Download" src="download.png" type="image" width="225">
        </div>
</form>
</code>```

this is an verify.php

```<code><meta http-equiv="refresh" content="5; url=download.php?file=<?php echo $file; ?>">
</code>```

this is an download.php

```<code><?php
$file = $_GET['file'];
header('Content-type: video/mp4');
header('Content-Disposition: attachment; filename="uploads/' . $file . '"');
?>
</code>```

And the media files are stored in uploads directory this code need to force mp4 to download unfortunately it is not downloading from correct path.

this is the output in console: /download.php?file=media.mp4".

in order to make it work it should be /uploads/media.mp4 ... please help! tell me what im doing wrong?

答:
if you want the same "name" for the "output" of the file, copy this code

```<code><?php
$file = $_GET['file'];
header('Content-type: video/mp4');
header('Content-Disposition: attachment; filename="' . $file . '"');
readfile("uploads/" . $file);
?>
</code>```

else :

```<code><?php
$file = $_GET['file'];
header('Content-type: video/mp4');
header('Content-Disposition: attachment; filename="[the name the file]"');
readfile("uploads/" . $file);
?>
</code>```

Body:
this is an index.php

<form action="verify.php" method="post" target="_blank">
        <input name="filename" type="hidden" value="media.mp4">

        <input name="filesize" type="hidden" value="10 MB">

            <input alt="Download" src="download.png" type="image" width="225">

</form>

this is an verify.php

<meta http-equiv="refresh" content="5; url=download.php?file=<?php echo $file; ?>">

this is an download.php

<?php
$file = $_GET['file'];
header('Content-type: video/mp4');
header('Content-Disposition: attachment; filename="uploads/' . $file . '"');
?>

And the media files are stored in uploads directory this code need to force mp4 to download unfortunately it is not downloading from correct path.

this is the output in console: /download.php?file=media.mp4".

in order to make it work it should be /uploads/media.mp4 ... please help! tell me what im doing wrong?

Body:
if you want the same "name" for the "output" of the file, copy this code

<?php
$file = $_GET['file'];
header('Content-type: video/mp4');
header('Content-Disposition: attachment; filename="' . $file . '"');
readfile("uploads/" . $file);
?>

else :

<?php
$file = $_GET['file'];
header('Content-type: video/mp4');
header('Content-Disposition: attachment; filename="[the name the file]"');
readfile("uploads/" . $file);
?>


问:
How did I break the auto resize feature of the Automatic Image Montage jQuery plugin?
Sorry in advance if this is confusing. I've incorporated the Automatic Image Montage jQuery plugin for a page I'm working on and seem to have broken the feature that automatically resizes images upon a window resize event. Everything else about the plugin is working as it should. What am I doing wrong?

I'm pretty inexperienced with jQuery and Javascript, but have only modified a few of the max/min image size options in the plugin's js file. The internal reference in the js file that seems related to this problem is 'smartresize.' If you don't want to download the demo from the link above I've included a de-minified version of the js file below. First, my relevant css and html are as follows:

CSS

```<code>/*=========================automontage==============================*/
.am-container {
margin-top:75px;
}
.am-wrapper{
float:left;
position:relative;
overflow:hidden;
}
.am-wrapper img{
position:absolute;
outline:none;
}
/*=========================automontage==============================*/
</code>```

HTML

```<code><div class="am-container" id="am-container">
   <a href="#="asdf"><img src="img/265_s.jpg"></img></a>
   <a href="#" title="asdf"><img src="img/mont1_cloud_s.jpg"></img></a>
   <a href="#" title="asdf"><img src="img/san_diego_street.jpg"></img></a>
   <a href="#" title="asdf"><img src="img/IMG_8576_s.jpg"></img></a>
   <a href="#" title="asdf"><img src="img/IMG_9827_1_s.jpg"></img></a>
   <a href="#" title="asdf"><img src="img/IMG_0999_s.jpg"></img></a>
   <a href="#" title="asdf"><img src="img/Lake_pano_11.jpg"></img></a>
   <a href="#" title="asdf"><img src="img/IMG_8967_s.jpg"></img></a>
   <a href="#" title="asdf"><img src="img/IMG_1346_s.jpg"></img></a>
   <a href="#" title="asdf"><img src="img/IMG_2450.jpg"></img></a>
</div>
</code>```

In HTML script

```<code><script type="text/javascript" src="js/jquery.montage.min.js"></script>
<script type="text/javascript">
                /*automontage*/
                    $(function() {

                        var $container  = $('#am-container'),
                            $imgs       = $container.find('img').hide(),
                            totalImgs   = $imgs.length,
                            cnt         = 0;

                        $imgs.each(function(i) {
                            var $img    = $(this);
                            $('<img/>').load(function() {
                                ++cnt;
                                if( cnt === totalImgs ) {
                                    $imgs.show();
                                    $container.montage({
                                        fillLastRow             : true,
                                        alternateHeight         : true,
                                        alternateHeightRange    : {
                                            min : 150,
                                            max : 350
                                        }
                                    });

                                    }
                            }).attr('src',$img.attr('src'));
                        });

                    });

            </script>
</code>```

jQuery Plugin File Code (de-minified)

/**
 * jQuery Montage plugin
 * http://www.codrops.com/
 *
 * Copyright 2011, Pedro Botelho
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Date: Tue Aug 30 2011
 */
(function( window, $, undefined ) {

 /*
 * Array.max, Array.min
 * @John Resig
 * http://ejohn.org/blog/fast-javascript-maxmin/
 */

 // function to get the Max value in array
    Array.max      = function( array ){
        return Math.max.apply( Math, array );
    };

    // function to get the Min value in array
    Array.min      = function( array ){
       return Math.min.apply( Math, array );
    };

 /*
 * smartresize: debounced resize event for jQuery
 *
 * latest version and complete README available on Github:
 * https://github.com/louisremi/jquery.smartresize.js
 *
 * Copyright 2011 @louis_remi
 * Licensed under the MIT license.
 */

 var $event = $.event, resizeTimeout;

 $event.special.smartresize  = {
  setup: function() {
   $(this).bind( "resize", $event.special.smartresize.handler );
  },
  teardown: function() {
   $(this).unbind( "resize", $event.special.smartresize.handler );
  },
  handler: function( event, execAsap ) {
   // Save the context
   var context = this,
    args  = arguments;

   // set correct event type
   event.type = "smartresize";

   if ( resizeTimeout ) { clearTimeout( resizeTimeout ); }
   resizeTimeout = setTimeout(function() {
    jQuery.event.handle.apply( context, args );
   }, execAsap === "execAsap"? 0 : 50 );
  }
 };

 $.fn.smartresize    = function( fn ) {
  return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] );
 };

 // ======================= imagesLoaded Plugin ===============================
 // https://github.com/desandro/imagesloaded

 // $('#my-container').imagesLoaded(myFunction)
 // execute a callback when all images have loaded.
 // needed because .load() doesn't work on cached images

 // callback function gets image collection as argument
 //  `this` is the container

 // original: mit license. paul irish. 2010.
 // contributors: Oren Solomianik, David DeSandro, Yiannis Chatzikonstantinou

 $.fn.imagesLoaded    = function( callback ) {
  var $images = this.find('img'),
   len  = $images.length,
   _this  = this,
   blank  = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

  function triggerCallback() {
   callback.call( _this, $images );
  }

  function imgLoaded() {
   if ( --len <= 0 && this.src !== blank ){
    setTimeout( triggerCallback );
    $images.unbind( 'load error', imgLoaded );
   }
  }

  if ( !len ) {
      triggerCallback();
  }

  $images.bind( 'load error',  imgLoaded ).each( function() {
      // cached images don't fire load sometimes, so we reset src.
      if (this.complete || this.complete === undefined){
    var src = this.src;
    // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
    // data uri bypasses webkit log warning (thx doug jones)
    this.src = blank;
    this.src = src;
      }
  });

  return this;
 };

 $.Montage      = function( options, element ) {
  this.element  = $( element ).show();
  this.cache  = {};
  this.heights = new Array();
  this._create( options );
 };

 $.Montage.defaults    = {
  liquid     : true, // if you use percentages (or no width at all) for the container's width, then set this to true
          // this will set the body's overflow-y to scroll ( fix for the scrollbar's width problem )
  margin     : 1, // space between images.
  minw     : 70, // the minimum width that a picture should have.
  minh     : 20, // the minimum height that a picture should have.
  maxh     : 250, // the maximum height that a picture should have.
  alternateHeight   : false,// alternate the height value for every row. If true this has priority over defaults.fixedHeight.
  alternateHeightRange : {  // the height will be a random value between min and max.
   min : 100,
   max : 300
  },
  fixedHeight    : null, // if the value is set this has priority over defaults.minsize. All images will have this height.
  minsize     : false,// minw,minh are irrelevant. Chosen height is the minimum one available.
  fillLastRow    : false // if true, there will be no gaps in the container. The last image will fill any white space available
    };

 $.Montage.prototype   = {
  _getImageWidth  : function( $img, h ) {
   var i_w = $img.width(), i_h = $img.height(), r_i = i_h / i_w;
   return Math.ceil( h / r_i );
  },
  _getImageHeight  : function( $img, w ) {
   var i_w = $img.width(), i_h = $img.height(), r_i = i_h / i_w;
   return Math.ceil( r_i * w );
  },
  _chooseHeight  : function() {
   // get the minimum height
   if( this.options.minsize ) {
    return Array.min( this.heights );
   }
   // otherwise get the most repeated heights. From those choose the minimum.
   var result  = {},
    max  = 0,
    res, val, min;

   for( var i = 0, total = this.heights.length; i < total; ++i ) {
    var val = this.heights[i], inc = ( result[val] || 0 ) + 1;

    if( val < this.options.minh || val > this.options.maxh ) continue;

    result[val] = inc;

    if( inc >= max ) {
     max = inc; res = val;
    }
   }
   for (var i in result) {
    if (result[i] === max) {
     val = i;
     min = min || val;

     if(min < this.options.minh)
      min = null;
     else if (min > val)
      min = val;
     if(min === null)
      min = val;
    }
   }
   if(min === undefined) min = this.heights[0];

   res = min;

   return res;
  },
  _stretchImage  : function( $img ) {
   var prevWrapper_w = $img.parent().width(),
    new_w    = prevWrapper_w + this.cache.space_w_left,
    crop    = {
     x  : new_w,
     y : this.theHeight
    };

   var new_image_w  = $img.width() + this.cache.space_w_left,
    new_image_h  = this._getImageHeight( $img, new_image_w );

   this._cropImage( $img, new_image_w, new_image_h, crop );
   this.cache.space_w_left = this.cache.container_w;
   // if this.options.alternateHeight is true, change row / change height
   if( this.options.alternateHeight)
    this.theHeight   = Math.floor( Math.random()*( this.options.alternateHeightRange.max - this.options.alternateHeightRange.min + 1 ) + this.options.alternateHeightRange.min );
  },
  _updatePrevImage : function( $nextimg ) {
   var $prevImage   = this.element.find('img.montage:last');

   this._stretchImage( $prevImage );

   this._insertImage( $nextimg );
  },
  _insertImage  : function( $img ) {
   // width the image should have with height = this.theHeight.
   var new_w = this._getImageWidth( $img, this.theHeight );

   // use the minimum height available if this.options.minsize = true.
   if( this.options.minsize && !this.options.alternateHeight ) {
    if( this.cache.space_w_left <= this.options.margin * 2 ) {
     this._updatePrevImage( $img );
    }
    else {
     if( new_w > this.cache.space_w_left ) {
      var crop = { x : this.cache.space_w_left, y : this.theHeight };
      this._cropImage( $img, new_w, this.theHeight, crop );
      this.cache.space_w_left = this.cache.container_w;
      $img.addClass('montage');
     }
     else {
      var crop = { x  : new_w, y : this.theHeight };
      this._cropImage( $img, new_w, this.theHeight, crop );
      this.cache.space_w_left -= new_w;
      $img.addClass('montage');
     }
    }
   }
   else {
    // the width is lower than the minimum width allowed.
    if( new_w < this.options.minw ) {
     // the minimum width allowed is higher than the space left to fill the row.
     // need to resize the previous (last) item in that row.
     if( this.options.minw > this.cache.space_w_left ) {
      this._updatePrevImage( $img );
     }
     else {
      var new_w = this.options.minw, new_h = this._getImageHeight( $img, new_w ), crop = { x : new_w, y : this.theHeight };
      this._cropImage( $img, new_w, new_h, crop );
      this.cache.space_w_left -= new_w;
      $img.addClass('montage');
     }
    }
    else {
     // the new width is higher than the space left but the space left is lower than the minimum width allowed.
     // need to resize the previous (last) item in that row.
     if( new_w > this.cache.space_w_left && this.cache.space_w_left < this.options.minw ) {
      this._updatePrevImage( $img );
     }
     else if( new_w > this.cache.space_w_left && this.cache.space_w_left >= this.options.minw ) {
      var crop = {x : this.cache.space_w_left, y : this.theHeight};
      this._cropImage( $img, new_w, this.theHeight, crop );
      this.cache.space_w_left = this.cache.container_w;
      // if this.options.alternateHeight is true, change row / change height
      if( this.options.alternateHeight)
       this.theHeight = Math.floor( Math.random()*( this.options.alternateHeightRange.max - this.options.alternateHeightRange.min + 1 ) + this.options.alternateHeightRange.min );
      $img.addClass('montage');
     }
     else {
      var crop = { x : new_w, y : this.theHeight};
      this._cropImage( $img, new_w, this.theHeight, crop );
      this.cache.space_w_left -= new_w;
      $img.addClass('montage');
     }
    }
   }
  },
  _cropImage   : function( $img, w, h, cropParam ) {
   // margin value
   var dec = this.options.margin * 2;

   var $wrapper = $img.parent('a');

   // resize the image
   this._resizeImage( $img, w, h );

   // adjust the top / left values to slice the image without loosing the its ratio
   $img.css({
    left : - ( w - cropParam.x ) / 2 + 'px',
    top  : - ( h - cropParam.y ) / 2 + 'px'
   });

   // wrap the image in a  element
   $wrapper.addClass('am-wrapper').css({
    width : cropParam.x - dec + 'px',
    height : cropParam.y + 'px',
    margin  : this.options.margin
   });
  },
  _resizeImage  : function( $img, w, h ) {
   $img.css( { width : w + 'px', height : h + 'px' } );
  },
  _reload    : function() {
   // container's width
   var new_el_w = this.element.width();

   // if different, something changed...
   if( new_el_w !== this.cache.container_w ) {
    this.element.hide();
    this.cache.container_w  = new_el_w;
    this.cache.space_w_left  = new_el_w;
    var instance     = this;
    instance.$imgs.removeClass('montage').each( function(i) {
     instance._insertImage( $(this) );
    });
    if( instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w ) {
     instance._stretchImage( instance.$imgs.eq( instance.totalImages - 1 ) );
    }
    instance.element.show();
   }
  },
  _create    : function( options ) {
   this.options  = $.extend( true, {}, $.Montage.defaults, options );

   var instance   = this,
    el_w    = instance.element.width();

   instance.$imgs  = instance.element.find('img');
   instance.totalImages= instance.$imgs.length;

   // solve the scrollbar width problem.
   if( instance.options.liquid )
    $('html').css( 'overflow-y', 'scroll' );

   // save the heights of all images.
   if( !instance.options.fixedHeight ) {
    instance.$imgs.each( function(i) {
     var $img = $(this), img_w = $img.width();

     // if images have width > instance.options.minw then "resize" image.
     if( img_w < instance.options.minw && !instance.options.minsize ) {
      var new_h = instance._getImageHeight( $img, instance.options.minw );
      instance.heights.push( new_h );
     }
     else {
      instance.heights.push( $img.height() );
     }
    });
   }

   // calculate which height to use for each image.
   instance.theHeight   = ( !instance.options.fixedHeight && !instance.options.alternateHeight ) ? instance._chooseHeight() : instance.options.fixedHeight;

   if( instance.options.alternateHeight )
    instance.theHeight  = Math.floor( Math.random() * ( instance.options.alternateHeightRange.max - instance.options.alternateHeightRange.min + 1 ) + instance.options.alternateHeightRange.min );

   // save some values.
   instance.cache.container_w = el_w;
   // space left to fill the row.
   instance.cache.space_w_left = el_w;

   // wrap the images with the right sizes.
   instance.$imgs.each( function(i) {
    instance._insertImage( $(this) );
   });

   if( instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w ) {
    instance._stretchImage( instance.$imgs.eq( instance.totalImages - 1 ) );
   }

   // window resize event : reload the container.
   $(window).bind('smartresize.montage', function() {
    instance._reload();
   });
  },
  add     : function( $images, callback ) {
   // adds one or more images to the container
   var $images_stripped = $images.find('img');
   this.$imgs   = this.$imgs.add( $images_stripped );
   this.totalImages= this.$imgs.length;
   this._add( $images, callback );
  },
  _add    : function( $images, callback ) {
   var instance = this;
   $images.find('img').each( function(i) {
    instance._insertImage( $(this) );
   });

   if( instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w )
    instance._stretchImage( instance.$imgs.eq( instance.totalImages - 1 ) );

   if ( callback ) callback.call( $images );
  },
  destroy    : function( callback ) {
   this._destroy( callback );
  },
  _destroy    : function( callback ) {
   this.$imgs.removeClass('montage').css({
    position : '',
    width  : '',
    height  : '',
    left  : '',
    top   : ''
   }).unwrap();

   if( this.options.liquid )
    $('html').css( 'overflow', '' );

   this.element.unbind('.montage').removeData('montage');

   $(window).unbind('.montage');

   if ( callback ) callback.call();
  },
  option    : function( key, value ) {
   // set options AFTER initialization:
   if ( $.isPlainObject( key ) ){
    this.options = $.extend( true, this.options, key );
   }
  }
 };

 // taken from jquery.masonry
 //   https://github.com/desandro/masonry
 // helper function for logging errors
 // $.error breaks jQuery chaining
 var logError     = function( message ) {
  if ( this.console ) {
   console.error( message );
  }
 };

 // Structure taken from jquery.masonry
 //   https://github.com/desandro/masonry
 // =======================  Plugin bridge  ===============================
 // leverages data method to either create or return $.Montage constructor
 // A bit from jQuery UI
 //   https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js
 // A bit from jcarousel
 //   https://github.com/jsor/jcarousel/blob/master/lib/jquery.jcarousel.js

 $.fn.montage     = function( options ) {
  if ( typeof options === 'string' ) {
   // call method
   var args = Array.prototype.slice.call( arguments, 1 );

   this.each(function() {
    var instance = $.data( this, 'montage' );
    if ( !instance ) {
     logError( "cannot call methods on montage prior to initialization; " +
     "attempted to call method '" + options + "'" );
     return;
    }
    if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
     logError( "no such method '" + options + "' for montage instance" );
     return;
    }
    // apply method
    instance[ options ].apply( instance, args );
   });
  }
  else {
   this.each(function() {
    var instance = $.data( this, 'montage' );
    if ( instance ) {
     // apply options & reload
     instance.option( options || {} );
     instance._reload();
    }
    else {
     // initialize new instance
     $.data( this, 'montage', new $.Montage( options, this ) );
    }
   });
  }

  return this;
 };

})( window, jQuery );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script></code>```

答: Figured it out. Turns out that my jQuery plugin version, which I'd changed from 1.6.2 to 1.12.4, broke the plugin. I played with the plugin version until I found one that worked for the other plugins I'm using, too (magnific popup lightbox, automatic montage). Now all is working! 1.7.0 was what worked for all.</p>

Body:
Sorry in advance if this is confusing. I've incorporated the Automatic Image Montage jQuery plugin for a page I'm working on and seem to have broken the feature that automatically resizes images upon a window resize event. Everything else about the plugin is working as it should. What am I doing wrong?

I'm pretty inexperienced with jQuery and Javascript, but have only modified a few of the max/min image size options in the plugin's js file. The internal reference in the js file that seems related to this problem is 'smartresize.' If you don't want to download the demo from the link above I've included a de-minified version of the js file below. First, my relevant css and html are as follows:

CSS

/*=========================automontage==============================*/
.am-container {
margin-top:75px;
}
.am-wrapper{
float:left;
position:relative;
overflow:hidden;
}
.am-wrapper img{
position:absolute;
outline:none;
}
/*=========================automontage==============================*/

HTML

In HTML script

jQuery Plugin File Code (de-minified)

/**
 * jQuery Montage plugin
 * http://www.codrops.com/
 *
 * Copyright 2011, Pedro Botelho
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Date: Tue Aug 30 2011
 */
(function( window, $, undefined ) {

 /*
 * Array.max, Array.min
 * @John Resig
 * http://ejohn.org/blog/fast-javascript-maxmin/
 */

 // function to get the Max value in array
    Array.max      = function( array ){
        return Math.max.apply( Math, array );
    };

    // function to get the Min value in array
    Array.min      = function( array ){
       return Math.min.apply( Math, array );
    };

 /*
 * smartresize: debounced resize event for jQuery
 *
 * latest version and complete README available on Github:
 * https://github.com/louisremi/jquery.smartresize.js
 *
 * Copyright 2011 @louis_remi
 * Licensed under the MIT license.
 */

 var $event = $.event, resizeTimeout;

 $event.special.smartresize  = {
  setup: function() {
   $(this).bind( "resize", $event.special.smartresize.handler );
  },
  teardown: function() {
   $(this).unbind( "resize", $event.special.smartresize.handler );
  },
  handler: function( event, execAsap ) {
   // Save the context
   var context = this,
    args  = arguments;

   // set correct event type
   event.type = "smartresize";

   if ( resizeTimeout ) { clearTimeout( resizeTimeout ); }
   resizeTimeout = setTimeout(function() {
    jQuery.event.handle.apply( context, args );
   }, execAsap === "execAsap"? 0 : 50 );
  }
 };

 $.fn.smartresize    = function( fn ) {
  return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] );
 };

 // ======================= imagesLoaded Plugin ===============================
 // https://github.com/desandro/imagesloaded

 // $('#my-container').imagesLoaded(myFunction)
 // execute a callback when all images have loaded.
 // needed because .load() doesn't work on cached images

 // callback function gets image collection as argument
 //  `this` is the container

 // original: mit license. paul irish. 2010.
 // contributors: Oren Solomianik, David DeSandro, Yiannis Chatzikonstantinou

 $.fn.imagesLoaded    = function( callback ) {
  var $images = this.find('img'),
   len  = $images.length,
   _this  = this,
   blank  = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

  function triggerCallback() {
   callback.call( _this, $images );
  }

  function imgLoaded() {
   if ( --len <= 0 && this.src !== blank ){
    setTimeout( triggerCallback );
    $images.unbind( 'load error', imgLoaded );
   }
  }

  if ( !len ) {
      triggerCallback();
  }

  $images.bind( 'load error',  imgLoaded ).each( function() {
      // cached images don't fire load sometimes, so we reset src.
      if (this.complete || this.complete === undefined){
    var src = this.src;
    // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
    // data uri bypasses webkit log warning (thx doug jones)
    this.src = blank;
    this.src = src;
      }
  });

  return this;
 };

 $.Montage      = function( options, element ) {
  this.element  = $( element ).show();
  this.cache  = {};
  this.heights = new Array();
  this._create( options );
 };

 $.Montage.defaults    = {
  liquid     : true, // if you use percentages (or no width at all) for the container's width, then set this to true
          // this will set the body's overflow-y to scroll ( fix for the scrollbar's width problem )
  margin     : 1, // space between images.
  minw     : 70, // the minimum width that a picture should have.
  minh     : 20, // the minimum height that a picture should have.
  maxh     : 250, // the maximum height that a picture should have.
  alternateHeight   : false,// alternate the height value for every row. If true this has priority over defaults.fixedHeight.
  alternateHeightRange : {  // the height will be a random value between min and max.
   min : 100,
   max : 300
  },
  fixedHeight    : null, // if the value is set this has priority over defaults.minsize. All images will have this height.
  minsize     : false,// minw,minh are irrelevant. Chosen height is the minimum one available.
  fillLastRow    : false // if true, there will be no gaps in the container. The last image will fill any white space available
    };

 $.Montage.prototype   = {
  _getImageWidth  : function( $img, h ) {
   var i_w = $img.width(), i_h = $img.height(), r_i = i_h / i_w;
   return Math.ceil( h / r_i );
  },
  _getImageHeight  : function( $img, w ) {
   var i_w = $img.width(), i_h = $img.height(), r_i = i_h / i_w;
   return Math.ceil( r_i * w );
  },
  _chooseHeight  : function() {
   // get the minimum height
   if( this.options.minsize ) {
    return Array.min( this.heights );
   }
   // otherwise get the most repeated heights. From those choose the minimum.
   var result  = {},
    max  = 0,
    res, val, min;

   for( var i = 0, total = this.heights.length; i < total; ++i ) {
    var val = this.heights[i], inc = ( result[val] || 0 ) + 1;

    if( val < this.options.minh || val > this.options.maxh ) continue;

    result[val] = inc;

    if( inc >= max ) {
     max = inc; res = val;
    }
   }
   for (var i in result) {
    if (result[i] === max) {
     val = i;
     min = min || val;

     if(min < this.options.minh)
      min = null;
     else if (min > val)
      min = val;
     if(min === null)
      min = val;
    }
   }
   if(min === undefined) min = this.heights[0];

   res = min;

   return res;
  },
  _stretchImage  : function( $img ) {
   var prevWrapper_w = $img.parent().width(),
    new_w    = prevWrapper_w + this.cache.space_w_left,
    crop    = {
     x  : new_w,
     y : this.theHeight
    };

   var new_image_w  = $img.width() + this.cache.space_w_left,
    new_image_h  = this._getImageHeight( $img, new_image_w );

   this._cropImage( $img, new_image_w, new_image_h, crop );
   this.cache.space_w_left = this.cache.container_w;
   // if this.options.alternateHeight is true, change row / change height
   if( this.options.alternateHeight)
    this.theHeight   = Math.floor( Math.random()*( this.options.alternateHeightRange.max - this.options.alternateHeightRange.min + 1 ) + this.options.alternateHeightRange.min );
  },
  _updatePrevImage : function( $nextimg ) {
   var $prevImage   = this.element.find('img.montage:last');

   this._stretchImage( $prevImage );

   this._insertImage( $nextimg );
  },
  _insertImage  : function( $img ) {
   // width the image should have with height = this.theHeight.
   var new_w = this._getImageWidth( $img, this.theHeight );

   // use the minimum height available if this.options.minsize = true.
   if( this.options.minsize && !this.options.alternateHeight ) {
    if( this.cache.space_w_left <= this.options.margin * 2 ) {
     this._updatePrevImage( $img );
    }
    else {
     if( new_w > this.cache.space_w_left ) {
      var crop = { x : this.cache.space_w_left, y : this.theHeight };
      this._cropImage( $img, new_w, this.theHeight, crop );
      this.cache.space_w_left = this.cache.container_w;
      $img.addClass('montage');
     }
     else {
      var crop = { x  : new_w, y : this.theHeight };
      this._cropImage( $img, new_w, this.theHeight, crop );
      this.cache.space_w_left -= new_w;
      $img.addClass('montage');
     }
    }
   }
   else {
    // the width is lower than the minimum width allowed.
    if( new_w < this.options.minw ) {
     // the minimum width allowed is higher than the space left to fill the row.
     // need to resize the previous (last) item in that row.
     if( this.options.minw > this.cache.space_w_left ) {
      this._updatePrevImage( $img );
     }
     else {
      var new_w = this.options.minw, new_h = this._getImageHeight( $img, new_w ), crop = { x : new_w, y : this.theHeight };
      this._cropImage( $img, new_w, new_h, crop );
      this.cache.space_w_left -= new_w;
      $img.addClass('montage');
     }
    }
    else {
     // the new width is higher than the space left but the space left is lower than the minimum width allowed.
     // need to resize the previous (last) item in that row.
     if( new_w > this.cache.space_w_left && this.cache.space_w_left < this.options.minw ) {
      this._updatePrevImage( $img );
     }
     else if( new_w > this.cache.space_w_left && this.cache.space_w_left >= this.options.minw ) {
      var crop = {x : this.cache.space_w_left, y : this.theHeight};
      this._cropImage( $img, new_w, this.theHeight, crop );
      this.cache.space_w_left = this.cache.container_w;
      // if this.options.alternateHeight is true, change row / change height
      if( this.options.alternateHeight)
       this.theHeight = Math.floor( Math.random()*( this.options.alternateHeightRange.max - this.options.alternateHeightRange.min + 1 ) + this.options.alternateHeightRange.min );
      $img.addClass('montage');
     }
     else {
      var crop = { x : new_w, y : this.theHeight};
      this._cropImage( $img, new_w, this.theHeight, crop );
      this.cache.space_w_left -= new_w;
      $img.addClass('montage');
     }
    }
   }
  },
  _cropImage   : function( $img, w, h, cropParam ) {
   // margin value
   var dec = this.options.margin * 2;

   var $wrapper = $img.parent('a');

   // resize the image
   this._resizeImage( $img, w, h );

   // adjust the top / left values to slice the image without loosing the its ratio
   $img.css({
    left : - ( w - cropParam.x ) / 2 + 'px',
    top  : - ( h - cropParam.y ) / 2 + 'px'
   });

   // wrap the image in a  element
   $wrapper.addClass('am-wrapper').css({
    width : cropParam.x - dec + 'px',
    height : cropParam.y + 'px',
    margin  : this.options.margin
   });
  },
  _resizeImage  : function( $img, w, h ) {
   $img.css( { width : w + 'px', height : h + 'px' } );
  },
  _reload    : function() {
   // container's width
   var new_el_w = this.element.width();

   // if different, something changed...
   if( new_el_w !== this.cache.container_w ) {
    this.element.hide();
    this.cache.container_w  = new_el_w;
    this.cache.space_w_left  = new_el_w;
    var instance     = this;
    instance.$imgs.removeClass('montage').each( function(i) {
     instance._insertImage( $(this) );
    });
    if( instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w ) {
     instance._stretchImage( instance.$imgs.eq( instance.totalImages - 1 ) );
    }
    instance.element.show();
   }
  },
  _create    : function( options ) {
   this.options  = $.extend( true, {}, $.Montage.defaults, options );

   var instance   = this,
    el_w    = instance.element.width();

   instance.$imgs  = instance.element.find('img');
   instance.totalImages= instance.$imgs.length;

   // solve the scrollbar width problem.
   if( instance.options.liquid )
    $('html').css( 'overflow-y', 'scroll' );

   // save the heights of all images.
   if( !instance.options.fixedHeight ) {
    instance.$imgs.each( function(i) {
     var $img = $(this), img_w = $img.width();

     // if images have width > instance.options.minw then "resize" image.
     if( img_w < instance.options.minw && !instance.options.minsize ) {
      var new_h = instance._getImageHeight( $img, instance.options.minw );
      instance.heights.push( new_h );
     }
     else {
      instance.heights.push( $img.height() );
     }
    });
   }

   // calculate which height to use for each image.
   instance.theHeight   = ( !instance.options.fixedHeight && !instance.options.alternateHeight ) ? instance._chooseHeight() : instance.options.fixedHeight;

   if( instance.options.alternateHeight )
    instance.theHeight  = Math.floor( Math.random() * ( instance.options.alternateHeightRange.max - instance.options.alternateHeightRange.min + 1 ) + instance.options.alternateHeightRange.min );

   // save some values.
   instance.cache.container_w = el_w;
   // space left to fill the row.
   instance.cache.space_w_left = el_w;

   // wrap the images with the right sizes.
   instance.$imgs.each( function(i) {
    instance._insertImage( $(this) );
   });

   if( instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w ) {
    instance._stretchImage( instance.$imgs.eq( instance.totalImages - 1 ) );
   }

   // window resize event : reload the container.
   $(window).bind('smartresize.montage', function() {
    instance._reload();
   });
  },
  add     : function( $images, callback ) {
   // adds one or more images to the container
   var $images_stripped = $images.find('img');
   this.$imgs   = this.$imgs.add( $images_stripped );
   this.totalImages= this.$imgs.length;
   this._add( $images, callback );
  },
  _add    : function( $images, callback ) {
   var instance = this;
   $images.find('img').each( function(i) {
    instance._insertImage( $(this) );
   });

   if( instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w )
    instance._stretchImage( instance.$imgs.eq( instance.totalImages - 1 ) );

   if ( callback ) callback.call( $images );
  },
  destroy    : function( callback ) {
   this._destroy( callback );
  },
  _destroy    : function( callback ) {
   this.$imgs.removeClass('montage').css({
    position : '',
    width  : '',
    height  : '',
    left  : '',
    top   : ''
   }).unwrap();

   if( this.options.liquid )
    $('html').css( 'overflow', '' );

   this.element.unbind('.montage').removeData('montage');

   $(window).unbind('.montage');

   if ( callback ) callback.call();
  },
  option    : function( key, value ) {
   // set options AFTER initialization:
   if ( $.isPlainObject( key ) ){
    this.options = $.extend( true, this.options, key );
   }
  }
 };

 // taken from jquery.masonry
 //   https://github.com/desandro/masonry
 // helper function for logging errors
 // $.error breaks jQuery chaining
 var logError     = function( message ) {
  if ( this.console ) {
   console.error( message );
  }
 };

 // Structure taken from jquery.masonry
 //   https://github.com/desandro/masonry
 // =======================  Plugin bridge  ===============================
 // leverages data method to either create or return $.Montage constructor
 // A bit from jQuery UI
 //   https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js
 // A bit from jcarousel
 //   https://github.com/jsor/jcarousel/blob/master/lib/jquery.jcarousel.js

 $.fn.montage     = function( options ) {
  if ( typeof options === 'string' ) {
   // call method
   var args = Array.prototype.slice.call( arguments, 1 );

   this.each(function() {
    var instance = $.data( this, 'montage' );
    if ( !instance ) {
     logError( "cannot call methods on montage prior to initialization; " +
     "attempted to call method '" + options + "'" );
     return;
    }
    if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
     logError( "no such method '" + options + "' for montage instance" );
     return;
    }
    // apply method
    instance[ options ].apply( instance, args );
   });
  }
  else {
   this.each(function() {
    var instance = $.data( this, 'montage' );
    if ( instance ) {
     // apply options & reload
     instance.option( options || {} );
     instance._reload();
    }
    else {
     // initialize new instance
     $.data( this, 'montage', new $.Montage( options, this ) );
    }
   });
  }

  return this;
 };

})( window, jQuery );


问:
Set a key if it does not exist, otherwise return its value
I don't seem to find a command in Redis to achieve the following:

Set a key if it does not exist, otherwise return its value

Is there any way of achieving this in one transaction?

答:
One transaction? sure. One command? Don't think so.

Within a transaction, use SETNX to set a key if it does not exist, then get the value.

```<code>MULTI
SETNX keyName value
GET keyName
EXEC
</code>```

Body:
One transaction? sure. One command? Don't think so.

Within a transaction, use SETNX to set a key if it does not exist, then get the value.

MULTI
SETNX keyName value
GET keyName
EXEC


问:
Is it legal for a C compiler to optimize out local static variables?
For a function like

```<code>int test(void) {
  static int x = 0;
  x++;
  return 0;
}
</code>```

is a C compiler allowed to optimize out x?

For reference, neither GCC 6.3.0 or Clang 3.9 optimize out incrementing x with -O3.

答:
The compiler would be within its rights to optimise away this function completely, given it has no observable side effects (from the point of view of the C standard).

As to why your compilers aren't doing so, I can't explain that!  (Though of course, they're under no obligation to do so.)

Body:
For a function like

int test(void) {
  static int x = 0;
  x++;
  return 0;
}

is a C compiler allowed to optimize out x?

For reference, neither GCC 6.3.0 or Clang 3.9 optimize out incrementing x with -O3.


问:
Starting Spotify App From Intent
I'm attempting to initialize a Spotify search exactly like what is mentioned here: Starting a Song from Spotify Intent

However, the example code always gives me an Activity Not Found Exception.

Does anyone have any ideas on how to overcome this?

Thanks!

Here is my current code for reference:

```<code>try {
                    final Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.setAction(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH);
                    intent.setComponent(new ComponentName("com.spotify.mobile.android.ui", "com.spotify.mobile.android.ui.Launcher"));
                    intent.putExtra(SearchManager.QUERY, trackName );
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                } catch ( ActivityNotFoundException e ) {
                    final Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.setAction(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH);
                    intent.setComponent(new ComponentName("com.spotify.mobile.android.ui", "com.spotify.mobile.android.ui.activity.MainActivity"));
                    intent.putExtra(SearchManager.QUERY, trackName );
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
</code>```

答:
```<code>intent.setComponent(new ComponentName("com.spotify.music", "com.spotify.music.MainActivity"));
</code>```

This fixed it, the package I was using was for an older Spotify app.

Title: Starting Spotify App From Intent

Body:
I'm attempting to initialize a Spotify search exactly like what is mentioned here: Starting a Song from Spotify Intent

However, the example code always gives me an Activity Not Found Exception.

Does anyone have any ideas on how to overcome this?

Thanks!

Here is my current code for reference:

try {
                    final Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.setAction(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH);
                    intent.setComponent(new ComponentName("com.spotify.mobile.android.ui", "com.spotify.mobile.android.ui.Launcher"));
                    intent.putExtra(SearchManager.QUERY, trackName );
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                } catch ( ActivityNotFoundException e ) {
                    final Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.setAction(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH);
                    intent.setComponent(new ComponentName("com.spotify.mobile.android.ui", "com.spotify.mobile.android.ui.activity.MainActivity"));
                    intent.putExtra(SearchManager.QUERY, trackName );
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }

Body:
intent.setComponent(new ComponentName("com.spotify.music", "com.spotify.music.MainActivity"));

This fixed it, the package I was using was for an older Spotify app.


问:
JSON formatter in C#?
Looking for a function that will take a string of Json as input and format it with line breaks and indentations. Validation would be a bonus, but isn't necessary, and I don't need to parse it into an object or anything.

Anyone know of such a library?

Sample input:

```<code>{"status":"OK", "results":[ {"types":[ "locality", "political"], "formatted_address":"New York, NY, USA", "address_components":[ {"long_name":"New York", "short_name":"New York", "types":[ "locality", "political"]}, {"long_name":"New York", "short_name":"New York", "types":[ "administrative_area_level_2", "political"]}, {"long_name":"New York", "short_name":"NY", "types":[ "administrative_area_level_1", "political"]}, {"long_name":"United States", "short_name":"US", "types":[ "country", "political"]}], "geometry":{"location":{"lat":40.7143528, "lng":-74.0059731}, "location_type":"APPROXIMATE", "viewport":{"southwest":{"lat":40.5788964, "lng":-74.2620919}, "northeast":{"lat":40.8495342, "lng":-73.7498543}}, "bounds":{"southwest":{"lat":40.4773990, "lng":-74.2590900}, "northeast":{"lat":40.9175770, "lng":-73.7002720}}}}]}
</code>```

答:
All credits are to Frank Tzanabetis. However this is the shortest direct example, that also survives in case of empty string or broken original JSON string:</p>
```<code>using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

    ...
    try
    {
        return JToken.Parse(jsonString).ToString(Formatting.Indented);
    }
    catch
    {
        return jsonString;
</code>```

Title: JSON formatter in C#?

Body:
Looking for a function that will take a string of Json as input and format it with line breaks and indentations. Validation would be a bonus, but isn't necessary, and I don't need to parse it into an object or anything.

Anyone know of such a library?

Sample input:

{"status":"OK", "results":[ {"types":[ "locality", "political"], "formatted_address":"New York, NY, USA", "address_components":[ {"long_name":"New York", "short_name":"New York", "types":[ "locality", "political"]}, {"long_name":"New York", "short_name":"New York", "types":[ "administrative_area_level_2", "political"]}, {"long_name":"New York", "short_name":"NY", "types":[ "administrative_area_level_1", "political"]}, {"long_name":"United States", "short_name":"US", "types":[ "country", "political"]}], "geometry":{"location":{"lat":40.7143528, "lng":-74.0059731}, "location_type":"APPROXIMATE", "viewport":{"southwest":{"lat":40.5788964, "lng":-74.2620919}, "northeast":{"lat":40.8495342, "lng":-73.7498543}}, "bounds":{"southwest":{"lat":40.4773990, "lng":-74.2590900}, "northeast":{"lat":40.9175770, "lng":-73.7002720}}}}]}

Body:
All credits are to Frank Tzanabetis. However this is the shortest direct example, that also survives in case of empty string or broken original JSON string:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

    ...
    try
    {
        return JToken.Parse(jsonString).ToString(Formatting.Indented);
    }
    catch
    {
        return jsonString;

ContentLicense: CC BY-SA 4.0


问:
Using GCC extensions with code compiled with clang?
I have a two questions regarding GCC extensions

If I compile a library using GCC attributes/extensions, will they work even if I link them to a program compiled with for example clang?

Should function attributes/extensions be declared in the function declaration or prototype?

答:
If the attributes/extensions only affect code generation and not interfaces, it should work.

Depends on the attribute.
E.g., attributes such as pure, const, or nonnull, are no good unless every translation unit that uses the functions can see them—you should put them on the prototypes in your header (and use the underscored form, e.g., __attribute__((__pure__))).

On the other hand, attributes affecting code generation or visibility should be on the implementation, or else if your library user decided to make an override of a function provided by your library, including your header would effectively force those attributes on their override.

In any case, if you put an attribute on the declaration, it affects the definition too (assuming the definition sees the declaration—thanks to Jonathan Leffler for the clarification), but definitions can take on additional attributes not present in the declaration(s).


问:
Cannot determine whether Google play store is installed or not on Android device
This was a simple matter of checking the installed packages on the device... before I've upgraded my OS to 2.3.5, I could locate the Market/Play store, using this code:

```<code>private static final String GooglePlayStorePackageName = "com.google.market";

void someMethod() {
    packageManager = getApplication().getPackageManager();
    List<PackageInfo> packages = packageManager.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
    for (PackageInfo packageInfo : packages) {
        if (packageInfo.packageName.equals(GooglePlayStorePackageName)) {
            googlePlayStoreInstalled = true;
            break;
        }
    }
}
</code>```

For some reason after the update, I simply cannot find the to package name to indicate the application is installed, although it is on the device, and I can access the market.

Has the package name changed? or perhaps I'm looking at this the wrong way?

Thanks,

Adam.

UPDATE:

That was a stupid way to check if a package is installed... a better way is:

```<code>protected final boolean isPackageInstalled(String packageName) {
    try {
        application.getPackageManager().getPackageInfo(packageName, 0);
    } catch (NameNotFoundException e) {
        return false;
    }
    return true;
}
</code>```

答:
In most case we want to find out whether Google Play Store is installed or not to launch it with some app page preloaded.

Why cant we do this:

```<code>final String appPackageName = getPackageName(); // get your app package name
try {
    Uri uri = Uri.parse("market://details?id=" + appPackageName);
    startActivity(new Intent(Intent.ACTION_VIEW, uri));
} catch (android.content.ActivityNotFoundException anfe) {
    // Google Play Store is not available.
}
</code>```

Body:
This was a simple matter of checking the installed packages on the device... before I've upgraded my OS to 2.3.5, I could locate the Market/Play store, using this code:

private static final String GooglePlayStorePackageName = "com.google.market";

void someMethod() {
    packageManager = getApplication().getPackageManager();
    List<PackageInfo> packages = packageManager.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
    for (PackageInfo packageInfo : packages) {
        if (packageInfo.packageName.equals(GooglePlayStorePackageName)) {
            googlePlayStoreInstalled = true;
            break;
        }
    }
}

For some reason after the update, I simply cannot find the to package name to indicate the application is installed, although it is on the device, and I can access the market.

Has the package name changed? or perhaps I'm looking at this the wrong way?

Thanks,

Adam.

UPDATE:

That was a stupid way to check if a package is installed... a better way is:

protected final boolean isPackageInstalled(String packageName) {
    try {
        application.getPackageManager().getPackageInfo(packageName, 0);
    } catch (NameNotFoundException e) {
        return false;
    }
    return true;
}

Body:
In most case we want to find out whether Google Play Store is installed or not to launch it with some app page preloaded.

Why cant we do this:

final String appPackageName = getPackageName(); // get your app package name
try {
    Uri uri = Uri.parse("market://details?id=" + appPackageName);
    startActivity(new Intent(Intent.ACTION_VIEW, uri));
} catch (android.content.ActivityNotFoundException anfe) {
    // Google Play Store is not available.
}


问:
jQuery AjaxUpload, have to click button twice?
I am using the AjaxUpload plugin with jQuery, and everything is working fine for the most part, but I have to click my button twice to get it to execute. I'm guessing this is a scope issue... or(?) still learning...

Here is my code:

```<code>    $(".upload-button").live("click", function(event) {
       event.preventDefault();
       var currentId = $(this).closest("div").attr("id").replace("slide-", "");
       new AjaxUpload($(this), {
         action: "./php/upload.php",
         name: 'userfile',
         autoSubmit: true,
         onSubmit: function(file , ext) {
       },
       onComplete: function(file, response) {
         // enable upload button
         // this.enable();
         $("#slide-" + currentId).find(".movie-image").attr("src", baseImgPath + file);
         $("#mImg" + currentId).val(file);
      }
   });
</code>```

Any ideas are appreciated. :)

答:
Try this :

```<code>$(".upload-button").live("hover", function(event) {

   var currentId = $(this).closest("div").attr("id").replace("slide-", "");
   new AjaxUpload($(this), {
     action: "./php/upload.php",
     name: 'userfile',
     autoSubmit: true,
     onSubmit: function(file , ext) {
         //onsubmit code here..
     },
     onComplete: function(file, response) {
         // oncomplete code here
     }
   });
   $(this).trigger('click');
</code>```

});

Mine working but I'm not really sure how it works. The 'hover' (instead of 'click') will create a new AjaxUpload (this will prevent from click it twice)

Body:
I am using the AjaxUpload plugin with jQuery, and everything is working fine for the most part, but I have to click my button twice to get it to execute. I'm guessing this is a scope issue... or(?) still learning...

Here is my code:

    $(".upload-button").live("click", function(event) {
       event.preventDefault();
       var currentId = $(this).closest("div").attr("id").replace("slide-", "");
       new AjaxUpload($(this), {
         action: "./php/upload.php",
         name: 'userfile',
         autoSubmit: true,
         onSubmit: function(file , ext) {
       },
       onComplete: function(file, response) {
         // enable upload button
         // this.enable();
         $("#slide-" + currentId).find(".movie-image").attr("src", baseImgPath + file);
         $("#mImg" + currentId).val(file);
      }
   });

Any ideas are appreciated. :)

Body:
Try this :

$(".upload-button").live("hover", function(event) {

   var currentId = $(this).closest("div").attr("id").replace("slide-", "");
   new AjaxUpload($(this), {
     action: "./php/upload.php",
     name: 'userfile',
     autoSubmit: true,
     onSubmit: function(file , ext) {
         //onsubmit code here..
     },
     onComplete: function(file, response) {
         // oncomplete code here
     }
   });
   $(this).trigger('click');

});

Mine working but I'm not really sure how it works. The 'hover' (instead of 'click') will create a new AjaxUpload (this will prevent from click it twice)


问:
How to select first 2 items from an array?
I want to select the first 2 item from an array and also select just first name of each person from an object, not the full name.

These are my codes:

index.html

```<code><body>
<button onclick="loadajax();">laod ajax</button>
<div id = "update"></div>

<script src="jquery.js"></script>
<script src="script.js"></script>
</body>
</code>```

script.js

```<code>function loadajax(){
    var request;
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    request.open('GET', 'data.json');
    request.onreadystatechange = function() {
        if ((request.readyState===4) && (request.status===200)) {
            var items = JSON.parse(request.responseText);
            var output = '<ul>';
            for (var key in items) {
                output += '<li>his name is:' + items[key].name + ' with the id of:'+ items[key].id +'</li>';
            }
            output += '</ul>';
            document.getElementById('update').innerHTML = output;
        }
    }
    request.send();
}
</code>```

data.json

```<code>[
  {
    "name":"Barot Bellingham",
    "id":"1"
  },
  {
    "name":"alex benjan",
    "id":"2"
  },
  {
    "name":"jony lekson",
    "id":"3"
  }
]
</code>```

this is the results:

his name is:Barot Bellingham with the id of:1

his name is:alex benjan with the id of:2

his name is:jony lekson with the id of:3

but what I want is this:

his name is:Barot  with the id of:1

his name is:alex  with the id of:2

do you have an idea how to do this?

答:
You can use slice:

```<code>for (let key in items.slice(0, 2)) { // ...etc
</code>```

But in general it is advised not to use for...in on arrays. Use for..of (or forEach), in combination with destructuring and a template literal:

```<code>for (let {name, id} of items.slice(0, 2)) {
    output += `<li>his name is: ${name} with the id of: ${id}</li>`
}
</code>```

Or, even better, use map in combination with join:

```<code>let output = '<ul>' + items.slice(0, 2).map(({name, id}) =>
    `<li>his name is: ${name} with the id of: ${id}</li>`
).join('') + '</ul>';
</code>```

The first name can be extracted by taking the first word with split (this is not 100% correct, as some first names can consist of two or more words):

```<code>let output = '<ul>' + items.slice(0, 2).map(item =>
    `<li>his name is: ${item.name.split(' ')[0]} with the id of: ${id}</li>`
).join('') + '</ul>';
</code>```

NB: This has little to do with Ajax or JSON, just with looping and array methods.

Body:
I want to select the first 2 item from an array and also select just first name of each person from an object, not the full name.

These are my codes:

index.html

<button onclick="loadajax();">laod ajax</button>

script.js

function loadajax(){
    var request;
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    request.open('GET', 'data.json');
    request.onreadystatechange = function() {
        if ((request.readyState===4) && (request.status===200)) {
            var items = JSON.parse(request.responseText);
            var output = '
';
            for (var key in items) {
                output += '
his name is:' + items[key].name + ' with the id of:'+ items[key].id +'
';
            }
            output += '
';
            document.getElementById('update').innerHTML = output;
        }
    }
    request.send();
}

data.json

[
  {
    "name":"Barot Bellingham",
    "id":"1"
  },
  {
    "name":"alex benjan",
    "id":"2"
  },
  {
    "name":"jony lekson",
    "id":"3"
  }
]

this is the results:

his name is:Barot Bellingham with the id of:1

his name is:alex benjan with the id of:2

his name is:jony lekson with the id of:3

but what I want is this:

his name is:Barot  with the id of:1

his name is:alex  with the id of:2

do you have an idea how to do this?

Body:
You can use slice:

for (let key in items.slice(0, 2)) { // ...etc

But in general it is advised not to use for...in on arrays. Use for..of (or forEach), in combination with destructuring and a template literal:

for (let {name, id} of items.slice(0, 2)) {
    output += `<li>his name is: ${name} with the id of: ${id}</li>`
}

Or, even better, use map in combination with join:

let output = '<ul>' + items.slice(0, 2).map(({name, id}) =>
    `<li>his name is: ${name} with the id of: ${id}</li>`
).join('') + '</ul>';

The first name can be extracted by taking the first word with split (this is not 100% correct, as some first names can consist of two or more words):

let output = '<ul>' + items.slice(0, 2).map(item =>
    `<li>his name is: ${item.name.split(' ')[0]} with the id of: ${id}</li>`
).join('') + '</ul>';

NB: This has little to do with Ajax or JSON, just with looping and array methods.


问:
Approach to utilize existing css files in sass framework
I've started working on a project that has bunch of css files eg. 15-20 css files which is not the right approach i wanted to use Sass framework but these bunch of css files have confused me. I want to make sure i dont break anything before start writing sass for these css file so wanted to know What's the best strategy i should adapt to integrate sass framework in a project considering we already have bunch of css files??</p>

答:
Valid css is valid sass so to start you could just change the extension to .scss and compile them along with your new sass files. So if you were generating just one main.css for example:

```<code>//main.scss
@import "existing-file-one";
@import "existing-file-two";
@import "existing-file-three";
@import "new-file";
</code>```

This would then add all your existing styles.

Body:
Valid css is valid sass so to start you could just change the extension to .scss and compile them along with your new sass files. So if you were generating just one main.css for example:

//main.scss
@import "existing-file-one";
@import "existing-file-two";
@import "existing-file-three";
@import "new-file";

This would then add all your existing styles.


问:
How to make the text hidden in hover
I am creating a menu that each item has a text and in hover an email replaces.  So I do not know how to remove the text in hover.

here is my code so far:

#home {
    font: 30px 'LeagueGothicRegular', Arial, sans-serif;
    color: #f9f8cc;
}

#home:hover {
    background:url(style/images/icon/home.png) #FFF;
    background-size: 83px 56px;
}
```

答:
You can also use opacity and this is how:

Html

```<code> <div id="home">
   <div class="yourDivClassThatContainsText">
      Text Text TExt
   </div>
</div>
</code>```

CSS

```<code>.yourDivClassThatContainsText{opacity:1;}
.yourDivClassThatContainsText:hover{opacity:0;}
</code>```

To make it really nice add this .transition class to the same div where  yourDivClassThatContainsText is here is the transition class:

```<code>.transition{-webkit-transition: all 0.6s ease; -moz-transition: all 0.6s ease; -ms-transition: all 0.6s ease; -o-transition: all 0.6s ease; transition: all 0.6s ease;}
</code>```

Thanks hope I helped

Title: How to make the text hidden in hover

Body:
You can also use opacity and this is how:

Html

 <div id="home">
   <div class="yourDivClassThatContainsText">
      Text Text TExt
   </div>
</div>

CSS

.yourDivClassThatContainsText{opacity:1;}
.yourDivClassThatContainsText:hover{opacity:0;}

To make it really nice add this .transition class to the same div where  yourDivClassThatContainsText is here is the transition class:

.transition{-webkit-transition: all 0.6s ease; -moz-transition: all 0.6s ease; -ms-transition: all 0.6s ease; -o-transition: all 0.6s ease; transition: all 0.6s ease;}

Thanks hope I helped


答:
Try converting your list to a string with str() and join(). Then merge the one string into your logic statement(string) with .format().

Viz:

```<code>dropped_as_strs = map(str, dropped)        # "a", "b", "c"
dropped_str = ',\n'.join(dropped_as_strs)  # "a,\nb,\nc"

logic = "if net ~ [\n{}\n] then {{\n    accept;\n}} ..."

result = logic.format(dropped_str)
</code>```

(Note the need to double '{' and '}' in str.format() calls.)

Title: Unable to print string concatenated with list

Body:
I have a script that scraps a list of IPs from a router. The final output should look like this:

if net ~ [
12.5.161.0/24,
12.9.242.0/24,
12.11.215.0/24,
12.17.239.0/24,
.... etc etc
216.248.237.0/24,
216.248.238.0/24,
216.248.239.0/24,
216.251.224.0/19,
216.253.79.0/24
] then {
    accept;
} else {
    reject;
}

I've gotten to the point where i can get the list of IPs in the right format, ie

12.5.161.0/24,
12.9.242.0/24,
12.11.215.0/24,
12.17.239.0/24,
.... etc etc
216.248.237.0/24,
216.248.238.0/24,
216.248.239.0/24,
216.251.224.0/19,
216.253.79.0/24

The prb I run into is stringing together the str at the beginning with all of my IPs as one batch in the middle and the 4 line str at the end.

So far I have:

routes = get_bird_routes(args.s)
prefixes = parse_routes(routes, args.p)
dropped = drop_prefixes(prefixes, args.d)
for p in dropped:

  lines = [   "if net ~ [",      str(p),    "] then {",  "    accept;",   "} else {",   "    reject;",       "}\n"  ]
  print "\n".join(lines)

but this gives me

if net ~ [
199.89.247.0/24
] then {
    accept;
} else {
    reject;
}

if net ~ [
192.149.228.0/24
] then {
    accept;
} else {
    reject;
}

if net ~ [
206.180.165.0/24
] then {
    accept;
} else {
    reject;
}

instead of all my IPs together and the str at the beg and at the end only. I tried to see what type(p) was (before i set it to str(p)) and it came back unicode. Looking at the document, I didnt get a clear understanding of what I was doing wrong. Newish to python still, any help appreciated!!

Body:
Try converting your list to a string with str() and join(). Then merge the one string into your logic statement(string) with .format().

Viz:

dropped_as_strs = map(str, dropped)        # "a", "b", "c"
dropped_str = ',\n'.join(dropped_as_strs)  # "a,\nb,\nc"

logic = "if net ~ [\n{}\n] then {{\n    accept;\n}} ..."

result = logic.format(dropped_str)

(Note the need to double '{' and '}' in str.format() calls.)


问:
Update JFrame with thread? - Java
I have asked this question so many times and have tried so many different things that I don't know where to turn.

Could someone please write a program for me to show me how to do this and make sure it works with well commented code. If not at least get me a good example. All my efforts are at the bottom of this post, but are not currently working.

Thread 1: GUI / visible .jar program

Thread 2: Random Number Generator

How would you get thread 1 to get updated after thread 2 generates a number? This update would be done every two seconds by Thread 2.

Download my source:

```<code>    Thread key1 = new Thread(new randomKeyGen(ranLKey));
    key1.start();
</code>```

Thats what I use to get my random class.

Random Class: http://pastebin.com/rTPnYsVX

Here are other posts that did not get me ANYWHERE!!!:

How to get Label into thread?

How to update JFrame Label within a Thread? - Java

答:
Use a Swing Timer. As long as the Timer has access to the label you can update the text and the Timer executes on the EDT so all you have to do is update the label with your random number.

We are not interested in looking at code on pastebin. Post your code here and keep the code simple. See the link on creating a SSCCE. Your whole demo program should be about 20-30 lines of code. That way its easy to debug and understand.

Title: Update JFrame with thread? - Java

Body:
I have asked this question so many times and have tried so many different things that I don't know where to turn.

Could someone please write a program for me to show me how to do this and make sure it works with well commented code. If not at least get me a good example. All my efforts are at the bottom of this post, but are not currently working.

Thread 1: GUI / visible .jar program

Thread 2: Random Number Generator

How would you get thread 1 to get updated after thread 2 generates a number? This update would be done every two seconds by Thread 2.

Download my source:

    Thread key1 = new Thread(new randomKeyGen(ranLKey));
    key1.start();

Thats what I use to get my random class.

Random Class: http://pastebin.com/rTPnYsVX

Here are other posts that did not get me ANYWHERE!!!:

How to get Label into thread?

How to update JFrame Label within a Thread? - Java