Programs & Examples On #Web services

A "web service" is a software system designed to support interoperable machine-to-machine interaction over the World Wide Web.

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

The problem is that POST method is forbidden for Nginx server's static files requests. Here is the workaround:

# Pass 405 as 200 for requested address:

server {
listen       80;
server_name  localhost;

location / {
    root   html;
    index  index.html index.htm;
}

error_page  404     /404.html;
error_page  403     /403.html;

error_page  405     =200 $uri;
}

If using proxy:

# If Nginx is like proxy for Apache:

error_page 405 =200 @405; 

location @405 { 
    root /htdocs; 
    proxy_pass http://localhost:8080; 
}

If using FastCGI:

location ~\.php(.*) {
fastcgi_pass 127.0.0.1:9000;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include /etc/nginx/fastcgi_params;
}

Browsers usually use GET, so you can use online tools like ApiTester to test your requests.

Source

Tracing XML request/responses with JAX-WS

I had been trying to find some framework library to log the web service soap request and response for a couple days. The code below fixed the issue for me:

System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");

Is it possible to specify proxy credentials in your web.config?

You can specify credentials by adding a new Generic Credential of your proxy server in Windows Credentials Manager:

1 In Web.config

<system.net>    
<defaultProxy enabled="true" useDefaultCredentials="true">      
<proxy usesystemdefault="True" />      
</defaultProxy>    
</system.net>
  1. In Credential Manager >> Add a Generic Credential

Internet or network address: your proxy address
User name: your user name
Password: you pass

This configuration worked for me, without change the code.

Example of SOAP request authenticated with WS-UsernameToken

The core thing is to define prefixes for namespaces and use them to fortify each and every tag - you are mixing 3 namespaces and that just doesn't fly by trying to hack defaults. It's also good to use exactly the prefixes used in the standard doc - just in case that the other side get a little sloppy.

Last but not least, it's much better to use default types for fields whenever you can - so for password you have to list the type, for the Nonce it's already Base64.

Make sure that you check that the generated token is correct before you send it via XML and don't forget that the content of wsse:Password is Base64( SHA-1 (nonce + created + password) ) and date-time in wsu:Created can easily mess you up. So once you fix prefixes and namespaces and verify that yout SHA-1 work fine without XML (just imagine you are validating the request and do the server side of SHA-1 calculation) you can also do a truial wihtout Created and even without Nonce. Oh and Nonce can have different encodings so if you really want to force another encoding you'll have to look further into wsu namespace.

<S11:Envelope xmlns:S11="..." xmlns:wsse="..." xmlns:wsu= "...">
  <S11:Header>
  ...
    <wsse:Security>
      <wsse:UsernameToken>
        <wsse:Username>NNK</wsse:Username>
        <wsse:Password Type="...#PasswordDigest">weYI3nXd8LjMNVksCKFV8t3rgHh3Rw==</wsse:Password>
        <wsse:Nonce>WScqanjCEAC4mQoBE07sAQ==</wsse:Nonce>
        <wsu:Created>2003-07-16T01:24:32</wsu:Created>
      </wsse:UsernameToken>
    </wsse:Security>
  ...
  </S11:Header>
...
</S11:Envelope>

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

Our issue was simply the port number on the endpoint was incorrectly set to 8080. Changed it to 8443 and it worked.

What is the difference between JAX-RS and JAX-WS?

i have been working on Apachi Axis1.1 and Axis2.0 and JAX-WS but i would suggest you must JAX-WS because it allow you make wsdl in any format , i was making operation as GetInquiry() in Apache Axis2 it did not allow me to Start Operation name in Upper Case , so i find it not good , so i would suggest you must use JAX-WS

Bypass invalid SSL certificate errors when calling web services in .Net

Alternatively you can register a call back delegate which ignores the certification error:

...
ServicePointManager.ServerCertificateValidationCallback = MyCertHandler;
...

static bool MyCertHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors error)
{
// Ignore errors
return true;
}

How do I set the timeout for a JAX-WS webservice client?

I know this is old and answered elsewhere but hopefully this closes this down. I'm not sure why you would want to download the WSDL dynamically but the system properties:

sun.net.client.defaultConnectTimeout (default: -1 (forever))
sun.net.client.defaultReadTimeout (default: -1 (forever))

should apply to all reads and connects using HttpURLConnection which JAX-WS uses. This should solve your problem if you are getting the WSDL from a remote location - but a file on your local disk is probably better!

Next, if you want to set timeouts for specific services, once you've created your proxy you need to cast it to a BindingProvider (which you know already), get the request context and set your properties. The online JAX-WS documentation is wrong, these are the correct property names (well, they work for me).

MyInterface myInterface = new MyInterfaceService().getMyInterfaceSOAP();
Map<String, Object> requestContext = ((BindingProvider)myInterface).getRequestContext();
requestContext.put(BindingProviderProperties.REQUEST_TIMEOUT, 3000); // Timeout in millis
requestContext.put(BindingProviderProperties.CONNECT_TIMEOUT, 1000); // Timeout in millis
myInterface.callMyRemoteMethodWith(myParameter);

Of course, this is a horrible way to do things, I would create a nice factory for producing these binding providers that can be injected with the timeouts you want.

Best way to create a simple python web service

Raw CGI is kind of a pain, Django is kind of heavyweight. There are a number of simpler, lighter frameworks about, e.g. CherryPy. It's worth looking around a bit.

How to pass a JSON array as a parameter in URL

You can pass your json Input as a POST request along with authorization header in this way

public static JSONObject getHttpConn(String json){
        JSONObject jsonObject=null;
        try {
            HttpPost httpPost=new HttpPost("http://google.com/");
            org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
            StringEntity stringEntity=new StringEntity("d="+json);

            httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
            String authorization="test:test@123";
            String encodedAuth = "Basic " + Base64.encode(authorization.getBytes());        
            httpPost.addHeader("Authorization", security.get("Authorization"));
            httpPost.setEntity(stringEntity);
            HttpResponse reponse=client.execute(httpPost);
            InputStream inputStream=reponse.getEntity().getContent();
            String jsonResponse=IOUtils.toString(inputStream);
            jsonObject=JSONObject.fromObject(jsonResponse);
            } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        } catch (ClientProtocolException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return jsonObject;


    }

This Method will return a json response.In same way you can use GET method

How to call a REST web service API from JavaScript?

Your Javascript:

function UserAction() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
             alert(this.responseText);
         }
    };
    xhttp.open("POST", "Your Rest URL Here", true);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send("Your JSON Data Here");
}

Your Button action::

<button type="submit" onclick="UserAction()">Search</button>

For more info go through the following link (Updated 2017/01/11)

How to generate service reference with only physical wsdl file

This may be the easiest method

  • Right click on the project and select "Add Service Reference..."
  • In the Address: box, enter the physical path (C:\test\project....) of the downloaded/Modified wsdl.
  • Hit Go

WCF Exception: Could not find a base address that matches scheme http for the endpoint

Your configuration should look similar to that. You may have to change <transport clientCredentialType="None" proxyCredentialType="None" /> depending on your needs for authentication. The config below doesn't require any authentication.

<bindings>
    <basicHttpBinding>
        <binding name="basicHttpBindingConfiguration">
            <security mode="Transport">
                <transport clientCredentialType="None" proxyCredentialType="None" />
            </security>
        </binding>       
    </basicHttpBinding>
</bindings>

<services>
    <service name="XXX">
        <endpoint
            name="AAA"
            address=""
            binding="basicHttpBinding"
            bindingConfiguration="basicHttpBindingConfiguration"
            contract="YourContract" />
    </service>
<services>

That will allow a WCF service with basicHttpBinding to use HTTPS.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

I solve this problem adding the environment variables JAVA_HOME(C:\Program Files\Java\jdkx.x.x_xx) and JRE_HOME.

JAX-WS - Adding SOAP Headers

I'm adding this answer because none of the others worked for me.

I had to add a Header Handler to the Proxy:

import java.util.Set;
import java.util.TreeSet;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class SOAPHeaderHandler implements SOAPHandler<SOAPMessageContext> {

    private final String authenticatedToken;

    public SOAPHeaderHandler(String authenticatedToken) {
        this.authenticatedToken = authenticatedToken;
    }

    public boolean handleMessage(SOAPMessageContext context) {
        Boolean outboundProperty =
                (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outboundProperty.booleanValue()) {
            try {
                SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
                SOAPFactory factory = SOAPFactory.newInstance();
                String prefix = "urn";
                String uri = "urn:xxxx";
                SOAPElement securityElem =
                        factory.createElement("Element", prefix, uri);
                SOAPElement tokenElem =
                        factory.createElement("Element2", prefix, uri);
                tokenElem.addTextNode(authenticatedToken);
                securityElem.addChildElement(tokenElem);
                SOAPHeader header = envelope.addHeader();
                header.addChildElement(securityElem);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // inbound
        }
        return true;
    }

    public Set<QName> getHeaders() {
        return new TreeSet();
    }

    public boolean handleFault(SOAPMessageContext context) {
        return false;
    }

    public void close(MessageContext context) {
        //
    }
}

In the proxy, I just add the Handler:

BindingProvider bp =(BindingProvider)basicHttpBindingAuthentication;
bp.getBinding().getHandlerChain().add(new SOAPHeaderHandler(authenticatedToken));
bp.getBinding().getHandlerChain().add(new SOAPLoggingHandler());

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

Difference between a SOAP message and a WSDL?

In a simple terms if you have a web service of calculator. WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on. Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.

Service Reference Error: Failed to generate code for the service reference

As stated above, there are a couple of different problems possible. What we found is that the .DLL for the WCF library had been added as a reference to the client project. This, in turn, created problems with resolving the objects and thus caused the files to be "emptied" by code generation steps. While unchecking the use "Reuse Types..." can seem like an answer, it creates extra definitions of object types, which are proxies to the real types, in a new name space, which then causes all kinds of "compatibility" issues with the use of those types. Only if you really want to "hide" a type should you check this option.

Hiding the type would be appropriate when you don't want a "DLL" type dependency to "leak" into a project that you are trying to keep segregated from another. If the DLL for the WCF library project creeps into the client project references, then you will have this problem with all kinds of strange side effects since the type definitions are also in the DLL.

SOAP or REST for Web Services?

I'd recommend you go with REST first - if you're using Java look at JAX-RS and the Jersey implementation. REST is much simpler and easy to interop in many languages.

As others have said in this thread, the problem with SOAP is its complexity when the other WS-* specifications come in and there are countless interop issues if you stray into the wrong parts of WSDL, XSDs, SOAP, WS-Addressing etc.

The best way to judge the REST v SOAP debate is look on the internet - pretty much all the big players in the web space, google, amazon, ebay, twitter et al - tend to use and prefer RESTful APIs over the SOAP ones.

The other nice approach to going with REST is that you can reuse lots of code and infratructure between a web application and a REST front end. e.g. rendering HTML versus XML versus JSON of your resources is normally pretty easy with frameworks like JAX-RS and implicit views - plus its easy to work with RESTful resources using a web browser

jQuery Call to WebService returns "No Transport" error

None of the proposed answers completely worked for me. My use case is slightly different (doing an ajax get to an S3 .json file in IE9). Setting jQuery.support.cors = true; got rid of the No Transport error but I was still getting Permission denied errors.

What did work for me was to use the jQuery-ajaxTransport-XDomainRequest to force IE9 to use XDomainRequest. Using this did not require setting jQuery.support.cors = true;

Java String to JSON conversion

Converting the String to JsonNode using ObjectMapper object :

ObjectMapper mapper = new ObjectMapper();

// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)

// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)

// For Json String 
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);

REST API 404: Bad URI, or Missing Resource?

So in essence, it sounds like the answer could depend on how the request is formed.

If the requested resource forms part of the URI as per a request to http://mywebsite/restapi/user/13 and user 13 does not exist, then a 404 is probably appropriate and intuitive because the URI is representative of a non-existent user/entity/document/etc. The same would hold for the more secure technique using a GUID http://mywebsite/api/user/3dd5b770-79ea-11e1-b0c4-0800200c9a66 and the api/restapi argument above.

However, if the requested resource ID was included in the request header [include your own example], or indeed, in the URI as a parameter, eg http://mywebsite/restapi/user/?UID=13 then the URI would still be correct (because the concept of a USER does exits at http://mywebsite/restapi/user/); and therefore the response could reasonable be expected to be a 200 (with an appropriately verbose message) because the specific user known as 13 does not exist but the URI does. This way we are saying the URI is good, but the request for data has no content.

Personally a 200 still doesn't feel right (though I have previously argued it does). A 200 response code (without a verbose response) could cause an issue not to be investigated when an incorrect ID is sent for example.

A better approach would be to send a 204 - No Contentresponse. This is compliant with w3c's description *The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.*1 The confusion, in my opinion is caused by the Wikipedia entry stating 204 No Content - The server successfully processed the request, but is not returning any content. Usually used as a response to a successful delete request. The last sentence is highly debateable. Consider the situation without that sentence and the solution is easy - just send a 204 if the entity does not exist. There is even an argument for returning a 204 instead of a 404, the request has been processed and no content has been returned! Please be aware though, 204's do not allow content in the response body

Sources

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes 1. http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

How to do a SOAP Web Service call from Java class?

Or just use Apache CXF's wsdl2java to generate objects you can use.

It is included in the binary package you can download from their website. You can simply run a command like this:

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl

It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);

There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315

How can I verify a Google authentication API access token?

An arbitrary OAuth access token can't be used for authentication, because the meaning of the token is outside of the OAuth Core spec. It could be intended for a single use or narrow expiration window, or it could provide access which the user doesn't want to give. It's also opaque, and the OAuth consumer which obtained it might never have seen any type of user identifier.

An OAuth service provider and one or more consumers could easily use OAuth to provide a verifiable authentication token, and there are proposals and ideas to do this out there, but an arbitrary service provider speaking only OAuth Core can't provide this without other co-ordination with a consumer. The Google-specific AuthSubTokenInfo REST method, along with the user's identifier, is close, but it isn't suitable, either, since it could invalidate the token, or the token could be expired.

If your Google ID is an OpenId identifier, and your 'public interface' is either a web app or can call up the user's browser, then you should probably use Google's OpenID OP.

OpenID consists of just sending the user to the OP and getting a signed assertion back. The interaction is solely for the benefit of the RP. There is no long-lived token or other user-specific handle which could be used to indicate that a RP has successfully authenticated a user with an OP.

One way to verify a previous authentication against an OpenID identifier is to just perform authentication again, assuming the same user-agent is being used. The OP should be able to return a positive assertion without user interaction (by verifying a cookie or client cert, for example). The OP is free to require another user interaction, and probably will if the authentication request is coming from another domain (my OP gives me the option to re-authenticate this particular RP without interacting in the future). And in Google's case, the UI that the user went through to get the OAuth token might not use the same session identifier, so the user will have to re-authenticate. But in any case, you'll be able to assert the identity.

Best way to call a JSON WebService from a .NET Console

I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:

// Returns JSON string
string GET(string url) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
            return reader.ReadToEnd();
        }
    }
    catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using (Stream responseStream = errorResponse.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText
        }
        throw;
    }
}

I then use JSON.Net to dynamically parse the string. Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/

POST looks like this:

// POST a JSON string
void POST(string url, string jsonContent) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    Byte[] byteArray = encoding.GetBytes(jsonContent);

    request.ContentLength = byteArray.Length;
    request.ContentType = @"application/json";

    using (Stream dataStream = request.GetRequestStream()) {
        dataStream.Write(byteArray, 0, byteArray.Length);
    }
    long length = 0;
    try {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            length = response.ContentLength;
        }
    }
    catch (WebException ex) {
        // Log exception and throw as for GET example above
    }
}

I use code like this in automated tests of our web service.

WSDL vs REST Pros and Cons

To me we should be careful when we use the word web service. We should all the time specify if we are speaking of SOAP web service, REST web service or other kind of web services because we are speaking about different things here and people don't understand anymore if we named all of them web services.

Basically SOAP web services are very well established for years and they follow a strict specification that describe how to communicate with them based on the SOAP specification. Now REST web services are a bit newer and basically looks like simpler because they are not using any communication protocol. Basically what you send and receive when you use a REST web service is plain XML. People like it because they can parse the xml the way they want without having to deal with a more sophisticated communication protocol like SOAP.

To me REST services are almost like if you would create a servlet instead of a SOAP web service. The servlet get data in and return data out. The format of the data are xml based. We can also imagine to use something else than xml if we want. For instance tags could be used instead of xml and that would be not REST anymore but something else (Could be even lighter in term of weight because xml is not light by nature). Would we call that still a web service? Yes we could but that will not follow any current standard and this is the main issue here if we start to call everything web services but we can do it the way we want then we are loosing on the interoperability side of the things. That means that the format of the data that is exchanged with the web service is not standardized anymore. That requires then that server and client agree on the format of the data whereas with SOAP this is all predefined already and server and client can interoperate without to know each other because they follow the same standard.

What people don't like with SOAP is that they have hard time to understand it and they cannot generate the queries manually. Computers can do that very well however so this is where we need to be clear: are web services queries and response supposed to be used directly by the end users or do we agree that web services are underneath API called by computer systems based on some normalized standards?

How can I consume a WSDL (SOAP) web service in Python?

There is a relatively new library which is very promising and albeit still poorly documented, seems very clean and pythonic: python zeep.

See also this answer for an example.

How to send json data in POST request using C#

You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using HttpClient:

using (var client = new HttpClient())
{
    // This would be the like http://www.uber.com
    client.BaseAddress = new Uri("Base Address/URL Address");

    // serialize your json using newtonsoft json serializer then add it to the StringContent
    var content = new StringContent(YourJson, Encoding.UTF8, "application/json") 

    // method address would be like api/callUber:SomePort for example
    var result = await client.PostAsync("Method Address", content);
    string resultContent = await result.Content.ReadAsStringAsync();   
}

How to test web service using command line curl

In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:

$ curl https://api.twitter.com/1/help/configuration.xml  | xmllint --format -
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool

Tested on Ubuntu 11.0.4/11.10.

Another issue is the desired content type. Twitter uses .xml/.json extension, but more idiomatic REST would require Accept header:

$ curl -H "Accept: application/json"

Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--    

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
</head>
<body>

<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
Address:        <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form> 
</p>
</pre>
</body>
</html>

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I get the same issue. In fact, the request didn't reach the jersey annoted method. I solved the problem with add the annotation: @Consumes(MediaType.APPLICATION_FORM_URLENCODED) The annotation @Consumes("/") don't work!

    @Path("/"+PropertiesHabilitation.KEY_EstNouvelleGH)
    @POST
    //@Consumes("*/*")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void  get__EstNouvelleGH( @Context HttpServletResponse response) {
        ...
    }

Request format is unrecognized for URL unexpectedly ending in

Despite 90% of all the information I found (while trying to find a solution to this error) telling me to add the HttpGet and HttpPost to the configuration, that did not work for me... and didn't make sense to me anyway.

My application is running on lots of servers (30+) and I've never had to add this configuration for any of them. Either the version of the application running under .NET 2.0 or .NET 4.0.

The solution for me was to re-register ASP.NET against IIS.

I used the following command line to achieve this...

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

WSDL validator?

you might want to look at the online version of xsv

Setting HttpContext.Current.Session in a unit test

I worte something about this a while ago.

Unit Testing HttpContext.Current.Session in MVC3 .NET

Hope it helps.

[TestInitialize]
public void TestSetup()
{
    // We need to setup the Current HTTP Context as follows:            

    // Step 1: Setup the HTTP Request
    var httpRequest = new HttpRequest("", "http://localhost/", "");

    // Step 2: Setup the HTTP Response
    var httpResponce = new HttpResponse(new StringWriter());

    // Step 3: Setup the Http Context
    var httpContext = new HttpContext(httpRequest, httpResponce);
    var sessionContainer = 
        new HttpSessionStateContainer("id", 
                                       new SessionStateItemCollection(),
                                       new HttpStaticObjectsCollection(), 
                                       10, 
                                       true,
                                       HttpCookieMode.AutoDetect,
                                       SessionStateMode.InProc, 
                                       false);
    httpContext.Items["AspSession"] = 
        typeof(HttpSessionState)
        .GetConstructor(
                            BindingFlags.NonPublic | BindingFlags.Instance,
                            null, 
                            CallingConventions.Standard,
                            new[] { typeof(HttpSessionStateContainer) },
                            null)
        .Invoke(new object[] { sessionContainer });

    // Step 4: Assign the Context
    HttpContext.Current = httpContext;
}

[TestMethod]
public void BasicTest_Push_Item_Into_Session()
{
    // Arrange
    var itemValue = "RandomItemValue";
    var itemKey = "RandomItemKey";

    // Act
    HttpContext.Current.Session.Add(itemKey, itemValue);

    // Assert
    Assert.AreEqual(HttpContext.Current.Session[itemKey], itemValue);
}

How do I upload a file with metadata using a REST web service?

To build on ccleve's answer, if you are using superagent / express / multer, on the front end side build your multipart request doing something like this:

superagent
    .post(url)
    .accept('application/json')
    .field('myVeryRelevantJsonData', JSON.stringify({ peep: 'Peep Peep!!!' }))
    .attach('myFile', file);

cf https://visionmedia.github.io/superagent/#multipart-requests.

On the express side, whatever was passed as field will end up in req.body after doing:

app.use(express.json({ limit: '3MB' }));

Your route would include something like this:

const multerMemStorage = multer.memoryStorage();
const multerUploadToMem = multer({
  storage: multerMemStorage,
  // Also specify fileFilter, limits...
});

router.post('/myUploads',
  multerUploadToMem.single('myFile'),
  async (req, res, next) => {
    // Find back myVeryRelevantJsonData :
    logger.verbose(`Uploaded req.body=${JSON.stringify(req.body)}`);

    // If your file is text:
    const newFileText = req.file.buffer.toString();
    logger.verbose(`Uploaded text=${newFileText}`);
    return next();
  },
  ...

One thing to keep in mind though is this note from the multer doc, concerning disk storage:

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

I guess this means it would be unreliable to, say, compute the target dir/filename based on json metadata passed along the file

how to fix java.lang.IndexOutOfBoundsException

You do not have any elements in the list so can't access the first element.

Could not establish secure channel for SSL/TLS with authority '*'

We had this issue on a new webserver from .aspx pages calling a webservice. We had not given permission to the app pool user to the machine certificate. The issue was fixed after we granted permission to the app pool user.

Call web service in excel

Yes You Can!

I worked on a project that did that (see comment). Unfortunately no code samples from that one, but googling revealed these:

How you can integrate data from several Web services using Excel and VBA

STEP BY STEP: Consuming Web Services through VBA (Excel or Word)

VBA: Consume Soap Web Services

How to use parameters with HttpPost

Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.

So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.

There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.

Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example

class MyInput
{
    String str1;
    String str2;

    public MyInput() { }
      //  getters, setters
 }

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}

Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.

The last option is to construct a POST body that looks like:

str1=value1&str2=value2

then add some additional annotations to your server method:

public void create(@QueryParam("str1") String str1, 
                  @QueryParam("str2") String str2)

@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).

If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.

SoapUI "failed to load url" error when loading WSDL

I had this issue when trying to use a SOCKS proxy. It appears that SoapUI does not support SOCKS proxys. I am using the Boomerang Chrome app instead.

getResourceAsStream() is always returning null

I had a similar problem and I searched for the solution for quite a while: It appears that the string parameter is case sensitive. So if your filename is abc.TXT but you search for abc.txt, eclipse will find it - the executable JAR file won't.

Create web service proxy in Visual Studio from a WSDL file

There's a Microsoft Doc for creating your WCF proxy from the command line .

You can find your local copy of wsdl.exe in a location similar to this: C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools (Learn more here)

In the end your Command should look similar to this:

"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\wsdl.exe"
 /language:CS /n:"My.Namespace" https://www.example.com/service/wsdl

How to secure RESTful web services?

If choosing between OAuth versions, go with OAuth 2.0.

OAuth bearer tokens should only be used with a secure transport.

OAuth bearer tokens are only as secure or insecure as the transport that encrypts the conversation. HTTPS takes care of protecting against replay attacks, so it isn't necessary for the bearer token to also guard against replay.

While it is true that if someone intercepts your bearer token they can impersonate you when calling the API, there are plenty of ways to mitigate that risk. If you give your tokens a long expiration period and expect your clients to store the tokens locally, you have a greater risk of tokens being intercepted and misused than if you give your tokens a short expiration, require clients to acquire new tokens for every session, and advise clients not to persist tokens.

If you need to secure payloads that pass through multiple participants, then you need something more than HTTPS/SSL, since HTTPS/SSL only encrypts one link of the graph. This is not a fault of OAuth.

Bearer tokens are easy to for clients to obtain, easy for clients to use for API calls and are widely used (with HTTPS) to secure public facing APIs from Google, Facebook, and many other services.

How to create a Restful web service with input parameters?

another way to do is get the UriInfo instead of all the QueryParam

Then you will be able to get the queryParam as per needed in your code

@GET
@Path("/query")
public Response getUsers(@Context UriInfo info) {

    String param_1 = info.getQueryParameters().getFirst("param_1");
    String param_2 = info.getQueryParameters().getFirst("param_2");


    return Response ;

}

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Restful API service

There is another approach here which basically helps you to forget about the whole management of the requests. It is based on an async queue method and a callable/callback based response. The main advantage is that by using this method you'll be able to make the whole process (request, get and parse response, sabe to db) completely transparent for you. Once you get the response code the work is already done. After that you just need to make a call to your db and you are done. It helps as well with the problematic of what happens when your activity is not active. What will happen here is that you'll have all your data saved in your local database but the response won't be processed by your activity, that's the ideal way.

I wrote about a general approach here http://ugiagonzalez.com/2012/07/02/theres-life-after-asynctasks-in-android/

I'll be putting specific sample code in upcoming posts. Hope it helps, feel free to contact me for sharing the approach and solving potential doubts or issues.

What are the differences between WCF and ASMX web services?

ASMX Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.

Second, ASMX web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.

We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc

Junit test case for database insert method with DAO and web service

@Test
public void testSearchManagementStaff() throws SQLException
{
    boolean res=true;
    ManagementDaoImp mdi=new ManagementDaoImp();
    boolean b=mdi.searchManagementStaff("[email protected]"," 123456");
    assertEquals(res,b);
}

How can I pass a username/password in the header to a SOAP WCF Service

Adding a custom hard-coded header may work (it also may get rejected at times) but it is totally the wrong way to do it. The purpose of the WSSE is security. Microsoft released the Microsoft Web Services Enhancements 2.0 and subsequently the WSE 3.0 for this exact reason. You need to install this package (http://www.microsoft.com/en-us/download/details.aspx?id=14089).

The documentation is not easy to understand, especially for those who have not worked with SOAP and the WS-Addressing. First of all the "BasicHttpBinding" is Soap 1.1 and it will not give you the same message header as the WSHttpBinding. Install the package and look at the examples. You will need to reference the DLL from WSE 3.0 and you will also need to setup your message correctly. There are a huge number or variations on the WS Addressing header. The one you are looking for is the UsernameToken configuration.

This is a longer explanation and I should write something up for everyone since I cannot find the right answer anywhere. At a minimum you need to start with the WSE 3.0 package.

SOAP vs REST (differences)

SOAP (Simple Object Access Protocol) and REST (Representation State Transfer) both are beautiful in their way. So I am not comparing them. Instead, I am trying to depict the picture, when I preferred to use REST and when SOAP.

What is payload?

When data is sent over the Internet, each unit transmitted includes both header information and the actual data being sent. The header identifies the source and destination of the packet, while the actual data is referred to as the payload. In general, the payload is the data that is carried on behalf of an application and the data received by the destination system.

Now, for example, I have to send a Telegram and we all know that the cost of the telegram will depend on some words.

So tell me among below mentioned these two messages, which one is cheaper to send?

<name>Arin</name>

or

"name": "Arin"

I know your answer will be the second one although both representing the same message second one is cheaper regarding cost.

So I am trying to say that, sending data over the network in JSON format is cheaper than sending it in XML format regarding payload.

Here is the first benefit or advantages of REST over SOAP. SOAP only support XML, but REST supports different format like text, JSON, XML, etc. And we already know, if we use Json then definitely we will be in better place regarding payload.

Now, SOAP supports the only XML, but it also has its advantages.

Really! How?

SOAP relies on XML in three ways Envelope – that defines what is in the message and how to process it.

A set of encoding rules for data types, and finally the layout of the procedure calls and responses gathered.

This envelope is sent via a transport (HTTP/HTTPS), and an RPC (Remote Procedure Call) is executed, and the envelope is returned with information in an XML formatted document.

The important point is that one of the advantages of SOAP is the use of the “generic” transport but REST uses HTTP/HTTPS. SOAP can use almost any transport to send the request but REST cannot. So here we got an advantage of using SOAP.

As I already mentioned in above paragraph “REST uses HTTP/HTTPS”, so go a bit deeper on these words.

When we are talking about REST over HTTP, all security measures applied HTTP are inherited, and this is known as transport level security and it secures messages only while it is inside the wire but once you delivered it on the other side you don’t know how many stages it will have to go through before reaching the real point where the data will be processed. And of course, all those stages could use something different than HTTP.So Rest is not safer completely, right?

But SOAP supports SSL just like REST additionally it also supports WS-Security which adds some enterprise security features. WS-Security offers protection from the creation of the message to it’s consumption. So for transport level security whatever loophole we found that can be prevented using WS-Security.

Apart from that, as REST is limited by it's HTTP protocol so it’s transaction support is neither ACID compliant nor can provide two-phase commit across distributed transnational resources.

But SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources.

I am not drawing any conclusion, but I will prefer SOAP-based web service while security, transaction, etc. are the main concerns.

Here is the "The Java EE 6 Tutorial" where they have said A RESTful design may be appropriate when the following conditions are met. Have a look.

Hope you enjoyed reading my answer.

PowerShell script to check the status of a URL

$request = [System.Net.WebRequest]::Create('http://stackoverflow.com/questions/20259251/powershell-script-to-check-the-status-of-a-url')

$response = $request.GetResponse()

$response.StatusCode

$response.Close()

Web Service vs WCF Service

From What's the Difference between WCF and Web Services?

WCF is a replacement for all earlier web service technologies from Microsoft. It also does a lot more than what is traditionally considered as "web services".

WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.

ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.

Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. Common scenarios for hosting WCF services are IIS,WAS, Self-hosting, Managed Windows Service.

The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in performance as compared to XmlSerializer.

How can I get the named parameters from a URL using Flask?

The URL parameters are available in request.args, which is an ImmutableMultiDict that has a get method, with optional parameters for default value (default) and type (type) - which is a callable that converts the input value to the desired format. (See the documentation of the method for more details.)

from flask import request

@app.route('/my-route')
def my_route():
  page = request.args.get('page', default = 1, type = int)
  filter = request.args.get('filter', default = '*', type = str)

Examples with the code above:

/my-route?page=34               -> page: 34  filter: '*'
/my-route                       -> page:  1  filter: '*'
/my-route?page=10&filter=test   -> page: 10  filter: 'test'
/my-route?page=10&filter=10     -> page: 10  filter: '10'
/my-route?page=*&filter=*       -> page:  1  filter: '*'

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Could me multiple reason for this. But you want might forget to add as @Bean for component which you have did @Autowired.

In my case, i have forgot to decorate with @Bean which causing this issue.

EOFError: end of file reached issue with Net::HTTP

If the URL is using https instead of http, you need to add the following line:

parsed_url = URI.parse(url)
http = Net::HTTP.new(parsed_url.host, parsed_url.port)
http.use_ssl = true

Note the additional http.use_ssl = true.

And the more appropriate code which would handle both http and https will be similar to the following one.

url = URI.parse(domain)
req = Net::HTTP::Post.new(url.request_uri)
req.set_form_data({'name'=>'Sur Max', 'email'=>'[email protected]'})
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == "https")
response = http.request(req)

See more in my blog: EOFError: end of file reached issue when post a form with Net::HTTP.

Angular JS POST request not sending JSON data

you can use your method by this way

var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();

$http({
    url: '/api/apiControllerName/methodName',
    method: 'POST',
    params: {application:app, from:d1, to:d2},
    headers: { 'Content-Type': 'application/json;charset=utf-8' },
    //timeout: 1,
    //cache: false,
    //transformRequest: false,
    //transformResponse: false
}).then(function (results) {
    return results;
}).catch(function (e) {

});

How to generate java classes from WSDL file

Yes you can use:

Wsdl2java eclipse plugin

With this all you will need is to supply the wsdl, and the client which is the Java classes will be automatically generated for you.

How to get info on sent PHP curl request

If you set CURLINFO_HEADER_OUT to true, outgoing headers are available in the array returned by curl_getinfo(), under request_header key:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://foo.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

curl_exec($ch);

$info = curl_getinfo($ch);
print_r($info['request_header']);

This will print:

GET /bar HTTP/1.1
Authorization: Basic c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk
Host: foo.com
Accept: */*

Note the auth details are base64-encoded:

echo base64_decode('c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk');
// prints: someusername:secretpassword

Also note that username and password need to be percent-encoded to escape any URL reserved characters (/, ?, &, : and so on) they might contain:

curl_setopt($ch, CURLOPT_USERPWD, urlencode($username).':'.urlencode($password));

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

it's not a login issue most times. The database might not have been created. To create the database, Go to db context file and add this.Database.EnsureCreated();

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

Make sure you have the EntityFramework Nuget package installed for your project.

From @TonyDing's answer:

Right-click on the Solution from the Visual Studio Solution Explorer click the Manage Nuget packages for solution and install the EntityFramework

Once it is installed, I still had the error, but then did a reinstall per @papergodzilla's comment:

Update-Package -reinstall

and it resolved my issue

Do this in the Package Manager Console (View > Other windows > Package Manager Console).
Now everything is good!

Question mark and colon in statement. What does it mean?

It is the ternary conditional operator.

If the condition in the parenthesis before the ? is true, it returns the value to the left of the :, otherwise the value to the right.

Compare and contrast REST and SOAP web services?

SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data

WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.

SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON

This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.

With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.

It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.

Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.

REST is over only HTTP

Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.

P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284

How to call a Web Service Method?

write return(secondmethod) inside of the first method

enter image description here

Call a REST API in PHP

If you are open to use third party tools you'd have a look at this one: https://github.com/CircleOfNice/DoctrineRestDriver

This is a completely new way to work with APIs.

First of all you define an entity which is defining the structure of incoming and outcoming data and annotate it with datasources:

/*
 * @Entity
 * @DataSource\Select("http://www.myApi.com/products/{id}")
 * @DataSource\Insert("http://www.myApi.com/products")
 * @DataSource\Select("http://www.myApi.com/products/update/{id}")
 * @DataSource\Fetch("http://www.myApi.com/products")
 * @DataSource\Delete("http://www.myApi.com/products/delete/{id}")
 */
class Product {
    private $name;

    public function setName($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

Now it's pretty easy to communicate with the REST API:

$product = new Product();
$product->setName('test');
// sends an API request POST http://www.myApi.com/products ...
$em->persist($product);
$em->flush();

$product->setName('newName');
// sends an API request UPDATE http://www.myApi.com/products/update/1 ...
$em->flush();

How to change webservice url endpoint?

I wouldn't go so far as @Femi to change the existing address property. You can add new services to the definitions section easily.

<wsdl:service name="serviceMethodName_2">
  <wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
    <soap:address location="http://new_end_point_adress"/>
  </wsdl:port>
</wsdl:service>

This doesn't require a recompile of the WSDL to Java and making updates isn't any more difficult than if you used the BindingProvider option (which didn't work for me btw).

How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

Instead of modding the auto-generated code or wrapping every call in duplicate code, you can inject your custom HTTP headers by adding a custom message inspector, it's easier than it sounds:

public class CustomMessageInspector : IClientMessageInspector
{
    readonly string _authToken;

    public CustomMessageInspector(string authToken)
    {
        _authToken = authToken;
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        var reqMsgProperty = new HttpRequestMessageProperty();
        reqMsgProperty.Headers.Add("Auth-Token", _authToken);
        request.Properties[HttpRequestMessageProperty.Name] = reqMsgProperty;
        return null;
    }

    public void AfterReceiveReply(ref Message reply, object correlationState)
    { }
}


public class CustomAuthenticationBehaviour : IEndpointBehavior
{
    readonly string _authToken;

    public CustomAuthenticationBehaviour (string authToken)
    {
        _authToken = authToken;
    }
    public void Validate(ServiceEndpoint endpoint)
    { }

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    { }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    { }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.ClientMessageInspectors.Add(new CustomMessageInspector(_authToken));
    }
}

And when instantiating your client class you can simply add it as a behavior:

this.Endpoint.EndpointBehaviors.Add(new CustomAuthenticationBehaviour("Auth Token"));

This will make every outgoing service call to have your custom HTTP header.

How do I solve this error, "error while trying to deserialize parameter"

I have a solution for this but not sure on the reason why this would be different from one environment to the other - although one big difference between the two environments is WSS svc pack 1 was installed on the environment where the error was occurring.

To fix this issue I got a good clue from this link - http://silverlight.net/forums/t/22787.aspx ie to "please check the Xml Schema of your service" and "the sequence in the schema is sorted alphabetically"

Looking at the wsdl generated I noticed that for the serialized class that was causing the error, the properties of this class were not visible in the wsdl.

The Definition of the class had private setters for most of the properties, but not for CustomFields property ie..

[Serializable]
public class FileMetaDataDto
{
    .
    . a constructor...   etc and several other properties edited for brevity
    . 

    public int Id { get; private set; }
    public string Version { get; private set; }
    public List<MetaDataValueDto> CustomFields { get; set; }

}

On removing private from the setter and redeploying the service then looking at the wsdl again, these properties were now visible, and the original error was fixed.

So the wsdl before update was

- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" /> 
  </s:sequence>
  </s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" /> 
  </s:sequence>
  </s:complexType>

The wsdl after update was

- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" /> 
  </s:sequence>
  </s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="1" maxOccurs="1" name="Id" type="s:int" /> 
  <s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="Title" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="ContentType" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="Icon" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="ModifiedBy" type="s:string" /> 
  <s:element minOccurs="1" maxOccurs="1" name="ModifiedDateTime" type="s:dateTime" /> 
  <s:element minOccurs="1" maxOccurs="1" name="FileSizeBytes" type="s:int" /> 
  <s:element minOccurs="0" maxOccurs="1" name="Url" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="RelativeFolderPath" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="DisplayVersion" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="Version" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" /> 
  <s:element minOccurs="0" maxOccurs="1" name="CheckoutBy" type="s:string" /> 
  </s:sequence>
  </s:complexType>

Best/Most Comprehensive API for Stocks/Financial Data

Some of the brokerage firms like TDAmeritrade have APIs you can use to get streaming data from their servers:

http://www.tdameritrade.com/tradingtools/partnertools/api_dev.html

Where to find free public Web Services?

https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.

JAXB Exception: Class not known to this context

I had the same exception on Tomcat.. I found another problem - when i use wsimport over maven plugin to generate stubs for more then 1 WSDLs - class ObjectFactory (stubs references to this class) contains methods ONLY for one wsdl. So you should merge all methods in one ObjectFactory class (for each WSDL) or generate each wsdl stubs in different directories (there will be separates ObjectFactory classes). It solves problem for me with this exception..J

UEFA/FIFA scores API

You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).

We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)

Maximum length of HTTP GET request

As already mentioned, HTTP itself doesn't impose any hard-coded limit on request length; but browsers have limits ranging on the 2048 character allowed in the GET method.

How to send a POST request using volley with string body?

Name = editTextName.getText().toString().trim();
Email = editTextEmail.getText().toString().trim();
Phone = editTextMobile.getText().toString().trim();


JSONArray jsonArray = new JSONArray();
jsonArray.put(Name);
jsonArray.put(Email);
jsonArray.put(Phone);
final String mRequestBody = jsonArray.toString();

StringRequest stringRequest = new StringRequest(Request.Method.PUT, OTP_Url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.v("LOG_VOLLEY", response);

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("LOG_VOLLEY", error.toString());
    }
}) {
    @Override
    public String getBodyContentType() {
        return "application/json; charset=utf-8";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
            return null;
        }
    }

};
stringRequest.setShouldCache(false);
VollySupport.getmInstance(RegisterActivity.this).addToRequestque(stringRequest);

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

I've had a very similar issue using spring-boot-starter-data-redis. To my implementation there was offered a @Bean for RedisTemplate as follows:

@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
    final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));

    // Add some specific configuration here. Key serializers, etc.
    return template;
}

The fix was to specify an array of RoutePlantCache as following:

template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));

Below the exception I had:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
 at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]

PKIX path building failed: unable to find valid certification path to requested target

Here is the solution that I used for installing a site's public cert into the systems keystore for use.

Download the certificate with the following command:

unix, linux, mac

openssl s_client -connect [host]:[port|443] < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > [host].crt

windows

openssl s_client -connect [host]:[port|443] < NUL | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > [host].crt

That will create a crt that can be used to import into a keystore.

Install the new certificate with the command:

keytool -import -alias "[host]" -keystore [path to keystore] -file [host].crt

This will allow you to import the new cert from the site that is causing the exception.

What is tempuri.org?

Unfortunately the tempuri.org URL now just redirects to Bing.

You can see what it used to render via archive.org:

https://web.archive.org/web/20090304024056/http://tempuri.org/

To quote:

Each XML Web Service needs a unique namespace in order for client applications to distinguish it from other services on the Web. By default, ASP.Net Web Services use http://tempuri.org/ for this purpose. While this suitable for XML Web Services under development, published services should use a unique, permanent namespace.

Your XML Web Service should be identified by a namespace that you control. For example, you can use your company's Internet domain name as part of the namespace. Although many namespaces look like URLs, they need not point to actual resources on the Web.

For XML Web Services creating[sic] using ASP.NET, the default namespace can be changed using the WebService attribute's Namespace property. The WebService attribute is applied to the class that contains the XML Web Service methods. Below is a code example that sets the namespace to "http://microsoft.com/webservices/":

C#

[WebService(Namespace="http://microsoft.com/webservices/")]
public class MyWebService {
   // implementation
}

Visual Basic.NET

<WebService(Namespace:="http://microsoft.com/webservices/")> Public Class MyWebService
    ' implementation
End Class

Visual J#.NET

/**@attribute WebService(Namespace="http://microsoft.com/webservices/")*/
public class MyWebService {
    // implementation
}

It's also worth reading section 'A 1.3 Generating URIs' at:

http://www.w3.org/TR/wsdl#_Toc492291092

How to call a SOAP web service on Android

I had my tryst with KSOAP; I chose a rather simpler approach.

Given a WSDL file, create SOAP Request templates for each Request(for e.g.: using SOAP UI) and then substitute the values to be passed in code. POST this data to the service end point using DefaultHttpClient instance and get the response stream. Parse the Response Stream using an XML Pull parser.

How to consume REST in Java

As others have said, you can do it using the lower level HTTP API, or you can use the higher level JAXRS APIs to consume a service as JSON. For example:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://host:8080/context/rest/method");
JsonArray response = target.request(MediaType.APPLICATION_JSON).get(JsonArray.class);

Create a asmx web service in C# using visual studio 2013

Short answer: Don't do it.

Longer answer: Use WCF. It's here to replace Asmx.

see this answer for example, or the first comment on this one.

John Saunders: ASMX is a legacy technology, and should not be used for new development. WCF or ASP.NET Web API should be used for all new development of web service clients and servers. One hint: Microsoft has retired the ASMX Forum on MSDN.


As for comment ... well, if you have to, you have to. I'll leave you in the competent hands of the other answers then. (Even though it's funny it has issues, and if it does, why are you doing it in VS2013 to begin with ?)

What is the difference between Document style and RPC style communication?

I think what you are asking is the difference between RPC Literal, Document Literal and Document Wrapped SOAP web services.

Note that Document web services are delineated into literal and wrapped as well and they are different - one of the primary difference is that the latter is BP 1.1 compliant and the former is not.

Also, in Document Literal the operation to be invoked is not specified in terms of its name whereas in Wrapped, it is. This, I think, is a significant difference in terms of easily figuring out the operation name that the request is for.

In terms of RPC literal versus Document Wrapped, the Document Wrapped request can be easily vetted / validated against the schema in the WSDL - one big advantage.

I would suggest using Document Wrapped as the web service type of choice due to its advantages.

SOAP on HTTP is the SOAP protocol bound to HTTP as the carrier. SOAP could be over SMTP or XXX as well. SOAP provides a way of interaction between entities (client and servers, for example) and both entities can marshal operation arguments / return values as per the semantics of the protocol.

If you were using XML over HTTP (and you can), it is simply understood to be XML payload on HTTP request / response. You would need to provide the framework to marshal / unmarshal, error handling and so on.

A detailed tutorial with examples of WSDL and code with emphasis on Java: SOAP and JAX-WS, RPC versus Document Web Services

REST API error return good practices

If the client quota is exceeded it is a server error, avoid 5xx in this instance.

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

What is the difference between a web API and a web service?

The basic difference between Web Services and Web APIs

Web Service:

1) It is a SOAP-based service and returns data as XML.

2) It only supports the HTTP protocol.

3) It is not open source but can be used by any client that understands XML.

5) It requires a SOAP protocol to receive and send data over the network, so it is not a light-weight architecture.

Web API:

1) A Web API is an HTTP based service and returns JSON or XML data by default.

2) It supports the HTTP protocol.

3) It can be hosted within an application or IIS.

4) It is open source and it can be used by any client that understands JSON or XML.

5) It has light-weight architecture and good for devices which have limited bandwidth, like mobile devices.

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

Found transport-attribute in binding-element which tells us that this is the WSDL 1.1 binding for the SOAP 1.1 HTTP binding.

ex.

<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

How to increase the timeout period of web service in asp.net?

In app.config file (or .exe.config) you can add or change the "receiveTimeout" property in binding. like this

<binding name="WebServiceName" receiveTimeout="00:00:59" />

How to access SOAP services from iPhone

Here is a swift 4 sample code which execute API calling using SOAP service format.

   func callSOAPWSToGetData() {

        let strSOAPMessage =
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "<soap:Body>" +
                "<CelsiusToFahrenheit xmlns=\"http://www.yourapi.com/webservices/\">" +
                "<Celsius>50</Celsius>" +
                "</CelsiusToFahrenheit>" +
                "</soap:Body>" +
        "</soap:Envelope>"

        guard let url = URL.init(string: "http://www.example.org") else {
            return
        }
        var request = URLRequest.init(url: url)
        let length = (strSOAPMessage as NSString).length
        request.addValue("application/soap+xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.addValue("http://www.yourapi.com/webservices/CelsiusToFahrenheit", forHTTPHeaderField: "SOAPAction")
        request.addValue(String(length), forHTTPHeaderField: "Content-Length")
        request.httpMethod = "POST"
        request.httpBody = strSOAPMessage.data(using: .utf8)

        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
        let task = session.dataTask(with: request) { (data, response, error) in
            guard let responseData = data else {
                print("Error: did not receive data")
                return
            }
            guard error == nil else {
                print("error calling GET on /todos/1")
                print(error ?? "")
                return
            }
            print(responseData)
            let strData = String.init(data: responseData, encoding: .utf8)
            print(strData ?? "")
        }
        task.resume()
    }

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

In my case, on commenting out the

<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> 

in the web.config file was throwing "Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata".

Server did not recognize the value of HTTP Header SOAPAction

I had similar issue. To debug the problem, I've run Wireshark and capture request generated by my code. Then I used XML Spy trial to create a SOAP request (assuming you have WSDL) and compared those two.

This should give you a hint what goes wrong.

RESTful web service - how to authenticate requests from other services?

Besides authentication, I suggest you think about the big picture. Consider make your backend RESTful service without any authentication; then put some very simple authentication required middle layer service between the end user and the backend service.

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

Read response body in JAX-RS client from a post request

Realizing the revision of the code I found the cause of why the reading method did not work for me. The problem was that one of the dependencies that my project used jersey 1.x. Update the version, adjust the client and it works.

I use the following maven dependency:

<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>

Regards

Carlos Cepeda

Please initialize the log4j system properly. While running web service

You can configure log4j.properties like above answers, or use org.apache.log4j.BasicConfigurator

public class FooImpl implements Foo {

    private static final Logger LOGGER = Logger.getLogger(FooBar.class);

    public Object createObject() {
        BasicConfigurator.configure();
        LOGGER.info("something");
        return new Object();
    }
}

So under the table, configure do:

  configure() {
    Logger root = Logger.getRootLogger();
    root.addAppender(new ConsoleAppender(
           new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
  }

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

Working Soap client example

Yes, if you can acquire any WSDL file, then you can use SoapUI to create mock service of that service complete with unit test requests. I created an example of this (using Maven) that you can try out.

How to post SOAP Request from PHP

We can use the PHP cURL library to generate simple HTTP POST request. The following example shows you how to create a simple SOAP request using cURL.

Create the soap-server.php which write the SOAP request into soap-request.xml in web folder.

We can use the PHP cURL library to generate simple HTTP POST request. The following example shows you how to create a simple SOAP request using cURL.

Create the soap-server.php which write the SOAP request into soap-request.xml in web folder.


<?php
  $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
  $f = fopen("./soap-request.xml", "w");
  fwrite($f, $HTTP_RAW_POST_DATA);
  fclose($f);
?>


The next step is creating the soap-client.php which generate the SOAP request using the cURL library and send it to the soap-server.php URL.

<?php
  $soap_request  = "<?xml version=\"1.0\"?>\n";
  $soap_request .= "<soap:Envelope xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">\n";
  $soap_request .= "  <soap:Body xmlns:m=\"http://www.example.org/stock\">\n";
  $soap_request .= "    <m:GetStockPrice>\n";
  $soap_request .= "      <m:StockName>IBM</m:StockName>\n";
  $soap_request .= "    </m:GetStockPrice>\n";
  $soap_request .= "  </soap:Body>\n";
  $soap_request .= "</soap:Envelope>";

  $header = array(
    "Content-type: text/xml;charset=\"utf-8\"",
    "Accept: text/xml",
    "Cache-Control: no-cache",
    "Pragma: no-cache",
    "SOAPAction: \"run\"",
    "Content-length: ".strlen($soap_request),
  );

  $soap_do = curl_init();
  curl_setopt($soap_do, CURLOPT_URL, "http://localhost/php-soap-curl/soap-server.php" );
  curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 10);
  curl_setopt($soap_do, CURLOPT_TIMEOUT,        10);
  curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true );
  curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($soap_do, CURLOPT_POST,           true );
  curl_setopt($soap_do, CURLOPT_POSTFIELDS,     $soap_request);
  curl_setopt($soap_do, CURLOPT_HTTPHEADER,     $header);

  if(curl_exec($soap_do) === false) {
    $err = 'Curl error: ' . curl_error($soap_do);
    curl_close($soap_do);
    print $err;
  } else {
    curl_close($soap_do);
    print 'Operation completed without any errors';
  }
?>


Enter the soap-client.php URL in browser to send the SOAP message. If success, Operation completed without any errors will be shown and the soap-request.xml will be created.

<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
  <soap:Body xmlns:m="http://www.example.org/stock">
    <m:GetStockPrice>
      <m:StockName>IBM</m:StockName>
    </m:GetStockPrice>
  </soap:Body>
</soap:Envelope>


Original - http://eureka.ykyuen.info/2011/05/05/php-send-a-soap-request-by-curl/

Difference between numeric, float and decimal in SQL Server

The case for Decimal

What it the underlying need?

It arises from the fact that, ultimately, computers represent, internally, numbers in binary format. That leads, inevitably, to rounding errors.

Consider this:

0.1 (decimal, or "base 10") = .00011001100110011... (binary, or "base 2")

The above ellipsis [...] means 'infinite'. If you look at it carefully, there is an infinite repeating pattern (='0011')

So, at some point the computer has to round that value. This leads to accumulation errors deriving from the repeated use of numbers that are inexactly stored.

Say that you want to store financial amounts (which are numbers that may have a fractional part). First of all, you cannot use integers obviously (integers don't have a fractional part). From a purely mathematical point of view, the natural tendency would be to use a float. But, in a computer, floats have the part of a number that is located after a decimal point - the "mantissa" - limited. That leads to rounding errors.

To overcome this, computers offer specific datatypes that limit the binary rounding error in computers for decimal numbers. These are the data type that should absolutely be used to represent financial amounts. These data types typically go by the name of Decimal. That's the case in C#, for example. Or, DECIMAL in most databases.

How can I remove 3 characters at the end of a string in php?

Just do:

echo substr($string, 0, -3);

You don't need to use a strlen call, since, as noted in the substr docs:

If length is given and is negative, then that many characters will be omitted from the end of string

WPF Databinding: How do I access the "parent" data context?

This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

What is a Memory Heap?

Presumably you mean heap from a memory allocation point of view, not from a data structure point of view (the term has multiple meanings).

A very simple explanation is that the heap is the portion of memory where dynamically allocated memory resides (i.e. memory allocated via malloc). Memory allocated from the heap will remain allocated until one of the following occurs:

  1. The memory is free'd
  2. The program terminates

If all references to allocated memory are lost (e.g. you don't store a pointer to it anymore), you have what is called a memory leak. This is where the memory has still been allocated, but you have no easy way of accessing it anymore. Leaked memory cannot be reclaimed for future memory allocations, but when the program ends the memory will be free'd up by the operating system.

Contrast this with stack memory which is where local variables (those defined within a method) live. Memory allocated on the stack generally only lives until the function returns (there are some exceptions to this, e.g. static local variables).

You can find more information about the heap in this article.

Debugging iframes with Chrome developer tools

In my fairly complex scenario the accepted answer for how to do this in Chrome doesn't work for me. You may want to try the Firefox debugger instead (part of the Firefox developer tools), which shows all of the 'Sources', including those that are part of an iFrame

How to see full absolute path of a symlink

realpath isn't available on all linux flavors, but readlink should be.

readlink -f symlinkName

The above should do the trick.

Alternatively, if you don't have either of the above installed, you can do the following if you have python 2.6 (or later) installed

python -c 'import os.path; print(os.path.realpath("symlinkName"))'

`require': no such file to load -- mkmf (LoadError)

The problem is still is recursive on Ubuntu 13/04/13.10/14.04

and

sudo apt-get install ruby1.9.1-dev

worked out for me okay. So If you are using Ubuntu 13.04/13.10/14.04 then using this will really come in handy.

This works even if ruby version is 1.9.3. This is because there is no ruby1.9.3-dev available in the Repository...

How to fetch all Git branches

Have tried many ways, only this one is simple and works for me.

for branch in $(git ls-remote -h git@<your_repository>.git | awk '{print $2}' | sed 's:refs/heads/::')
do
  git checkout "$branch"
  git pull
done

What certificates are trusted in truststore?

Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

keytool -list -v -keystore truststore.jks

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

Maven uses batch files to do its business. With any batch script, you must call another script using the call command so it knows to return back to your script after the called script completes. Try prepending call to all commands.

Another thing you could try is using the start command which should work similarly.

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

Plotly is missing in this list. I've linked the python binding page. It definitively has animated and interative 3D Charts. And since it is Open Source most of that is available offline. Of course it is working with Jupyter

Update div with jQuery ajax response html

You are setting the html of #showresults of whatever data is, and then replacing it with itself, which doesn't make much sense ?
I'm guessing you where really trying to find #showresults in the returned data, and then update the #showresults element in the DOM with the html from the one from the ajax call :

$('#submitform').click(function () {
    $.ajax({
        url: "getinfo.asp",
        data: {
            txtsearch: $('#appendedInputButton').val()
        },
        type: "GET",
        dataType: "html",
        success: function (data) {
            var result = $('<div />').append(data).find('#showresults').html();
            $('#showresults').html(result);
        },
        error: function (xhr, status) {
            alert("Sorry, there was a problem!");
        },
        complete: function (xhr, status) {
            //$('#showresults').slideDown('slow')
        }
    });
});

Responsive image align center bootstrap 3

If you're using Bootstrap v3.0.1 or greater, you should use this solution instead. It doesn't override Bootstrap's styles with custom CSS, but instead uses a Bootstrap feature.

My original answer is shown below for posterity


This is a pleasantly easy fix. Because .img-responsive from Bootstrap already sets display: block, you can use margin: 0 auto to center the image:

.product .img-responsive {
    margin: 0 auto;
}

How to convert PDF files to images

The thread "converting PDF file to a JPEG image" is suitable for your request.

One solution is to use a third-party library. ImageMagick is a very popular and is freely available too. You can get a .NET wrapper for it here. The original ImageMagick download page is here.

And you also can take a look at the thread "How to open a page from a pdf file in pictureBox in C#".

If you use this process to convert a PDF to tiff, you can use this class to retrieve the bitmap from TIFF.

public class TiffImage
{
    private string myPath;
    private Guid myGuid;
    private FrameDimension myDimension;
    public ArrayList myImages = new ArrayList();
    private int myPageCount;
    private Bitmap myBMP;

    public TiffImage(string path)
    {
        MemoryStream ms;
        Image myImage;

        myPath = path;
        FileStream fs = new FileStream(myPath, FileMode.Open);
        myImage = Image.FromStream(fs);
        myGuid = myImage.FrameDimensionsList[0];
        myDimension = new FrameDimension(myGuid);
        myPageCount = myImage.GetFrameCount(myDimension);
        for (int i = 0; i < myPageCount; i++)
        {
            ms = new MemoryStream();
            myImage.SelectActiveFrame(myDimension, i);
            myImage.Save(ms, ImageFormat.Bmp);
            myBMP = new Bitmap(ms);
            myImages.Add(myBMP);
            ms.Close();
        }
        fs.Close();
    }
}

Use it like so:

private void button1_Click(object sender, EventArgs e)
{
    TiffImage myTiff = new TiffImage("D:\\Some.tif");
    //imageBox is a PictureBox control, and the [] operators pass back
    //the Bitmap stored at that position in the myImages ArrayList in the TiffImage
    this.pictureBox1.Image = (Bitmap)myTiff.myImages[0];
    this.pictureBox2.Image = (Bitmap)myTiff.myImages[1];
    this.pictureBox3.Image = (Bitmap)myTiff.myImages[2];
}

Python nonlocal statement

a = 0    #1. global variable with respect to every function in program

def f():
    a = 0          #2. nonlocal with respect to function g
    def g():
        nonlocal a
        a=a+1
        print("The value of 'a' using nonlocal is ", a)
    def h():
        global a               #3. using global variable
        a=a+5
        print("The value of a using global is ", a)
    def i():
        a = 0              #4. variable separated from all others
        print("The value of 'a' inside a function is ", a)

    g()
    h()
    i()
print("The value of 'a' global before any function", a)
f()
print("The value of 'a' global after using function f ", a)

jQuery AJAX submit form

To avoid multiple formdata sends:

Don't forget to unbind submit event, before the form submited again, User can call sumbit function more than one time, maybe he forgot something, or was a validation error.

 $("#idForm").unbind().submit( function(e) {
  ....

HTML button onclick event

Having trouble with a button onclick event in jsfiddle?

If so see Onclick event not firing on jsfiddle.net

alternative to "!is.null()" in R

To handle undefined variables as well as nulls, you can use substitute with deparse:

nullSafe <- function(x) {
  if (!exists(deparse(substitute(x))) || is.null(x)) {
    return(NA)
  } else {
    return(x)
  }
}

nullSafe(my.nonexistent.var)

How to push JSON object in to array using javascript

var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};

var data = [];
data.push(postdata);

console.log(data);

Property '...' has no initializer and is not definitely assigned in the constructor

change the

fieldname?: any[]; 

to this:

fieldname?: any; 

Regular expression for letters, numbers and - _

/^[\w-_.]*$/

What is means By:

  • ^ Start of string

  • [......] Match characters inside

  • \w Any word character so 0-9 a-z A-Z

  • -_. Matched by charecter - and _ and .

  • Zero or more of pattern or unlimited $ End of string If you want to limit the amount of characters:

    /^[\w-_.]{0,5}$/
    

    {0,5} Means 0-5 Numbers & characters

Creating the Singleton design pattern in PHP5

You don't really need to use Singleton pattern because it's considered to be an antipattern. Basically there is a lot of reasons to not to implement this pattern at all. Read this to start with: Best practice on PHP singleton classes.

If after all you still think you need to use Singleton pattern then we could write a class that will allow us to get Singleton functionality by extending our SingletonClassVendor abstract class.

This is what I came with to solve this problem.

<?php
namespace wl;


/**
 * @author DevWL
 * @dosc allows only one instance for each extending class.
 * it acts a litle bit as registry from the SingletonClassVendor abstract class point of view
 * but it provides a valid singleton behaviour for its children classes
 * Be aware, the singleton pattern is consider to be an anti-pattern
 * mostly because it can be hard to debug and it comes with some limitations.
 * In most cases you do not need to use singleton pattern
 * so take a longer moment to think about it before you use it.
 */
abstract class SingletonClassVendor
{
    /**
     *  holds an single instance of the child class
     *
     *  @var array of objects
     */
    protected static $instance = [];

    /**
     *  @desc provides a single slot to hold an instance interchanble between all child classes.
     *  @return object
     */
    public static final function getInstance(){
        $class = get_called_class(); // or get_class(new static());
        if(!isset(self::$instance[$class]) || !self::$instance[$class] instanceof $class){
            self::$instance[$class] = new static(); // create and instance of child class which extends Singleton super class
            echo "new ". $class . PHP_EOL; // remove this line after testing
            return  self::$instance[$class]; // remove this line after testing
        }
        echo "old ". $class . PHP_EOL; // remove this line after testing
        return static::$instance[$class];
    }

    /**
     * Make constructor abstract to force protected implementation of the __constructor() method, so that nobody can call directly "new Class()".
     */
    abstract protected function __construct();

    /**
     * Make clone magic method private, so nobody can clone instance.
     */
    private function __clone() {}

    /**
     * Make sleep magic method private, so nobody can serialize instance.
     */
    private function __sleep() {}

    /**
     * Make wakeup magic method private, so nobody can unserialize instance.
     */
    private function __wakeup() {}

}

Use example:

/**
 * EXAMPLE
 */

/**
 *  @example 1 - Database class by extending SingletonClassVendor abstract class becomes fully functional singleton
 *  __constructor must be set to protected becaouse: 
 *   1 to allow instansiation from parent class 
 *   2 to prevent direct instanciation of object with "new" keword.
 *   3 to meet requierments of SingletonClassVendor abstract class
 */
class Database extends SingletonClassVendor
{
    public $type = "SomeClass";
    protected function __construct(){
        echo "DDDDDDDDD". PHP_EOL; // remove this line after testing
    }
}


/**
 *  @example 2 - Config ...
 */
class Config extends SingletonClassVendor
{
    public $name = "Config";
    protected function __construct(){
        echo "CCCCCCCCCC" . PHP_EOL; // remove this line after testing
    }
}

Just to prove that it works as expected:

/**
 *  TESTING
 */
$bd1 = Database::getInstance(); // new
$bd2 = Database::getInstance(); // old
$bd3 = Config::getInstance(); // new
$bd4 = Config::getInstance(); // old
$bd5 = Config::getInstance(); // old
$bd6 = Database::getInstance(); // old
$bd7 = Database::getInstance(); // old
$bd8 = Config::getInstance(); // old

echo PHP_EOL."COMPARE ALL DATABASE INSTANCES".PHP_EOL;
var_dump($bd1);
echo '$bd1 === $bd2' . ($bd1 === $bd2)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd2 === $bd6' . ($bd2 === $bd6)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd6 === $bd7' . ($bd6 === $bd7)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE

echo PHP_EOL;

echo PHP_EOL."COMPARE ALL CONFIG INSTANCES". PHP_EOL;
var_dump($bd3);
echo '$bd3 === $bd4' . ($bd3 === $bd4)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd4 === $bd5' . ($bd4 === $bd5)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd5 === $bd8' . ($bd5 === $bd8)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE

In Python, how do I index a list with another list?

L= {'a':'a','d':'d', 'h':'h'}
index= ['a','d','h'] 
for keys in index:
    print(L[keys])

I would use a Dict add desired keys to index

How can I auto hide alert box after it showing it?

You can't close an alert box with Javascript.

You could, however, use a window instead:

var w = window.open('','','width=100,height=100')
w.document.write('Message')
w.focus()
setTimeout(function() {w.close();}, 5000)

Convert Month Number to Month Name Function in SQL

Here is my solution using some information from others to solve a problem.

datename(month,dateadd(month,datepart(month,Help_HelpMain.Ticket_Closed_Date),-1)) as monthname

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

If you use an actuall version there is a "setup_xampp.bat/.sh" script in the root directory. The path has to be absolute but the script changes all needed paths to your current location.

passing argument to DialogFragment

So there is two ways to pass values from fragment/activity to dialog fragment:-

  1. Create dialog fragment object with make setter method and pass value/argument.

  2. Pass value/argument through bundle.

Method 1:

// Fragment or Activity 
@Override
public void onClick(View v) {
     DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
     dialog.setValue(header, body);
     dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");         
}


//  your dialog fragment
public class MyDialogFragment extends DialogFragment {
    String header; 
    String body;
    public void setValue(String header, String body) {   
          this.header = header;
          this.body = body;
    }
    // use above variable into your dialog fragment
}

Note:- This is not best way to do

Method 2:

// Fragment or Activity 
@Override
public void onClick(View v) {
     DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
     
     Bundle bundle = new Bundle();
     bundle.putString("header", "Header");
     bundle.putString("body", "Body");  
     dialog.setArguments(bundle);
     dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");         
}


//  your dialog fragment
public class MyDialogFragment extends DialogFragment {
    String header; 
    String body;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
             header = getArguments().getString("header","");
             body = getArguments().getString("body","");
        }
    }
    // use above variable into your dialog fragment
}

Note:- This is the best way to do.

Apple Cover-flow effect using jQuery or other library?

Check out momoflow: http://flow.momolog.info True coverflow effect, and performant on Webkit (Safari and Chrome) and Opera, ok on Firefox.

How do I remove a single breakpoint with GDB?

You can delete all breakpoints using

del <start_breakpoint_num> - <end_breakpoint_num>

To view the start_breakpoint_num and end_breakpoint_num use:

info break

SimpleDateFormat parsing date with 'Z' literal

In the pattern, the inclusion of a 'z' date-time component indicates that timezone format needs to conform to the General time zone "standard", examples of which are Pacific Standard Time; PST; GMT-08:00.

A 'Z' indicates that the timezone conforms to the RFC 822 time zone standard, e.g. -0800.

I think you need a DatatypeConverter ...

@Test
public void testTimezoneIsGreenwichMeanTime() throws ParseException {
    final Calendar calendar = javax.xml.bind.DatatypeConverter.parseDateTime("2010-04-05T17:16:00Z");
    TestCase.assertEquals("gotten timezone", "GMT+00:00", calendar.getTimeZone().getID());
}

JavaScript string and number conversion

You want to become familiar with parseInt() and toString().

And useful in your toolkit will be to look at a variable to find out what type it is—typeof:

<script type="text/javascript">
    /**
     * print out the value and the type of the variable passed in
     */

    function printWithType(val) {
        document.write('<pre>');
        document.write(val);
        document.write(' ');
        document.writeln(typeof val);
        document.write('</pre>');
    }

    var a = "1", b = "2", c = "3", result;

    // Step (1) Concatenate "1", "2", "3" into "123"
    // - concatenation operator is just "+", as long
    //   as all the items are strings, this works
    result = a + b + c;
    printWithType(result); //123 string

    // - If they were not strings you could do
    result = a.toString() + b.toString() + c.toString();
    printWithType(result); // 123 string

    // Step (2) Convert "123" into 123
    result = parseInt(result,10);
    printWithType(result); // 123 number

    // Step (3) Add 123 + 100 = 223
    result = result + 100;
    printWithType(result); // 223 number

    // Step (4) Convert 223 into "223"
    result = result.toString(); //
    printWithType(result); // 223 string

    // If you concatenate a number with a 
    // blank string, you get a string    
    result = result + "";
    printWithType(result); //223 string
</script>

Send message to specific client with socket.io and node.js

You can do this

On server.

global.io=require("socket.io")(server);

io.on("connection",function(client){
    console.log("client is ",client.id);
    //This is handle by current connected client 
    client.emit('messages',{hello:'world'})
    //This is handle by every client
    io.sockets.emit("data",{data:"This is handle by every client"})
    app1.saveSession(client.id)

    client.on("disconnect",function(){
        app1.deleteSession(client.id)
        console.log("client disconnected",client.id);
    })

})

    //And this is handle by particular client 
    var socketId=req.query.id
    if(io.sockets.connected[socketId]!=null) {
        io.sockets.connected[socketId].emit('particular User', {data: "Event response by particular user "});
    }

And on client, it is very easy to handle.

var socket=io.connect("http://localhost:8080/")
    socket.on("messages",function(data){
        console.log("message is ",data);
        //alert(data)
    })
    socket.on("data",function(data){
        console.log("data is ",data);
        //alert(data)
    })

    socket.on("particular User",function(data){
        console.log("data from server ",data);
        //alert(data)
    })

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

just uncheck the 'Sign the click once manifests' from the signing tab in project properties,it will remove the error and you can create a new one as from there.

Should I declare Jackson's ObjectMapper as a static field?

Although ObjectMapper is thread safe, I would strongly discourage from declaring it as a static variable, especially in multithreaded application. Not even because it is a bad practice, but because you are running a heavy risk of deadlocking. I am telling it from my own experience. I created an application with 4 identical threads that were getting and processing JSON data from web services. My application was frequently stalling on the following command, according to the thread dump:

Map aPage = mapper.readValue(reader, Map.class);

Beside that, performance was not good. When I replaced static variable with the instance based variable, stalling disappeared and performance quadrupled. I.e. 2.4 millions JSON documents were processed in 40min.56sec., instead of 2.5 hours previously.

CSS3 Box Shadow on Top, Left, and Right Only

It's better if you just cover the bottom part with another div and you will get consistent drop shadow across the board.

#servicesContainer {
  /*your css*/
  position: relative;
}

and it's fixed! like magic!

Centering a Twitter Bootstrap button

Bootstrap has it's own centering class named text-center.

<div class="span7 text-center"></div>

How do I send a POST request as a JSON?

This one works fine for me with apis

import requests

data={'Id':id ,'name': name}
r = requests.post( url = 'https://apiurllink', data = data)

How to configure Eclipse build path to use Maven dependencies?

I did like this..

Right click on the project--> configure-->convert to maven project. Right click on the project-->maven-->add dependencies.

Is it possible to have placeholders in strings.xml for runtime values?

A Direct Kotlin Solution to the problem:

strings.xml

<string name="customer_message">Hello, %1$s!\nYou have %2$d Products in your cart.</string>

kotlinActivityORFragmentFile.kt:

val username = "Andrew"
val products = 1000
val text: String = String.format(
      resources.getString(R.string.customer_message), username, products )

Using SED with wildcard

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt

How do I mount a remote Linux folder in Windows through SSH?

Dokan looks like a FUSE and sshfs implementation for Windows. If it works as expected and advertised, it would do exactly what you are looking for.

(Link updated and working 2015-10-15)

Stop embedded youtube iframe?

One cannot simply overestimate this post and answers thx OP and helpers. My solution with just video_id exchanging:

<div style="pointer-events: none;">
    <iframe id="myVideo" src="https://www.youtube.com/embed/video_id?rel=0&modestbranding=1&fs=0&controls=0&autoplay=1&showinfo=0&version=3&enablejsapi=1" width="560" height="315" frameborder="0"></iframe> </div>

    <button id="play">PLAY</button>

    <button id="pause">PAUSE</button>


    <script>
        $('#play').click(function() {
            $('#myVideo').each(function(){ 
                var frame = document.getElementById("myVideo");
                frame.contentWindow.postMessage(
                    '{"event":"command","func":"playVideo","args":""}', 
                    '*'); 
            });
        });

        $('#pause').click(function() {
            $('#myVideo').each(function(){ 
                var frame = document.getElementById("myVideo");
                frame.contentWindow.postMessage(
                  '{"event":"command","func":"pauseVideo","args":""}',
                  '*'); 
            });
        });
    </script>

C#: How would I get the current time into a string?

DateTime.Now.ToString("h:mm tt")
DateTime.Now.ToString("MM/dd/yyyy")

Here are some common format strings

$(document).ready shorthand

Even shorter variant is to use

$(()=>{

});

where $ stands for jQuery and ()=>{} is so called 'arrow function' that inherits this from the closure. (So that in this you'll probably have window instead of document.)

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

Since you have not specified you are connected to a server from the device or emulator so I guess you are using your application in the emulator.

If you are referring your localhost on your system from the Android emulator then you have to use http://10.0.2.2:8080/ Because Android emulator runs in a Virtual Machine therefore here 127.0.0.1 or localhost will be emulator's own loopback address.

Refer: Emulator Networking

How to get index in Handlebars each helper?

In the newer versions of Handlebars index (or key in the case of object iteration) is provided by default with the standard each helper.


snippet from : https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811

The index of the current array item has been available for some time now via @index:

{{#each array}}
    {{@index}}: {{this}}
{{/each}}

For object iteration, use @key instead:

{{#each object}}
    {{@key}}: {{this}}
{{/each}} 

android download pdf from url then open it with a pdf reader

Download source code from here (Open Pdf from url in Android Programmatically)

MainActivity.java

package com.deepshikha.openpdf;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView)findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
        webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

        webview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                progressbar.setVisibility(View.GONE);
            }
        });

    }
}

Thanks!

How do I export an Android Studio project?

It seems as if Android Studio is missing some features Eclipse has (which is surprising considering the choice to make Android Studio official IDE).

Eclipse had the ability to export zip files which could be sent over email for example. If you zip the folder from your workspace, and try to send it over Gmail for example, Gmail will refuse because the folder contains executable. Obviously you can delete files but that is inefficient if you do that frequently going back and forth from work.

Here's a solution though: You can use source control. Android Studio supports that. Your code will be stored online. A git will do the trick. Look under "VCS" in the top menu in Android Studio. It has many other benefits as well. One of the downsides though, is that if you use GitHub for free, your code is open source and everyone can see it.

jQuery - on change input text

I recently was wondering why my code doesn't work, then I realized, I need to setup the event handlers as soon as the document is loaded, otherwise when browser loads the code line by line, it loads the JavaScript, but it does not yet have the element to assign the event handler to it. with your example, it should be like this:

$(document).ready(function(){
     $("#kat").change(function(){ 
         alert("Hello");
     });
});

Parse JSON with R

Try below code using RJSONIO in console

library(RJSONIO)
library(RCurl)


json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")

json_file2 = RJSONIO::fromJSON(json_file)

head(json_file2)

Cancel a UIView animation?

Even if you cancel the animation in the ways above animation didStopSelector still runs. So if you have logic states in your application driven by animations you will have problems. For this reason with the ways described above I use the context variable of UIView animations. If you pass the current state of your program by the context param to the animation, when the animation stops your didStopSelector function may decide if it should do something or just return based on the current state and the state value passed as context.

Styling an input type="file" button

Update Nevermind, this doesn't work in IE or it's new brother, FF. Works on every other type of element as expected, but doesn't work on file inputs. A much better way to do this is to just create a file input and a label that links to it. Make the file input display none and boom, it works in IE9+ seamlessly.

Warning: Everything below this is crap!

By using pseudo elements positioned/sized against their container, we can get by with only one input file (no additional markup needed), and style as per usual.

Demo

<input type="file" class="foo">

.foo {
    display: block;
    position: relative;
    width: 300px;
    margin: auto;
    cursor: pointer;
    border: 0;
    height: 60px;
    border-radius: 5px;
    outline: 0;
}
.foo:hover:after {
    background: #5978f8;
}
.foo:after {
    transition: 200ms all ease;
    border-bottom: 3px solid rgba(0,0,0,.2);
    background: #3c5ff4;
    text-shadow: 0 2px 0 rgba(0,0,0,.2);
    color: #fff;
    font-size: 20px;
    text-align: center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: block;
    content: 'Upload Something';
    line-height: 60px;
    border-radius: 5px;
}

Enjoy guys!

Old Update

Turned this into a Stylus mixin. Should be easy enough for one of you cool SCSS cats to convert it.

file-button(button_width = 150px)
  display block
  position relative
  margin auto
  cursor pointer
  border 0
  height 0
  width 0
  outline none
  &:after
    position absolute
    top 0
    text-align center
    display block
    width button_width
    left -(button_width / 2)

Usage:

<input type="file">

input[type="file"]
    file-button(200px)

Downgrade npm to an older version

Before doing that Download Node Js 8.11.3 from the URL: download

Open command prompt and run this:

npm install -g [email protected]

use this version this is the stable version which works along with cordova 7.1.0

for installing cordova use : • npm install -g [email protected]

• Run command

• Cordova platform remove android (if you have old android code or code is having some issue)

• Cordova platform add android : for building android app in cordova Running: Corodva run android

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

How can I count the numbers of rows that a MySQL query returned?

Assuming you're using the mysql_ or mysqli_ functions, your question should already have been answered by others.

However if you're using PDO, there is no easy function to return the number of rows retrieved by a select statement, unfortunately. You have to use count() on the resultset (after assigning it to a local variable, usually).

Or if you're only interested in the number and not the data, PDOStatement::fetchColumn() on your SELECT COUNT(1)... result.

Python os.path.join on Windows

to join a windows path, try

mypath=os.path.join('c:\\', 'sourcedir')

basically, you will need to escape the slash

Is there functionality to generate a random character in Java?

I use this:

char uppercaseChar = (char) ((int)(Math.random()*100)%26+65);

char lowercaseChar = (char) ((int)(Math.random()*1000)%26+97);

How to obtain a QuerySet of all rows, with specific fields for each one of them?

We can select required fields over values.

Employee.objects.all().values('eng_name','rank')

How to link to a <div> on another page?

You simply combine the ideas of a link to another page, as with href=foo.html, and a link to an element on the same page, as with href=#bar, so that the fragment like #bar is written immediately after the URL that refers to another page:

<a href="foo.html#bar">Some nice link text</a>

The target is specified the same was as when linking inside one page, e.g.

<div id="bar">
<h2>Some heading</h2>
Some content
</div>

or (if you really want to link specifically to a heading only)

<h2 id="bar">Some heading</h2>

xml.LoadData - Data at the root level is invalid. Line 1, position 1

If your xml is in a string use the following to remove any byte order mark:

        xml = new Regex("\\<\\?xml.*\\?>").Replace(xml, "");

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

How do I get the Session Object in Spring?

i made my own utils. it is handy. :)

package samples.utils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContextUtils;


/**
 * SpringMVC????
 * 
 * @author ??([email protected])
 *
 */
public final class WebContextHolder {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebContextHolder.class);

    private static WebContextHolder INSTANCE = new WebContextHolder();

    public WebContextHolder get() {
        return INSTANCE;
    }

    private WebContextHolder() {
        super();
    }

    // --------------------------------------------------------------------------------------------------------------

    public HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attributes.getRequest();
    }

    public HttpSession getSession() {
        return getSession(true);
    }

    public HttpSession getSession(boolean create) {
        return getRequest().getSession(create);
    }

    public String getSessionId() {
        return getSession().getId();
    }

    public ServletContext getServletContext() {
        return getSession().getServletContext();    // servlet2.3
    }

    public Locale getLocale() {
        return RequestContextUtils.getLocale(getRequest());
    }

    public Theme getTheme() {
        return RequestContextUtils.getTheme(getRequest());
    }

    public ApplicationContext getApplicationContext() {
        return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    }

    public ApplicationEventPublisher getApplicationEventPublisher() {
        return (ApplicationEventPublisher) getApplicationContext();
    }

    public LocaleResolver getLocaleResolver() {
        return RequestContextUtils.getLocaleResolver(getRequest());
    }

    public ThemeResolver getThemeResolver() {
        return RequestContextUtils.getThemeResolver(getRequest());
    }

    public ResourceLoader getResourceLoader() {
        return (ResourceLoader) getApplicationContext();
    }

    public ResourcePatternResolver getResourcePatternResolver() {
        return (ResourcePatternResolver) getApplicationContext();
    }

    public MessageSource getMessageSource() {
        return (MessageSource) getApplicationContext();
    }

    public ConversionService getConversionService() {
        return getBeanFromApplicationContext(ConversionService.class);
    }

    public DataSource getDataSource() {
        return getBeanFromApplicationContext(DataSource.class);
    }

    public Collection<String> getActiveProfiles() {
        return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
    }

    public ClassLoader getBeanClassLoader() {
        return ClassUtils.getDefaultClassLoader();
    }

    private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
        try {
            return getApplicationContext().getBean(requiredType);
        } catch (NoUniqueBeanDefinitionException e) {
            LOGGER.error(e.getMessage(), e);
            throw e;
        } catch (NoSuchBeanDefinitionException e) {
            LOGGER.warn(e.getMessage());
            return null;
        }
    }

}

C# Clear Session

Found this article on net, very relevant to this topic. So posting here.

ASP.NET Internals - Clearing ASP.NET Session variables

How do I show a running clock in Excel?

See the below code (taken from this post)

Put this code in a Module in VBA (Developer Tab -> Visual Basic)

Dim TimerActive As Boolean
Sub StartTimer()
    Start_Timer
End Sub
Private Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
    TimerActive = False
End Sub
Private Sub Timer()
    If TimerActive Then
        ActiveSheet.Cells(1, 1).Value = Time
        Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
    End If
End Sub

You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.

Private Sub Workbook_Open()
    Module1.StartTimer
End Sub

Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.

How to specify jdk path in eclipse.ini on windows 8 when path contains space

Go to C drive root in cmd Type dir /x This will list down the directories name with ~.use that instead of Program Files in your jdk path

HTTP Basic Authentication - what's the expected web browser experience?

WWW-Authenticate header

You may also get this if the server is sending a 401 response code but not setting the WWW-Authenticate header correctly - I should know, I've just fixed that in out own code because VB apps weren't popping up the authentication prompt.

How can I check the extension of a file?

Some of the answers above don't account for folder names with periods. (folder.mp3 is a valid folder name). You should make sure the "file" isn't actually a folder before checking the extension.


Checking the extension of a file:

import os

file_path = "C:/folder/file.mp3"
if os.path.isfile(file_path):
    file_extension = os.path.splitext(file_path)[1]
    if file_extension.lower() == ".mp3":
        print("It's an mp3")
    if file_extension.lower() == ".flac":
        print("It's a flac")

Output:

It's an mp3

Checking the extension of all files in a folder:

import os

directory = "C:/folder"
for file in os.listdir(directory):
    file_path = os.path.join(directory, file)
    if os.path.isfile(file_path):
        file_extension = os.path.splitext(file_path)[1]
        print(file, "ends in", file_extension)

Output:

abc.txt ends in .txt
file.mp3 ends in .mp3
song.flac ends in .flac

Comparing file extension against multiple types:

import os

file_path = "C:/folder/file.mp3"
if os.path.isfile(file_path):
    file_extension = os.path.splitext(file_path)[1]
    if file_extension.lower() in {'.mp3', '.flac', '.ogg'}:
        print("It's a music file")
    elif file_extension.lower() in {'.jpg', '.jpeg', '.png'}:
        print("It's an image file")

Output:

It's a music file

how to automatically scroll down a html page?

here is the example using Pure JavaScript

_x000D_
_x000D_
function scrollpage() {  _x000D_
 function f() _x000D_
 {_x000D_
  window.scrollTo(0,i);_x000D_
  if(status==0) {_x000D_
      i=i+40;_x000D_
   if(i>=Height){ status=1; } _x000D_
  } else {_x000D_
   i=i-40;_x000D_
   if(i<=1){ status=0; }  // if you don't want continue scroll then remove this line_x000D_
  }_x000D_
 setTimeout( f, 0.01 );_x000D_
 }f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
 #top { border: 1px solid black;  height: 20000px; }_x000D_
 #bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
_x000D_
_x000D_

Programmatically stop execution of python script?

You want sys.exit(). From Python's docs:

>>> import sys
>>> print sys.exit.__doc__
exit([status])

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).

So, basically, you'll do something like this:

from sys import exit

# Code!

exit(0) # Successful exit

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

assuming your project is maven based, add it to your POM:

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.26</version>
    </dependency>

Save > Build > and test connection again. It works! Your actual mysql java connector version may vary.

Creating a config file in PHP

Use an INI file is a flexible and powerful solution! PHP has a native function to handle it properly. For example, it is possible to create an INI file like this:

app.ini

[database]
db_name     = mydatabase
db_user     = myuser
db_password = mypassword

[application]
app_email = [email protected]
app_url   = myapp.com

So the only thing you need to do is call:

$ini = parse_ini_file('app.ini');

Then you can access the definitions easily using the $ini array.

echo $ini['db_name'];     // mydatabase
echo $ini['db_user'];     // myuser
echo $ini['db_password']; // mypassword
echo $ini['app_email'];   // [email protected]

IMPORTANT: For security reasons the INI file must be in a non public folder

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

In a pinch, you can disable SSL entirely, or per connection (note this is not recommended for production!) see https://stackoverflow.com/a/19542614/32453

Java: How to set Precision for double value?

To expand on @EJP, the concept of 'precision' when dealing with doubles is extremely fraught. As discussed in https://stackoverflow.com/a/3730040/390153 you can't even represent 0.1 as a double regardless of the precision, for the same reason you can't represent 1/3 in base 10 with finite precision.

You need to consider the problem you are trying to solve, and consider:

a) Should I be using doubles in the first place; if precision is a relevant concept, then using doubles may well be a mistake.

b) If doubles are appropriate, what do I mean by precision? If you are only talking about display, wrap the logic in a display function and you will only need to deal with it in one place; ie. apply the DRY principle.

How do I parse command line arguments in Java?

If you are already using Spring Boot, argument parsing comes out of the box.

If you want to run something after startup, implement the ApplicationRunner interface:

@SpringBootApplication
public class Application implements ApplicationRunner {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Override
  public void run(ApplicationArguments args) {
    args.containsOption("my-flag-option"); // test if --my-flag-option was set
    args.getOptionValues("my-option");     // returns values of --my-option=value1 --my-option=value2 
    args.getOptionNames();                 // returns a list of all available options
    // do something with your args
  }
}

Your run method will be invoked after the context has started up successfully.

If you need access to the arguments before you fire up your application context, you can just simply parse the application arguments manually:

@SpringBootApplication
public class Application implements ApplicationRunner {

  public static void main(String[] args) {
    ApplicationArguments arguments = new DefaultApplicationArguments(args);
    // do whatever you like with your arguments
    // see above ...
    SpringApplication.run(Application.class, args);
  }

}

And finally, if you need access to your arguments in a bean, just inject the ApplicationArguments:

@Component
public class MyBean {

   @Autowired
   private ApplicationArguments arguments;

   // ...
}

How to remove an element from the flow?

Try to use this:

position: relative;
clear: both;

I use it when I can't use absolute position, for example in printing when you use page-break-after: always; works fine only with position:relative.

R memory management / cannot allocate vector of size n Mb

For Windows users, the following helped me a lot to understand some memory limitations:

  • before opening R, open the Windows Resource Monitor (Ctrl-Alt-Delete / Start Task Manager / Performance tab / click on bottom button 'Resource Monitor' / Memory tab)
  • you will see how much RAM memory us already used before you open R, and by which applications. In my case, 1.6 GB of the total 4GB are used. So I will only be able to get 2.4 GB for R, but now comes the worse...
  • open R and create a data set of 1.5 GB, then reduce its size to 0.5 GB, the Resource Monitor shows my RAM is used at nearly 95%.
  • use gc() to do garbage collection => it works, I can see the memory use go down to 2 GB

enter image description here

Additional advice that works on my machine:

  • prepare the features, save as an RData file, close R, re-open R, and load the train features. The Resource Manager typically shows a lower Memory usage, which means that even gc() does not recover all possible memory and closing/re-opening R works the best to start with maximum memory available.
  • the other trick is to only load train set for training (do not load the test set, which can typically be half the size of train set). The training phase can use memory to the maximum (100%), so anything available is useful. All this is to take with a grain of salt as I am experimenting with R memory limits.

Does C have a "foreach" loop construct?

C does not have an implementation of for-each. When parsing an array as a point the receiver does not know how long the array is, thus there is no way to tell when you reach the end of the array. Remember, in C int* is a point to a memory address containing an int. There is no header object containing information about how many integers that are placed in sequence. Thus, the programmer needs to keep track of this.

However, for lists, it is easy to implement something that resembles a for-each loop.

for(Node* node = head; node; node = node.next) {
   /* do your magic here */
}

To achieve something similar for arrays you can do one of two things.

  1. use the first element to store the length of the array.
  2. wrap the array in a struct which holds the length and a pointer to the array.

The following is an example of such struct:

typedef struct job_t {
   int count;
   int* arr;
} arr_t;

Get a file name from a path

Dont use _splitpath() and _wsplitpath(). They are not safe, and they are obsolete!

Instead, use their safe versions, namely _splitpath_s() and _wsplitpath_s()

Simple Deadlock Examples

public class DeadlockProg {

    /**
     * @Gowtham Chitimi Reddy IIT(BHU);
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final Object ob1 = new Object();
        final Object ob2 = new Object();
        Thread t1 = new Thread(){
            public void run(){
                synchronized(ob1){
                    try{
                        Thread.sleep(100);
                    }
                    catch(InterruptedException e){
                        System.out.println("Error catched");
                    }
                    synchronized(ob2){

                    }
                }

            }
        };
        Thread t2 = new Thread(){
            public void run(){
                synchronized(ob2){
                    try{
                        Thread.sleep(100);
                    }
                    catch(InterruptedException e){
                        System.out.println("Error catched");
                    }
                    synchronized(ob1){                      
                    }
                }               
            }
        };
        t1.start();
        t2.start();
    }

}

How to parse date string to Date?

Here is a working example:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;

public class j4496359 {
    public static void main(String[] args) {
        try {
            String target = "Thu Sep 28 20:29:30 JST 2000";
            DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
            Date result =  df.parse(target);
            System.out.println(result); 
        } catch (ParseException pe) {
            pe.printStackTrace();
        }
    }
}

Will print:

Thu Sep 28 13:29:30 CEST 2000

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

How can I build XML in C#?

XmlWriter is the fastest way to write good XML. XDocument, XMLDocument and some others works good aswell, but are not optimized for writing XML. If you want to write the XML as fast as possible, you should definitely use XmlWriter.

Using Colormaps to set color of line in matplotlib

I thought it would be beneficial to include what I consider to be a more simple method using numpy's linspace coupled with matplotlib's cm-type object. It's possible that the above solution is for an older version. I am using the python 3.4.3, matplotlib 1.4.3, and numpy 1.9.3., and my solution is as follows.

import matplotlib.pyplot as plt

from matplotlib import cm
from numpy import linspace

start = 0.0
stop = 1.0
number_of_lines= 1000
cm_subsection = linspace(start, stop, number_of_lines) 

colors = [ cm.jet(x) for x in cm_subsection ]

for i, color in enumerate(colors):
    plt.axhline(i, color=color)

plt.ylabel('Line Number')
plt.show()

This results in 1000 uniquely-colored lines that span the entire cm.jet colormap as pictured below. If you run this script you'll find that you can zoom in on the individual lines.

cm.jet between 0.0 and 1.0 with 1000 graduations

Now say I want my 1000 line colors to just span the greenish portion between lines 400 to 600. I simply change my start and stop values to 0.4 and 0.6 and this results in using only 20% of the cm.jet color map between 0.4 and 0.6.

enter image description here

So in a one line summary you can create a list of rgba colors from a matplotlib.cm colormap accordingly:

colors = [ cm.jet(x) for x in linspace(start, stop, number_of_lines) ]

In this case I use the commonly invoked map named jet but you can find the complete list of colormaps available in your matplotlib version by invoking:

>>> from matplotlib import cm
>>> dir(cm)

How to get access to raw resources that I put in res folder?

TextView txtvw = (TextView)findViewById(R.id.TextView01);
        txtvw.setText(readTxt());

 private String readTxt()
    {
    InputStream raw = getResources().openRawResource(R.raw.hello);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int i;
    try
    {
        i = raw.read();
        while (i != -1)
        {
            byteArrayOutputStream.write(i);
            i = raw.read();
        }
        raw.close();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block

        e.printStackTrace();
    }


    return byteArrayOutputStream.toString();

}

TextView01:: txtview in linearlayout hello:: .txt file in res/raw folder (u can access ny othr folder as wel)

Ist 2 lines are 2 written in onCreate() method

rest is to be written in class extending Activity!!

Mongoose.js: Find user by username LIKE value

Just complementing @PeterBechP 's answer.

Don't forget to scape the special chars. https://stackoverflow.com/a/6969486

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

var name = 'Peter+with+special+chars';

model.findOne({name: new RegExp('^'+escapeRegExp(name)+'$', "i")}, function(err, doc) {
  //Do your action here..
});

How to check if dropdown is disabled?

I was searching for something like this, because I've got to check which of all my selects are disabled.

So I use this:

let select= $("select");

for (let i = 0; i < select.length; i++) {
    const element = select[i];
    if(element.disabled == true ){
        console.log(element)
    }
}

A weighted version of random.choice

One way is to randomize on the total of all the weights and then use the values as the limit points for each var. Here is a crude implementation as a generator.

def rand_weighted(weights):
    """
    Generator which uses the weights to generate a
    weighted random values
    """
    sum_weights = sum(weights.values())
    cum_weights = {}
    current_weight = 0
    for key, value in sorted(weights.iteritems()):
        current_weight += value
        cum_weights[key] = current_weight
    while True:
        sel = int(random.uniform(0, 1) * sum_weights)
        for key, value in sorted(cum_weights.iteritems()):
            if sel < value:
                break
        yield key

Can MySQL convert a stored UTC time to local timezone?

I am not sure what math can be done on a DATETIME data type, but if you are using PHP, I strongly recommend using the integer-based timestamps. Basically, you can store a 4-byte integer in the database using PHP's time() function. This makes doing math on it much more straightforward.

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

This is now no longer needed for Java 9, nor for any recent release of Java 6, 7, or 8. Finally! :)

Per JDK-8170157, the unlimited cryptographic policy is now enabled by default.

Specific versions from the JIRA issue:

  • Java 9 (10, 11, etc..): Any official release!
  • Java 8u161 or later (Available now)
  • Java 7u171 or later (Only available through 'My Oracle Support')
  • Java 6u181 or later (Only available through 'My Oracle Support')

Note that if for some odd reason the old behavior is needed in Java 9, it can be set using:

Security.setProperty("crypto.policy", "limited");

How do I jump to a closing bracket in Visual Studio Code?

You can learn commands from the command palette Ctrl/Cmd + Shift + P). Look for "Go to Bracket". The keybinding is also shown there.

How do I make a simple crawler in PHP?

It's an old question. A lot of good things happened since then. Here are my two cents on this topic:

  1. To accurately track the visited pages you have to normalize URI first. The normalization algorithm includes multiple steps:

    • Sort query parameters. For example, the following URIs are equivalent after normalization: GET http://www.example.com/query?id=111&cat=222 GET http://www.example.com/query?cat=222&id=111
    • Convert the empty path. Example: http://example.org ? http://example.org/

    • Capitalize percent encoding. All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive. Example: http://example.org/a%c2%B1b ? http://example.org/a%C2%B1b

    • Remove unnecessary dot-segments. Example: http://example.org/../a/b/../c/./d.html ? http://example.org/a/c/d.html

    • Possibly some other normalization rules

  2. Not only <a> tag has href attribute, <area> tag has it too https://html.com/tags/area/. If you don't want to miss anything, you have to scrape <area> tag too.

  3. Track crawling progress. If the website is small, it is not a problem. Contrarily it might be very frustrating if you crawl half of the site and it failed. Consider using a database or a filesystem to store the progress.

  4. Be kind to the site owners. If you are ever going to use your crawler outside of your website, you have to use delays. Without delays, the script is too fast and might significantly slow down some small sites. From sysadmins perspective, it looks like a DoS attack. A static delay between the requests will do the trick.

If you don't want to deal with that, try Crawlzone and let me know your feedback. Also, check out the article I wrote a while back https://www.codementor.io/zstate/this-is-how-i-crawl-n98s6myxm

How to run bootRun with spring profile via gradle task

Using this shell command it will work:

SPRING_PROFILES_ACTIVE=test gradle clean bootRun

Sadly this is the simplest way I have found. It sets environment property for that call and then runs the app.

Lollipop : draw behind statusBar with its color set to transparent

The Right solution is to Change a property in XML under your Activity tag to below style. It just works

  android:theme="@style/Theme.AppCompat.Light.NoActionBar"

setState() inside of componentDidUpdate()

this.setState creates an infinite loop when used in ComponentDidUpdate when there is no break condition in the loop. You can use redux to set a variable true in the if statement and then in the condition set the variable false then it will work.

Something like this.

if(this.props.route.params.resetFields){

        this.props.route.params.resetFields = false;
        this.setState({broadcastMembersCount: 0,isLinkAttached: false,attachedAffiliatedLink:false,affilatedText: 'add your affiliate link'});
        this.resetSelectedContactAndGroups();
        this.hideNext = false;
        this.initialValue_1 = 140;
        this.initialValue_2 = 140;
        this.height = 20
    }

jQuery - adding elements into an array

Try this, at the end of the each loop, ids array will contain all the hexcodes.

var ids = [];

    $(document).ready(function($) {
    var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
    $(".color_cell").each(function() {
        code = $(this).attr('id');
        ids.push(code);
        $div.append(code + "<br />");
    });



});

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

you have to include two more jar files.

xmlbeans-2.3.0.jar and dom4j-1.6.1.jar Add try it will work.

Note: It is required for the files with .xlsx formats only, not for just .xlt formats.

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

Ways to implement data versioning in MongoDB

I worked through this solution that accommodates a published, draft and historical versions of the data:

{
  published: {},
  draft: {},
  history: {
    "1" : {
      metadata: <value>,
      document: {}
    },
    ...
  }
}

I explain the model further here: http://software.danielwatrous.com/representing-revision-data-in-mongodb/

For those that may implement something like this in Java, here's an example:

http://software.danielwatrous.com/using-java-to-work-with-versioned-data/

Including all the code that you can fork, if you like

https://github.com/dwatrous/mongodb-revision-objects

SQL subquery with COUNT help

SELECT e.*,
       cnt.colCount 
FROM eventsTable e
INNER JOIN (
           select columnName,count(columnName) as colCount
           from eventsTable e2 
          group by columnName
           ) as cnt on cnt.columnName = e.columnName
WHERE e.columnName='Business'

-- Added space

Postgresql - change the size of a varchar column to lower length

Ok, I'm probably late to the party, BUT...

THERE'S NO NEED TO RESIZE THE COLUMN IN YOUR CASE!

Postgres, unlike some other databases, is smart enough to only use just enough space to fit the string (even using compression for longer strings), so even if your column is declared as VARCHAR(255) - if you store 40-character strings in the column, the space usage will be 40 bytes + 1 byte of overhead.

The storage requirement for a short string (up to 126 bytes) is 1 byte plus the actual string, which includes the space padding in the case of character. Longer strings have 4 bytes of overhead instead of 1. Long strings are compressed by the system automatically, so the physical requirement on disk might be less. Very long values are also stored in background tables so that they do not interfere with rapid access to shorter column values.

(http://www.postgresql.org/docs/9.0/interactive/datatype-character.html)

The size specification in VARCHAR is only used to check the size of the values which are inserted, it does not affect the disk layout. In fact, VARCHAR and TEXT fields are stored in the same way in Postgres.

Boolean vs tinyint(1) for boolean values in MySQL

While it's true that bool and tinyint(1) are functionally identical, bool should be the preferred option because it carries the semantic meaning of what you're trying to do. Also, many ORMs will convert bool into your programing language's native boolean type.

What should every programmer know about security?

Just wanted to share this for web developers:

security-guide-for-developers
https://github.com/FallibleInc/security-guide-for-developers

get original element from ng-click

You need $event.currentTarget instead of $event.target.

Errno 13 Permission denied Python

Your user don't have the right permissions to read the file, since you used open() without specifying a mode.

Since you're using Windows, you should read a little more about File and Folder Permissions.

Also, if you want to play with your file permissions, you should right-click it, choose Properties and select Security tab.

Or if you want to be a little more hardcore, you can run your script as admin.

SO Related Questions:

How to remove trailing whitespaces with sed?

Just for fun:

#!/bin/bash

FILE=$1

if [[ -z $FILE ]]; then
   echo "You must pass a filename -- exiting" >&2
   exit 1
fi

if [[ ! -f $FILE ]]; then
   echo "There is not file '$FILE' here -- exiting" >&2
   exit 1
fi

BEFORE=`wc -c "$FILE" | cut --delimiter=' ' --fields=1`

# >>>>>>>>>>
sed -i.bak -e's/[ \t]*$//' "$FILE"
# <<<<<<<<<<

AFTER=`wc -c "$FILE" | cut --delimiter=' ' --fields=1`

if [[ $? != 0 ]]; then
   echo "Some error occurred" >&2
else
   echo "Filtered '$FILE' from $BEFORE characters to $AFTER characters"
fi

VBScript -- Using error handling

I'm exceptionally new to VBScript, so this may not be considered best practice or there may be a reason it shouldn't be done this that way I'm not yet aware of, but this is the solution I came up with to trim down the amount of error logging code in my main code block.

Dim oConn, connStr
Set oConn = Server.CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX"

ON ERROR RESUME NEXT

oConn.Open connStr
If err.Number <> 0 Then : showError() : End If


Sub ShowError()

    'You could write the error details to the console...
    errDetail = "<script>" & _
    "console.log('Description: " & err.Description & "');" & _
    "console.log('Error number: " & err.Number & "');" & _
    "console.log('Error source: " & err.Source & "');" & _
    "</script>"

    Response.Write(errDetail)       

    '...you could display the error info directly in the page...
    Response.Write("Error Description: " & err.Description)
    Response.Write("Error Source: " & err.Source)
    Response.Write("Error Number: " & err.Number)

    '...or you could execute additional code when an error is thrown...
    'Insert error handling code here

    err.clear
End Sub

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Easiest solution for this to remove the index.php code which is allocated on

xammp-> htdocs-> index.php 

you can delete the code of this page to solution your problem but have another way which is .htaccss file. Some time you show this problem because of have some issue or miss code on .htaccss file thas way yo saw the xammp dashboard every time. Hop it will resolve your problem. Happy Coding and Good Luck

How to convert Set to Array?

SIMPLEST ANSWER

just spread the set inside []

let mySet = new Set()
mySet.add(1)
mySet.add(5)
mySet.add(5) 
let arr = [...mySet ]

Result: [1,5]

How can I uninstall Ruby on ubuntu?

Here is what sudo apt-get purge ruby* removed relating to GRUB for me:

grub-pc 
grub-gfxpayload-lists
grub2-common
grub-pc-bin 
grub-common 

Storing sex (gender) in database

An Int (or TinyInt) aligned to an Enum field would be my methodology.

First, if you have a single bit field in a database, the row will still use a full byte, so as far as space savings, it only pays off if you have multiple bit fields.

Second, strings/chars have a "magic value" feel to them, regardless of how obvious they may seem at design time. Not to mention, it lets people store just about any value they would not necessarily map to anything obvious.

Third, a numeric value is much easier (and better practice) to create a lookup table for, in order to enforce referential integrity, and can correlate 1-to-1 with an enum, so there is parity in storing the value in memory within the application or in the database.

Upload files from Java client to a HTTP server

You'd normally use java.net.URLConnection to fire HTTP requests. You'd also normally use multipart/form-data encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data request body. The specification is in more detail described in RFC2388.

Here's a kickoff example:

String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try (
    OutputStream output = connection.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
    // Send normal param.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
    writer.append(CRLF).append(param).append(CRLF).flush();

    // Send text file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
    writer.append(CRLF).flush();
    Files.copy(textFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // Send binary file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
    writer.append(CRLF).flush();
    Files.copy(binaryFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // End of multipart/form-data.
    writer.append("--" + boundary + "--").append(CRLF).flush();
}

// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200

This code is less verbose when you use a 3rd party library like Apache Commons HttpComponents Client.

The Apache Commons FileUpload as some incorrectly suggest here is only of interest in the server side. You can't use and don't need it at the client side.

See also

Determine if a String is an Integer in Java

You can use Integer.parseInt(str) and catch the NumberFormatException if the string is not a valid integer, in the following fashion (as pointed out by all answers):

static boolean isInt(String s)
{
 try
  { int i = Integer.parseInt(s); return true; }

 catch(NumberFormatException er)
  { return false; }
}

However, note here that if the evaluated integer overflows, the same exception will be thrown. Your purpose was to find out whether or not, it was a valid integer. So its safer to make your own method to check for validity:

static boolean isInt(String s)  // assuming integer is in decimal number system
{
 for(int a=0;a<s.length();a++)
 {
    if(a==0 && s.charAt(a) == '-') continue;
    if( !Character.isDigit(s.charAt(a)) ) return false;
 }
 return true;
}

How to find substring from string?

In C, use the strstr() standard library function:

const char *str = "/user/desktop/abc/post/";
const int exists = strstr(str, "/abc/") != NULL;

Take care to not accidentally find a too-short substring (this is what the starting and ending slashes are for).

Looping through dictionary object

One way is to loop through the keys of the dictionary, which I recommend:

foreach(int key in sp.Keys)
    dynamic value = sp[key];

Another way, is to loop through the dictionary as a sequence of pairs:

foreach(KeyValuePair<int, dynamic> pair in sp)
{
    int key = pair.Key;
    dynamic value = pair.Value;
}

I recommend the first approach, because you can have more control over the order of items retrieved if you decorate the Keys property with proper LINQ statements, e.g., sp.Keys.OrderBy(x => x) helps you retrieve the items in ascending order of the key. Note that Dictionary uses a hash table data structure internally, therefore if you use the second method the order of items is not easily predictable.

Update (01 Dec 2016): replaced vars with actual types to make the answer more clear.

php codeigniter count rows

If you really want to count all rows. You can use this in model function:

$this->db->select('count(*)');
$query = $this->db->get('home');
$cnt = $query->row_array();
return $cnt['count(*)'];

It returns single value, that is row count

The entity name must immediately follow the '&' in the entity reference

Do

<script>//<![CDATA[
    /* script */
//]]></script>

How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved

I have mentioned that the Maven dependency in the pom.xml is wrong. It should be

    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

Getting multiple keys of specified value of a generic Dictionary?

revised: okay to have some kind of find you would need something other than dictionary, since if you think about it dictionary are one way keys. that is, the values might not be unique

that said it looks like you're using c#3.0 so you might not have to resort to looping and could use something like:

var key = (from k in yourDictionary where string.Compare(k.Value, "yourValue", true)  == 0 select k.Key).FirstOrDefault();

MySQL Stored procedure variables from SELECT statements

I am facing a strange behavior.

SELECT INTO and SET Both works for some variables and not for others. Event syntaxes are the same

SET @Invoice_UserId :=  (SELECT UserId FROM invoice WHERE InvoiceId = @Invoice_Id  LIMIT 1); -- Working
                SET @myamount := (SELECT amount FROM invoice WHERE InvoiceId = @Invoice_Id LIMIT 1); - Not working
SELECT  Amount INTO @myamount FROM invoice WHERE InvoiceId = 29  LIMIT 1; - Not working

If I run these queries directly then works, but not working in stored procedure.

Java 8 stream map on entry set

Simply translating the "old for loop way" into streams:

private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {
    int subLength = prefix.length();
    return input.entrySet().stream()
            .collect(Collectors.toMap(
                   entry -> entry.getKey().substring(subLength), 
                   entry -> AttributeType.GetByName(entry.getValue())));
}

Component is part of the declaration of 2 modules

Had same problem. Just make sure to remove every occurrence of module in "declarations" but AppModule.

Worked for me.

Switch role after connecting to database

--create a user that you want to use the database as:

create role neil;

--create the user for the web server to connect as:

create role webgui noinherit login password 's3cr3t';

--let webgui set role to neil:

grant neil to webgui; --this looks backwards but is correct.

webgui is now in the neil group, so webgui can call set role neil . However, webgui did not inherit neil's permissions.

Later, login as webgui:

psql -d some_database -U webgui
(enter s3cr3t as password)

set role neil;

webgui does not need superuser permission for this.

You want to set role at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:

public class SetRoleJdbcInterceptor extends JdbcInterceptor {

    @Override
    public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if(authentication != null) {
            try {

                /* 
                  use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.

                  Or use a whitelist-map approach
                */
                String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());

                Statement statement = pooledConnection.getConnection().createStatement();
                statement.execute("set role \"" + username + "\"");
                statement.close();
            } catch(SQLException exp){
                throw new RuntimeException(exp);
            }
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if("close".equals(method.getName())){
            Statement statement = ((Connection)proxy).createStatement();
            statement.execute("reset role");
            statement.close();
        }

        return super.invoke(proxy, method, args);
    }
}

Regex to check whether a string contains only numbers

If you need just positive integer numbers and don't need leading zeros (e.g. "0001234" or "00"):

var reg = /^(?:[1-9]\d*|\d)$/;

How to query a MS-Access Table from MS-Excel (2010) using VBA

All you need is a ADODB.Connection

Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset   ' Microsoft ActiveX Data Objects Library

Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"

Set rs = cnn.Execute(SQLQuery) ' Retrieve the data

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

How to convert Blob to File in JavaScript

My modern variant:

function blob2file(blobData) {
  const fd = new FormData();
  fd.set('a', blobData);
  return fd.get('a');
}

How to resolve "gpg: command not found" error during RVM installation?

GnuPG (with binary name gpg) is an application used for public key encryption using the OpenPGP protocol, but also verification of signatures (cryptographic signatures, that also can validate the publisher if used correctly). To some extend, you could say it's for OpenPGP what OpenSSL is for X.509 and TLS.

Unlike most Linux distributions (which make heavy use of GnuPG for ensuring untampered software within their package repositories), Mac OS X does not bring GnuPG with the operating system, so you have to install it on your own.

Possible sources are:

  • Package manager Homebrew: brew install gnupg gnupg2
  • Package manager MacPorts: sudo port install gnupg gnupg2
  • Install from GPGTools, which also brings GUI applications and integration in Apple Mail

Path to MSBuild

For Visual Studio 2017 without knowing the exact edition you could use this in a batch script:

FOR /F "tokens=* USEBACKQ" %%F IN (`where /r "%PROGRAMFILES(x86)%\Microsoft Visual 
Studio\2017" msbuild.exe ^| findstr /v /i "amd64"`) DO (SET msbuildpath=%%F)

The findstr command is to ignore certain msbuild executables (in this example the amd64).

How to picture "for" loop in block representation of algorithm

Here's a flow chart that illustrates a for loop:

Flow Chart For Loop

The equivalent C code would be

for(i = 2; i <= 6; i = i + 2) {
    printf("%d\t", i + 1);
}

I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.

Fixed GridView Header with horizontal and vertical scrolling in asp.net

It is possible to apply the specific GridView / Table layout via custom CSS rules (as it was discussed in the <table><tbody> scrollable? thread) to fix GridView's Header. However, this approach will not work in all browsers. The 3-rd ASP.NET GridView controls (such as the ASPxGridView from DevExpress component vendor provide this functionality.

Check also the following CodeProject solutions:

jQuery Toggle Text?

<h2 id="changeText" class="mainText"> Main Text </h2>

(function() {
    var mainText = $('.mainText').text(),
        altText = 'Alt Text';

    $('#changeText').on('click', function(){
        $(this).toggleClass('altText');
        $('.mainText').text(mainText);
        $('.altText').text(altText);
    });

})();

C++ cout hex values?

If you want to print a single hex number, and then revert back to decimal you can use this:

std::cout << std::hex << num << std::dec << std::endl;

How do I set the time zone of MySQL?

If you're using PDO:

$offset="+10:00";
$db->exec("SET time_zone='".$offset."';");

If you're using MySQLi:

$db->MySQLi->query("SET time_zone='".$offset."';");

More about formatting the offset here: https://www.sitepoint.com/synchronize-php-mysql-timezone-configuration/

<DIV> inside link (<a href="">) tag

No, the link assigned to the containing <a> will be assigned to every elements inside it.

And, this is not the proper way. You can make a <a> behave like a <div>.

An Example [Demo]

CSS

a.divlink { 
     display:block;
     width:500px;
     height:500px; 
     float:left;
}

HTML

<div>
    <a class="divlink" href="yourlink.html">
         The text or elements inside the elements
    </a>
    <a class="divlink" href="yourlink2.html">
         Another text or element
    </a>
</div>

How to add an element at the end of an array?

The OP says, for unknown reasons, "I prefer it without an arraylist or list."

If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int or Integer), then you can use one of the NIO Buffer classes like java.nio.IntBuffer. These act a lot like StringBuffer does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.

Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate() a larger one and use put() to dump the old buffer into the new one.

If it's not a primitive, you should probably just use List, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.

How to set the 'selected option' of a select dropdown list with jquery

Try this :

$('select[name^="salesrep"] option[value="Bruce Jones"]').attr("selected","selected");

Just replace option[value="Bruce Jones"] by option[value=result[0]]

And before selecting a new option, you might want to "unselect" the previous :

$('select[name^="salesrep"] option:selected').attr("selected",null);

You may want to read this too : jQuery get specific option tag text

Edit: Using jQuery Mobile, this link may provide a good solution : jquery mobile - set select/option values

Style jQuery autocomplete in a Bootstrap input field

Try this (demo):

.ui-autocomplete {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 1000;
  display: none;
  float: left;
  min-width: 160px;
  padding: 5px 0;
  margin: 2px 0 0;
  list-style: none;
  font-size: 14px;
  text-align: left;
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  background-clip: padding-box;
}

.ui-autocomplete > li > div {
  display: block;
  padding: 3px 20px;
  clear: both;
  font-weight: normal;
  line-height: 1.42857143;
  color: #333333;
  white-space: nowrap;
}

.ui-state-hover,
.ui-state-active,
.ui-state-focus {
  text-decoration: none;
  color: #262626;
  background-color: #f5f5f5;
  cursor: pointer;
}

.ui-helper-hidden-accessible {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
}

How to strip HTML tags from string in JavaScript?

I know this question has an accepted answer, but I feel that it doesn't work in all cases.

For completeness and since I spent too much time on this, here is what we did: we ended up using a function from php.js (which is a pretty nice library for those more familiar with PHP but also doing a little JavaScript every now and then):

http://phpjs.org/functions/strip_tags:535

It seemed to be the only piece of JavaScript code which successfully dealt with all the different kinds of input I stuffed into my application. That is, without breaking it – see my comments about the <script /> tag above.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

onclick="location.href='link.html'" does not load page in Safari

I had the same error. Make sure you don't have any <input>, <select>, etc. name="location".

CSS Child vs Descendant selectors

In theory: Child => an immediate descendant of an ancestor (e.g. Joe and his father)

Descendant => any element that is descended from a particular ancestor (e.g. Joe and his great-great-grand-father)

In practice: try this HTML:

<div class="one">
  <span>Span 1.
    <span>Span 2.</span>
  </span>
</div>

<div class="two">
  <span>Span 1.
    <span>Span 2.</span>
  </span>
</div>

with this CSS:

span { color: red; } 
div.one span { color: blue; } 
div.two > span { color: green; }

http://jsfiddle.net/X343c/1/

Python in Xcode 4+?

Try Editra It's free, has a lot of cool features and plug-ins, it runs on most platforms, and it is written in Python. I use it for all my non-XCode development at home and on Windows/Linux at work.

Return anonymous type results?

You must use ToList() method first to take rows from database and then select items as a class. Try this:

public partial class Dog {
    public string BreedName  { get; set; }}

List<Dog> GetDogsWithBreedNames(){
    var db = new DogDataContext(ConnectString);
    var result = (from d in db.Dogs
                  join b in db.Breeds on d.BreedId equals b.BreedId
                  select new
                  {
                      Name = d.Name,
                      BreedName = b.BreedName
                  }).ToList()
                    .Select(x=> 
                          new Dog{
                              Name = x.Name,
                              BreedName = x.BreedName,
                          }).ToList();
return result;}

So, the trick is first ToList(). It is immediately makes the query and gets the data from database. Second trick is Selecting items and using object initializer to generate new objects with items loaded.

Hope this helps.

How to convert byte[] to InputStream?

Check out java.io.ByteArrayInputStream

How do I connect to a MySQL Database in Python?

Just a modification in above answer. Simply run this command to install mysql for python

sudo yum install MySQL-python
sudo apt-get install MySQL-python

remember! It is case sensitive.

What are the differences between B trees and B+ trees?

A B+tree is a balanced tree in which every path from the root of the tree to a leaf is of the same length, and each nonleaf node of the tree has between [n/2] and [n] children, where n is fixed for a particular tree. It contains index pages and data pages. Binary trees only have two children per parent node, B+ trees can have a variable number of children for each parent node

Short form for Java if statement

Use the ternary operator:

name = ((city.getName() == null) ? "N/A" : city.getName());

I think you have the conditions backwards - if it's null, you want the value to be "N/A".

What if city is null? Your code *hits the bed in that case. I'd add another check:

name = ((city == null) || (city.getName() == null) ? "N/A" : city.getName());

C char* to int conversion

Use atoi() from <stdlib.h>

http://linux.die.net/man/3/atoi

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s)
{
  int sign=1;
  if(*s == '-'){
    sign = -1;
    s++;
  }
  int num=0;
  while(*s){
    num=((*s)-'0')+num*10;
    s++;   
  }
  return num*sign;
}

What is the difference between task and thread?

I usually use Task to interact with Winforms and simple background worker to make it not freezing the UI. here an example when I prefer using Task

private async void buttonDownload_Click(object sender, EventArgs e)
{
    buttonDownload.Enabled = false;
    await Task.Run(() => {
        using (var client = new WebClient())
        {
            client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
        }
    })
    buttonDownload.Enabled = true;
}

VS

private void buttonDownload_Click(object sender, EventArgs e)
{
    buttonDownload.Enabled = false;
    Thread t = new Thread(() =>
    {
        using (var client = new WebClient())
        {
            client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
        }
        this.Invoke((MethodInvoker)delegate()
        {
            buttonDownload.Enabled = true;
        });
    });
    t.IsBackground = true;
    t.Start();
}

the difference is you don't need to use MethodInvoker and shorter code.

Click a button programmatically

The best practice for this sort of situation is to create a method that hold all the logics, and call the method in both events, rather than calling an event from another event;

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Private Sub LogicMethod()

     // All your logic goes here

End Sub

In case you need the properties of the EventArgs (e), you can easily pass it through parameters in your method, that will avoid errors if ever the sender is of different types. But that won't be a problem in your case, as both senders are of type Button.

How can I set the background color of <option> in a <select> element?

Just like normal background-color: #f0f

You just need a way to target it, eg: <option id="myPinkOption">blah</option>

Get device token for push notification

If you are still not getting device token, try putting following code so to register your device for push notification.

It will also work on ios8 or more.

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000

    if ([UIApplication respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         UIRemoteNotificationTypeBadge |
         UIRemoteNotificationTypeAlert |
         UIRemoteNotificationTypeSound];

    }
#else
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     UIRemoteNotificationTypeBadge |
     UIRemoteNotificationTypeAlert |
     UIRemoteNotificationTypeSound];

#endif

How to display list items as columns?

If you take a look at the following example - it uses fixed width columns, and I think this is the behavior requested.

http://www.vanderlee.com/martijn/demo/column/

If the bottom example is the same as the top, you don't need the jquery column plugin.

_x000D_
_x000D_
ul{margin:0; padding:0;}_x000D_
_x000D_
#native {_x000D_
  -webkit-column-width: 150px;_x000D_
  -moz-column-width: 150px;_x000D_
  -o-column-width: 150px;_x000D_
  -ms-column-width: 150px;_x000D_
  column-width: 150px;_x000D_
  _x000D_
  -webkit-column-rule-style: solid;_x000D_
  -moz-column-rule-style: solid;_x000D_
  -o-column-rule-style: solid;_x000D_
  -ms-column-rule-style: solid;_x000D_
  column-rule-style: solid;_x000D_
}
_x000D_
<div id="native">_x000D_
  <ul>_x000D_
    <li>1</li>_x000D_
    <li>2</li>_x000D_
    <li>3</li>_x000D_
    <li>4</li>_x000D_
    <li>5</li>_x000D_
    <li>6</li>_x000D_
    <li>7</li>_x000D_
    <li>8</li>_x000D_
    <li>9</li>_x000D_
    <li>10</li>_x000D_
    <li>11</li>_x000D_
    <li>12</li>_x000D_
    <li>13</li>_x000D_
    <li>14</li>_x000D_
    <li>15</li>_x000D_
    <li>16</li>_x000D_
    <li>17</li>_x000D_
    <li>18</li>_x000D_
    <li>19</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I filter a date of a DateTimeField in Django?

There's a fantastic blogpost that covers this here: Comparing Dates and Datetimes in the Django ORM

The best solution posted for Django>1.7,<1.9 is to register a transform:

from django.db import models

class MySQLDatetimeDate(models.Transform):
    """
    This implements a custom SQL lookup when using `__date` with datetimes.
    To enable filtering on datetimes that fall on a given date, import
    this transform and register it with the DateTimeField.
    """
    lookup_name = 'date'

    def as_sql(self, compiler, connection):
        lhs, params = compiler.compile(self.lhs)
        return 'DATE({})'.format(lhs), params

    @property
    def output_field(self):
        return models.DateField()

Then you can use it in your filters like this:

Foo.objects.filter(created_on__date=date)

EDIT

This solution is definitely back end dependent. From the article:

Of course, this implementation relies on your particular flavor of SQL having a DATE() function. MySQL does. So does SQLite. On the other hand, I haven’t worked with PostgreSQL personally, but some googling leads me to believe that it does not have a DATE() function. So an implementation this simple seems like it will necessarily be somewhat backend-dependent.

How to find lines containing a string in linux

Write the queue job information in long format to text file

qstat -f > queue.txt

Grep job names

grep 'Job_Name' queue.txt

How do I update Homebrew?

Alternatively you could update brew by installing it again. (Think I did this as El Capitan changed something)

Note: this is a heavy handed approach that will remove all applications installed via brew!

Try to install brew a fresh and it will tell how to uninstall.

At original time of writing to uninstall:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Edit: As of 2020 to uninstall:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

If if doesn't work then use "!Important"

@media (min-width: 1200px) { .container { width: 970px !important; } }

How to extract a substring using regex

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile(".*'([^']*)'.*");
        String mydata = "some string with 'the data i want' inside";

        Matcher matcher = pattern.matcher(mydata);
        if(matcher.matches()) {
            System.out.println(matcher.group(1));
        }

    }
}

Reshape an array in NumPy

numpy has a great tool for this task ("numpy.reshape") link to reshape documentation

a = [[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]

`numpy.reshape(a,(3,3))`

you can also use the "-1" trick

`a = a.reshape(-1,3)`

the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3

so yes.. this would also work: a = a.reshape(3,-1)

and this: a = a.reshape(-1,2) would do nothing

and this: a = a.reshape(-1,9) would change the shape to (2,9)

Are there any naming convention guidelines for REST APIs?

I would say that it's preferable to use as few special characters as possible in REST URLs. One of the benefits of REST is that it makes the "interface" for a service easy to read. Camel case or Pascal case is probably good for the resource names (Users or users). I don't think there are really any hard standards around REST.

Also, I think Gandalf is right, it's usually cleaner in REST to not use query string parameters, but instead create paths that define which resources you want to deal with.

http://api.example.com/HelloWorld/Users/12345/Order/3/etc

Writing a string to a cell in excel

I think you may be getting tripped up on the sheet protection. I streamlined your code a little and am explicitly setting references to the workbook and worksheet objects. In your example, you explicitly refer to the workbook and sheet when you're setting the TxtRng object, but not when you unprotect the sheet.

Try this:

Sub varchanger()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim TxtRng  As Range

    Set wb = ActiveWorkbook
    Set ws = wb.Sheets("Sheet1")
    'or ws.Unprotect Password:="yourpass"
    ws.Unprotect

    Set TxtRng = ws.Range("A1")
    TxtRng.Value = "SubTotal"
    'http://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu
    ' or ws.Protect Password:="yourpass"
    ws.Protect

End Sub

If I run the sub with ws.Unprotect commented out, I get a run-time error 1004. (Assuming I've protected the sheet and have the range locked.) Uncommenting the line allows the code to run fine.

NOTES:

  1. I'm re-setting sheet protection after writing to the range. I'm assuming you want to do this if you had the sheet protected in the first place. If you are re-setting protection later after further processing, you'll need to remove that line.
  2. I removed the error handler. The Excel error message gives you a lot more detail than Err.number. You can put it back in once you get your code working and display whatever you want. Obviously you can use Err.Description as well.
  3. The Cells(1, 1) notation can cause a huge amount of grief. Be careful using it. Range("A1") is a lot easier for humans to parse and tends to prevent forehead-slapping mistakes.

A non well formed numeric value encountered

This error occurs when you perform calculations with variables that use letters combined with numbers (alphanumeric), for example 24kb, 886ab ...

I had the error in the following function

function get_config_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);       
    switch($last) {
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $this->fix_integer_overflow($val);
}

The application uploads images but it didn't work, it showed the following warning:

enter image description here

Solution: The intval() function extracts the integer value of a variable with alphanumeric data and creates a new variable with the same value but converted to an integer with the intval() function. Here is the code:

function get_config_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    $intval = intval(trim($val));
    switch($last) {
        case 'g':
            $intval *= 1024;
        case 'm':
            $intval *= 1024;
        case 'k':
            $intval *= 1024;
    }
    return $this->fix_integer_overflow($intval);
}

How to join entries in a set into one string?

The join is called on the string:

print ", ".join(set_3)

Trim specific character from a string

to keep this question up to date:

here is an approach i'd choose over the regex function using the ES6 spread operator.

function trimByChar(string, character) {
  const first = [...string].findIndex(char => char !== character);
  const last = [...string].reverse().findIndex(char => char !== character);
  return string.substring(first, string.length - last);
}

Improved version after @fabian 's comment (can handle strings containing the same character only)

_x000D_
_x000D_
function trimByChar1(string, character) {
  const arr = Array.from(string);
  const first = arr.findIndex(char => char !== character);
  const last = arr.reverse().findIndex(char => char !== character);
  return (first === -1 && last === -1) ? '' : string.substring(first, string.length - last);
}
_x000D_
_x000D_
_x000D_

How can I see an the output of my C programs using Dev-C++?

The use of line system("PAUSE") will fix that problem and also include the pre processor directory #include<stdlib.h>.

How add "or" in switch statements?

The example for switch statement shows that you can't stack non-empty cases, but should use gotos:

// statements_switch.cs
using System;
class SwitchTest 
{
   public static void Main()  
   {
      Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large"); 
      Console.Write("Please enter your selection: "); 
      string s = Console.ReadLine(); 
      int n = int.Parse(s);
      int cost = 0;
      switch(n)       
      {         
         case 1:   
            cost += 25;
            break;                  
         case 2:            
            cost += 25;
            goto case 1;           
         case 3:            
            cost += 50;
            goto case 1;             
         default:            
            Console.WriteLine("Invalid selection. Please select 1, 2, or3.");            
            break;      
       }
       if (cost != 0)
          Console.WriteLine("Please insert {0} cents.", cost);
       Console.WriteLine("Thank you for your business.");
   }
}

How to add constraints programmatically using Swift

It helps me to learn visually, so this is a supplemental answer.

Boilerplate code

override func viewDidLoad() {
    super.viewDidLoad()

    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add constraints code here
    // ...
}

Each of the following examples are independent of the others.

Pin left edge

myView.leading = leadingMargin + 20

enter image description here

Method 1: Anchor Style

let margins = view.layoutMarginsGuide
myView.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 20).isActive = true
  • In addition to leadingAnchor, there is also trailingAnchor, topAnchor, and bottomAnchor.

Method 2: NSLayoutConstraint Style

NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.leadingMargin, multiplier: 1.0, constant: 20.0).isActive = true
  • In addition to .leading there is also .trailing, .top, and .bottom.
  • In addition to .leadingMargin there is also .trailingMargin, .topMargin, and .bottomMargin.

Set Width and Height

width = 200
height = 100

enter image description here

Method 1: Anchor Style

myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true

Method 2: NSLayoutConstraint Style

NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true

Center in container

myView.centerX = centerX
myView.centerY = centerY

enter image description here

Method 1: Anchor Style

myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

Method 2: NSLayoutConstraint Style

NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true

Notes

  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
  • The examples above showed just the one or two constraints that were being focused on. However, in order to properly place myView in my test project I needed to have four constraints.

Further Reading

How to change color of Toolbar back button in Android?

Just use the MaterialToolbar and override the default colors:

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
        android:theme="@style/MyThemeOverlay_Toolbar"
        ..>

with:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- color used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/...</item>
  </style>

enter image description here

If you are using the androidx.appcompat.widget.Toolbar or the MaterialToolbar with the default style (Widget.MaterialComponents.Toolbar) you can use:

<androidx.appcompat.widget.Toolbar
    android:theme="@style/MyThemeOverlay_Toolbar2"

with:

  <style name="MyThemeOverlay_Toolbar2" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is used by title -->
    <item name="android:textColorPrimary">@color/white</item>

    <!-- This attributes is used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/secondaryColor</item>
  </style>

How to draw a checkmark / tick using CSS?

li:before {
    content: '';
    height: 5px;
    background-color: green;
    position: relative;
    display: block;
    top: 50%;
    left: 50%;
    width: 9px;
    margin-left: -15px;
    -ms-transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    transform: rotate(45deg);
}
li:after {
    content: '';
    height: 5px;
    background-color: green;
    position: relative;
    display: block;
    top: 50%;
    left: 50%;
    width: 20px;
    margin-left: -11px;
    margin-top: -6px;
    -ms-transform: rotate(-45deg);
    -webkit-transform: rotate(-45deg);
    transform: rotate(-45deg);
}

Commenting multiple lines in DOS batch file

You can use a goto to skip over code.

goto comment
...skip this...
:comment

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

OK so I think i know the issue you're having.

Basically, because Composer can't see the migration files you are creating, you are having to run the dump-autoload command which won't download anything new, but looks for all of the classes it needs to include again. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php), and this is why your migration is working after you run that command.

How to fix it (possibly) You need to add some extra information to your composer.json file.

"autoload": {
    "classmap": [
        "PATH TO YOUR MIGRATIONS FOLDER"
    ],
}

You need to add the path to your migrations folder to the classmap array. Then run the following three commands...

php artisan clear-compiled 
composer dump-autoload
php artisan optimize

This will clear the current compiled files, update the classes it needs and then write them back out so you don't have to do it again.

Ideally, you execute composer dump-autoload -o , for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticable).

Hope you can manage to get this sorted, as its very annoying indeed :(

jQuery - how to write 'if not equal to' (opposite of ==)

if ("one" !== 1 )

would evaluate as true, the string "one" is not equal to the number 1

How do I check if a Key is pressed on C++

There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.

Solution for linux and other posix compliant systems:

Here, for Morgan Mattews's code provide kbhit() functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.

Solution for windows:

For windows, Microsoft offers _kbhit()

sql - insert into multiple tables in one query

I had the same problem. I solve it with a for loop.

Example:

If I want to write in 2 identical tables, using a loop

for x = 0 to 1

 if x = 0 then TableToWrite = "Table1"
 if x = 1 then TableToWrite = "Table2"
  Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT

either

ArrTable = ("Table1", "Table2")

for xArrTable = 0 to Ubound(ArrTable)
 Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT

If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.

finding first day of the month in python

You can use dateutil.rrule:

In [1]: from dateutil.rrule import *

In [2]: rrule(DAILY, bymonthday=1)[0].date()
Out[2]: datetime.date(2018, 10, 1)

In [3]: rrule(DAILY, bymonthday=1)[1].date()
Out[3]: datetime.date(2018, 11, 1)

Is it possible to have multiple statements in a python lambda expression?

After analyzing all solutions offered above I came up with this combination, which seem most clear ad useful for me:

func = lambda *args, **kwargs: "return value" if [
    print("function 1..."),
    print("function n"),
    ["for loop" for x in range(10)]
] else None

Isn't it beautiful? Remember that there have to be something in list, so it has True value. And another thing is that list can be replaced with set, to look more like C style code, but in this case you cannot place lists inside as they are not hashabe

MySQL: Large VARCHAR vs. TEXT?

Short answer: No practical, performance, or storage, difference.

Long answer:

There is essentially no difference (in MySQL) between VARCHAR(3000) (or any other large limit) and TEXT. The former will truncate at 3000 characters; the latter will truncate at 65535 bytes. (I make a distinction between bytes and characters because a character can take multiple bytes.)

For smaller limits in VARCHAR, there are some advantages over TEXT.

  • "smaller" means 191, 255, 512, 767, or 3072, etc, depending on version, context, and CHARACTER SET.
  • INDEXes are limited in how big a column can be indexed. (767 or 3072 bytes; this is version and settings dependent)
  • Intermediate tables created by complex SELECTs are handled in two different ways -- MEMORY (faster) or MyISAM (slower). When 'large' columns are involved, the slower technique is automatically picked. (Significant changes coming in version 8.0; so this bullet item is subject to change.)
  • Related to the previous item, all TEXT datatypes (as opposed to VARCHAR) jump straight to MyISAM. That is, TINYTEXT is automatically worse for generated temp tables than the equivalent VARCHAR. (But this takes the discussion in a third direction!)
  • VARBINARY is like VARCHAR; BLOB is like TEXT.

Rebuttal to other answers

The original question asked one thing (which datatype to use); the accepted answer answered something else (off-record storage). That answer is now out of date.

When this thread was started and answered, there were only two "row formats" in InnoDB. Soon afterwards, two more formats (DYNAMIC and COMPRESSED) were introduced.

The storage location for TEXT and VARCHAR() is based on size, not on name of datatype. For an updated discussion of on/off-record storage of large text/blob columns, see this .

How to disable Excel's automatic cell reference change after copy/paste?

Click on the cell you want to copy. In the formula bar, highlight the formula.

Press Ctrl C.

Press escape (to take you out of actively editing that formula).

Choose new cell. Ctrl V.

Ignore invalid self-signed ssl certificate in node.js with https.request?

You can also create a request instance with default options:

require('request').defaults({ rejectUnauthorized: false })

rejected master -> master (non-fast-forward)

If git pull does not help, then probably you have pushed your changes (A) and after that had used git commit --amend to add some more changes (B). Therefore, git thinks that you can lose the history - it interprets B as a different commit despite it contains all changes from A.

             B
            /
        ---X---A

If nobody changes the repo after A, then you can do git push --force.

However, if there are changes after A from other person:

             B
            /
        ---X---A---C

then you must rebase that persons changes from A to B (C->D).

             B---D
            /
        ---X---A---C

or fix the problem manually. I didn't think how to do that yet.

ConcurrentModificationException for ArrayList

You can't remove from list if you're browsing it with "for each" loop. You can use Iterator. Replace:

for (DrugStrength aDrugStrength : aDrugStrengthList) {
    if (!aDrugStrength.isValidDrugDescription()) {
        aDrugStrengthList.remove(aDrugStrength);
    }
}

With:

for (Iterator<DrugStrength> it = aDrugStrengthList.iterator(); it.hasNext(); ) {
    DrugStrength aDrugStrength = it.next();
    if (!aDrugStrength.isValidDrugDescription()) {
        it.remove();
    }
}

find if an integer exists in a list of integers

bool vExist = false;
int vSelectValue = 1;

List<int> vList = new List<int>();
vList.Add(1);
vList.Add(2);

IEnumerable vRes = (from n in vListwhere n == vSelectValue);
if (vRes.Count > 0) {
    vExist = true;
}

Check if a variable exists in a list in Bash

This is almost your original proposal but almost a 1-liner. Not that complicated as other valid answers, and not so depending on bash versions (can work with old bashes).

OK=0 ; MP_FLAVOURS="vanilla lemon hazelnut straciatella"
for FLAV in $MP_FLAVOURS ; do [ $FLAV == $FLAVOR ] && { OK=1 ; break; } ; done
[ $OK -eq 0 ] && { echo "$FLAVOR not a valid value ($MP_FLAVOURS)" ; exit 1 ; }

I guess my proposal can still be improved, both in length and style.

I can’t find the Android keytool

I never installed Java, but when you install Android Studio it has its own version within the Android directory. Here is where mine is located. Your path may be similar. After that you can either put the keytool into your path, or just run it from that directory.

C:\Program Files\Android\Android Studio\jre\bin

HTML/CSS: Making two floating divs the same height

You should use flexbox to achieve this. It's not supported in IE8 and IE9 and only with the -ms prefix in IE10, but all other browsers support it. For vendor prefixes, you should also use autoprefixer.

.parent {
    display: flex;
    flex-wrap: wrap; // allow wrapping items
}

.child {
    flex-grow: 1;
    flex-basis: 50%; // 50% for two in a row, 33% three in a row etc.
}

What's the difference between align-content and align-items?

according to what I understood from here:

when you use align-item or justify-item, you are adjusting "the content inside a grid item along the column axis or row axis respectively.

But: if you use align-content or justify-content, you are setting the position a grid along the column axis or the row axis. it occurs when you have a grid in a bigger container and width or height are inflexible (using px).

Redirecting Output from within Batch file

This may fail in the case of "toxic" characters in the input. Considering an input like thisIsAnIn^^^^put is a good way how to get understand what is going on. Sure there is a rule that an input string MUST be inside double quoted marks but I have a feeling that this rule is a valid rule only if the meaning of the input is a location on a NTFS partition (maybe it is a rule for URLs I am not sure). But it is not a rule for an arbitrary input string of course (it is "a good practice" but you cannot count with it).

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Safely limiting Ansible playbooks to a single machine?

I have a wrapper script called provision forces you to choose the target, so I don't have to handle it elsewhere.

For those that are curious, I use ENV vars for options that my vagrantfile uses (adding the corresponding ansible arg for cloud systems) and let the rest of the ansible args pass through. Where I am creating and provisioning more than 10 servers at a time I include an auto retry on failed servers (as long as progress is being made - I found when creating 100 or so servers at a time often a few would fail the first time around).

echo 'Usage: [VAR=value] bin/provision [options] dev|all|TARGET|vagrant'
echo '  bootstrap - Bootstrap servers ssh port and initial security provisioning'
echo '  dev - Provision localhost for development and control'
echo '  TARGET - specify specific host or group of hosts'
echo '  all - provision all servers'
echo '  vagrant - Provision local vagrant machine (environment vars only)'
echo
echo 'Environment VARS'
echo '  BOOTSTRAP - use cloud providers default user settings if set'
echo '  TAGS - if TAGS env variable is set, then only tasks with these tags are run'
echo '  SKIP_TAGS - only run plays and tasks whose tags do not match these values'
echo '  START_AT_TASK - start the playbook at the task matching this name'
echo
ansible-playbook --help | sed -e '1d
    s#=/etc/ansible/hosts# set by bin/provision argument#
    /-k/s/$/ (use for fresh systems)/
    /--tags/s/$/ (use TAGS var instead)/
    /--skip-tags/s/$/ (use SKIP_TAGS var instead)/
    /--start-at-task/s/$/ (use START_AT_TASK var instead)/
'

How to change root logging level programmatically for logback

I think you can use MDC to change logging level programmatically. The code below is an example to change logging level on current thread. This approach does not create dependency to logback implementation (SLF4J API contains MDC).

<configuration>
  <turboFilter class="ch.qos.logback.classic.turbo.DynamicThresholdFilter">
    <Key>LOG_LEVEL</Key>
    <DefaultThreshold>DEBUG</DefaultThreshold>
    <MDCValueLevelPair>
      <value>TRACE</value>
      <level>TRACE</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>DEBUG</value>
      <level>DEBUG</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>INFO</value>
      <level>INFO</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>WARN</value>
      <level>WARN</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>ERROR</value>
      <level>ERROR</level>
    </MDCValueLevelPair>
  </turboFilter>
  ......
</configuration>
MDC.put("LOG_LEVEL", "INFO");

Hide element by class in pure Javascript

Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });

Forked @http://jsfiddle.net/QVJXD/

How to convert Map keys to array?

Array.from(myMap.keys()) does not work in google application scripts.

Trying to use it results in the error TypeError: Cannot find function from in object function Array() { [native code for Array.Array, arity=1] }.

To get a list of keys in GAS do this:

var keysList = Object.keys(myMap);

How to get Linux console window width in Python

I searched around and found a solution for windows at :

http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/

and a solution for linux here.

So here is a version which works both on linux, os x and windows/cygwin :

""" getTerminalSize()
 - get width and height of console
 - works on linux,os x,windows,cygwin(windows)
"""

__all__=['getTerminalSize']


def getTerminalSize():
   import platform
   current_os = platform.system()
   tuple_xy=None
   if current_os == 'Windows':
       tuple_xy = _getTerminalSize_windows()
       if tuple_xy is None:
          tuple_xy = _getTerminalSize_tput()
          # needed for window's python in cygwin's xterm!
   if current_os == 'Linux' or current_os == 'Darwin' or  current_os.startswith('CYGWIN'):
       tuple_xy = _getTerminalSize_linux()
   if tuple_xy is None:
       print "default"
       tuple_xy = (80, 25)      # default value
   return tuple_xy

def _getTerminalSize_windows():
    res=None
    try:
        from ctypes import windll, create_string_buffer

        # stdin handle is -10
        # stdout handle is -11
        # stderr handle is -12

        h = windll.kernel32.GetStdHandle(-12)
        csbi = create_string_buffer(22)
        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
    except:
        return None
    if res:
        import struct
        (bufx, bufy, curx, cury, wattr,
         left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
        sizex = right - left + 1
        sizey = bottom - top + 1
        return sizex, sizey
    else:
        return None

def _getTerminalSize_tput():
    # get terminal width
    # src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window
    try:
       import subprocess
       proc=subprocess.Popen(["tput", "cols"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       cols=int(output[0])
       proc=subprocess.Popen(["tput", "lines"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       rows=int(output[0])
       return (cols,rows)
    except:
       return None


def _getTerminalSize_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234'))
        except:
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (env['LINES'], env['COLUMNS'])
        except:
            return None
    return int(cr[1]), int(cr[0])

if __name__ == "__main__":
    sizex,sizey=getTerminalSize()
    print  'width =',sizex,'height =',sizey

The source was not found, but some or all event logs could not be searched

Didnt work for me.

I created a new key and string value and managed to get it working

Key= HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\<Your app name>\
String EventMessageFile value=C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll

In Java, can you modify a List while iterating through it?

Use Java 8's removeIf(),

To remove safely,

letters.removeIf(x -> !x.equals("A"));

One line if/else condition in linux shell scripting

It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with "&&".

maxline='cat journald.conf | grep "#SystemMaxUse="'; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2 && mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually."; fi

Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.

Convert list to array in Java

This is works. Kind of.

public static Object[] toArray(List<?> a) {
    Object[] arr = new Object[a.size()];
    for (int i = 0; i < a.size(); i++)
        arr[i] = a.get(i);
    return arr;
}

Then the main method.

public static void main(String[] args) {
    List<String> list = new ArrayList<String>() {{
        add("hello");
        add("world");
    }};
    Object[] arr = toArray(list);
    System.out.println(arr[0]);
}

How to protect Excel workbook using VBA?

To lock whole workbook from opening, Thisworkbook.password option can be used in VBA.

If you want to Protect Worksheets, then you have to first Lock the cells with option Thisworkbook.sheets.cells.locked = True and then use the option Thisworkbook.sheets.protect password:="pwd".

Primarily search for these keywords: Thisworkbook.password or Thisworkbook.Sheets.Cells.Locked