Programs & Examples On #Geturl

How to send post request with x-www-form-urlencoded body

string urlParameters = "param1=value1&param2=value2";
string _endPointName = "your url post api";

var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);

httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";

System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                                                  (se, cert, chain, sslerror) =>
                                                  {
                                                      return true;
                                                  };


using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(urlParameters);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                }

How to get request URL in Spring Boot RestController

If you don't want any dependency on Spring's HATEOAS or javax.* namespace, use ServletUriComponentsBuilder to get URI of current request:

import org.springframework.web.util.UriComponentsBuilder;

ServletUriComponentsBuilder.fromCurrentRequest();
ServletUriComponentsBuilder.fromCurrentRequestUri();

Reading Excel file using node.js

You can also use this node module called js-xlsx

1) Install module
npm install xlsx

2) Import module + code snippet

var XLSX = require('xlsx')
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;
var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
console.log(xlData);

Base64: java.lang.IllegalArgumentException: Illegal character

The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.

For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.

static String getBase64EncodedCipherText(String cipherText) {
    byte[] cText = cipherText.getBytes();
    // return an ISO-8859-1 encoded String
    return Base64.getEncoder().encodeToString(cText);
}

static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
    return new String((Base64.getDecoder().decode(encodedCipherText)));
}

public static void main(String[] args) {
    try {
        String cText = getRawCipherText(null, "Hello World of Encryption...");

        System.out.println("Text to encrypt/encode: Hello World of Encryption...");
        // This output is a simple sanity check to display that the text
        // has indeed been converted to a cipher text which 
        // is unreadable by all but the most intelligent of programmers.
        // It is absolutely inhuman of me to do such a thing, but I am a
        // rebel and cannot be trusted in any way.  Please look away.
        System.out.println("RAW CIPHER TEXT: " + cText);
        cText = getBase64EncodedCipherText(cText);
        System.out.println("BASE64 ENCODED: " + cText);
        // There he goes again!!
        System.out.println("BASE64 DECODED:  " + getBase64DecodedCipherText(cText));
        System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

The output looks like:

Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;?C?l??<8??U???X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED:  q$;?C?l??<8??U???X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

The immediate cause of the problem is that the JDBC driver has attempted to read from a network Socket that has been closed by "the other end".

This could be due to a few things:

  • If the remote server has been configured (e.g. in the "SQLNET.ora" file) to not accept connections from your IP.

  • If the JDBC url is incorrect, you could be attempting to connect to something that isn't a database.

  • If there are too many open connections to the database service, it could refuse new connections.

Given the symptoms, I think the "too many connections" scenario is the most likely. That suggests that your application is leaking connections; i.e. creating connections and then failing to (always) close them.

How do I read a response from Python Requests?

If the response is in json you could do something like (python3):

import json
import requests as reqs

# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')

# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)

for i in response_dict:
    print("key: ", i, "val: ", response_dict[i])

To see everything in the response you can use .__dict__:

print(response.__dict__)

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Based on the hint and link provided in Simone Giannis answer, this is my hack to fix this.

I am testing on uri.getAuthority(), because UNC path will report an Authority. This is a bug - so I rely on the existence of a bug, which is evil, but it apears as if this will stay forever (since Java 7 solves the problem in java.nio.Paths).

Note: In my context I will receive absolute paths. I have tested this on Windows and OS X.

(Still looking for a better way to do it)

package com.christianfries.test;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

public class UNCPathTest {

    public static void main(String[] args) throws MalformedURLException, URISyntaxException {
        UNCPathTest upt = new UNCPathTest();

        upt.testURL("file://server/dir/file.txt");  // Windows UNC Path

        upt.testURL("file:///Z:/dir/file.txt");     // Windows drive letter path

        upt.testURL("file:///dir/file.txt");        // Unix (absolute) path
    }

    private void testURL(String urlString) throws MalformedURLException, URISyntaxException {
        URL url = new URL(urlString);
        System.out.println("URL is: " + url.toString());

        URI uri = url.toURI();
        System.out.println("URI is: " + uri.toString());

        if(uri.getAuthority() != null && uri.getAuthority().length() > 0) {
            // Hack for UNC Path
            uri = (new URL("file://" + urlString.substring("file:".length()))).toURI();
        }

        File file = new File(uri);
        System.out.println("File is: " + file.toString());

        String parent = file.getParent();
        System.out.println("Parent is: " + parent);

        System.out.println("____________________________________________________________");
    }

}

How to use youtube-dl from a python program?

It's not difficult and actually documented:

import youtube_dl

ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s.%(ext)s'})

with ydl:
    result = ydl.extract_info(
        'http://www.youtube.com/watch?v=BaW_jenozKc',
        download=False # We just want to extract the info
    )

if 'entries' in result:
    # Can be a playlist or a list of videos
    video = result['entries'][0]
else:
    # Just a video
    video = result

print(video)
video_url = video['url']
print(video_url)

Using for loop inside of a JSP

Do this

    <% for(int i = 0; i < allFestivals.size(); i+=1) { %>
        <tr>      
            <td><%=allFestivals.get(i).getFestivalName()%></td>
        </tr>
    <% } %>

Better way is to use c:foreach see link jstl for each

javax.naming.NoInitialContextException - Java

If working on EJB client library:

You need to mention the argument for getting the initial context.

InitialContext ctx = new InitialContext();

If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:

Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");

InitialContext ctx = new InitialContext(props);

URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.

The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.

Android: Pass data(extras) to a fragment

I prefer Serializable = no boilerplate code. For passing data to other Fragments or Activities the speed difference to a Parcelable does not matter.

I would also always provide a helper method for a Fragment or Activity, this way you always know, what data has to be passed. Here an example for your ListMusicFragment:

private static final String EXTRA_MUSIC_LIST = "music_list";

public static ListMusicFragment createInstance(List<Music> music) {
    ListMusicFragment fragment = new ListMusicFragment();
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_MUSIC_LIST, music);
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public View onCreateView(...) { 
    ...
    Bundle bundle = intent.getArguments();
    List<Music> musicList = (List<Music>)bundle.getSerializable(EXTRA_MUSIC_LIST);
    ...
}

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

This answer might be late but I would like to mention few things when your Activity dependent on AsyncTask. That would help you in prevent crashes and memory management. As already mentioned in above answers go with interface, we also say them callbacks. They will work as an informer, but never ever send strong reference of Activity or interface always use weak reference in those cases.

Please refer to below screenshot to findout how that can cause issues.

enter image description here

As you can see if we started AsyncTask with a strong reference then there is no guarantee that our Activity/Fragment will be alive till we get data, so it would be better to use WeakReference in those cases and that will also help in memory management as we will never hold the strong reference of our Activity then it will be eligible for garbage collection after its distortion.

Check below code snippet to find out how to use awesome WeakReference -

MyTaskInformer.java Interface which will work as an informer.

public interface MyTaskInformer {

    void onTaskDone(String output);

}

MySmallAsyncTask.java AsyncTask to do long running task, which will use WeakReference.

public class MySmallAsyncTask extends AsyncTask<String, Void, String> {

    // ***** Hold weak reference *****
    private WeakReference<MyTaskInformer> mCallBack;

    public MySmallAsyncTask(MyTaskInformer callback) {
        this.mCallBack = new WeakReference<>(callback);
    }

    @Override
    protected String doInBackground(String... params) {

        // Here do whatever your task is like reading/writing file
        // or read data from your server or any other heavy task

        // Let us suppose here you get response, just return it
        final String output = "Any out, mine is just demo output";

        // Return it from here to post execute
        return output;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        // Here you can't guarantee that Activity/Fragment is alive who started this AsyncTask

        // Make sure your caller is active

        final MyTaskInformer callBack = mCallBack.get();

        if(callBack != null) {
            callBack.onTaskDone(s);
        }
    }
}

MainActivity.java This class is used to start my AsyncTask implement interface on this class and override this mandatory method.

public class MainActivity extends Activity implements MyTaskInformer {

    private TextView mMyTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mMyTextView = (TextView) findViewById(R.id.tv_text_view);

        // Start your AsyncTask and pass reference of MyTaskInformer in constructor
        new MySmallAsyncTask(this).execute();
    }

    @Override
    public void onTaskDone(String output) {

        // Here you will receive output only if your Activity is alive.
        // no need to add checks like if(!isFinishing())

        mMyTextView.setText(output);
    }
}

How do I convert a org.w3c.dom.Document object to a String?

use some thing like

import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

//method to convert Document to String
public String getStringFromDocument(Document doc)
{
    try
    {
       DOMSource domSource = new DOMSource(doc);
       StringWriter writer = new StringWriter();
       StreamResult result = new StreamResult(writer);
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.transform(domSource, result);
       return writer.toString();
    }
    catch(TransformerException ex)
    {
       ex.printStackTrace();
       return null;
    }
} 

Add legend to ggplot2 line plot

I really like the solution proposed by @Brian Diggs. However, in my case, I create the line plots in a loop rather than giving them explicitly because I do not know apriori how many plots I will have. When I tried to adapt the @Brian's code I faced some problems with handling the colors correctly. Turned out I needed to modify the aesthetic functions. In case someone has the same problem, here is the code that worked for me.

I used the same data frame as @Brian:

data <- structure(list(month = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 
                                       1317798000, 1317884400, 1317970800, 1318057200, 
                                       1318143600, 1318230000, 1318316400, 1318402800, 
                                       1318489200, 1318575600, 1318662000, 1318748400, 
                                       1318834800, 1318921200, 1319007600, 1319094000), 
                                     class = c("POSIXct", "POSIXt"), tzone = ""),
                   TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71, 
                               25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18, 
                               25.19, 24.19, 27.65, 23.92), 
                   TempMed = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52,
                                 19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 
                                 20.45, 19.42, 19.97, 19.61), 
                   TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82, 
                               14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 16.95, 
                               17.55, 15.21, 14.22, 16.42)), 
              .Names = c("month", "TempMax", "TempMed", "TempMin"), 
              row.names = c(NA, 20L), class = "data.frame")  

In my case, I generate my.cols and my.names dynamically, but I don't want to make things unnecessarily complicated so I give them explicitly here. These three lines make the ordering of the legend and assigning colors easier.

my.cols <- heat.colors(3, alpha=1)
my.names <- c("TempMin", "TempMed", "TempMax")
names(my.cols) <- my.names

And here is the plot:

p <-  ggplot(data, aes(x = month))

for (i in 1:3){
  p <- p + geom_line(aes_(y = as.name(names(data[i+1])), colour = 
colnames(data[i+1])))#as.character(my.names[i])))
}
p + scale_colour_manual("", 
                        breaks = as.character(my.names),
                        values = my.cols)
p

enter image description here

Determine if JavaScript value is an "integer"?

Use jQuery's IsNumeric method.

http://api.jquery.com/jQuery.isNumeric/

if ($.isNumeric(id)) {
   //it's numeric
}

CORRECTION: that would not ensure an integer. This would:

if ( (id+"").match(/^\d+$/) ) {
   //it's all digits
}

That, of course, doesn't use jQuery, but I assume jQuery isn't actually mandatory as long as the solution works

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

Windows must be created on the same stack (aka microtask) as the user-initiated event, e.g. a click callback--so they can't be created later, asynchronously.

However, you can create a window without a URL and you can then change that window's URL once you do know it, even asynchronously!

window.onclick = () => {
  // You MUST create the window on the same event
  // tick/stack as the user-initiated event (e.g. click callback)
  const googleWindow = window.open();

  // Do your async work
  fakeAjax(response => {
    // Change the URL of the window you created once you
    // know what the full URL is!
    googleWindow.location.replace(`https://google.com?q=${response}`);
  });
};

function fakeAjax(callback) {
  setTimeout(() => {
    callback('example');
  }, 1000);
}

Modern browsers will open the window with a blank page (often called about:blank), and assuming your async task to get the URL is fairly quick, the resulting UX is mostly fine. If you instead want to render a loading message (or anything) into the window while the user waits, you can use Data URIs.

window.open('data:text/html,<h1>Loading...<%2Fh1>');

Set content of iframe

If you want to set an html content containg script tag to iframe, you have access to the iframe you created with:

$(iframeElement).contentWindow.document

so you can set innerHTML of any element in this.

But, for script tag, you should create and append an script tag, like this:

https://stackoverflow.com/a/13122011/4718434

Regex to extract URLs from href attribute in HTML with Python

The best answer is...

Don't use a regex

The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.

Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?

Parse the HTML instead

For many tasks, using Beautiful Soup will be far faster and easier to use:

>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser')           # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']

If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser that does exactly what you want:

from html.parser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self, output_list=None):
        HTMLParser.__init__(self)
        if output_list is None:
            self.output_list = []
        else:
            self.output_list = output_list
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            self.output_list.append(dict(attrs).get('href'))

Test:

>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']

You could even create a new method that accepts a string, calls feed, and returns output_list. This is a vastly more powerful and extensible way than regular expressions to extract information from html.

Proxy setting for R

On Mac OS, I found the best solution here. Quoting the author, two simple steps are:

1) Open Terminal and do the following:

export http_proxy=http://staff-proxy.ul.ie:8080
export HTTP_PROXY=http://staff-proxy.ul.ie:8080

2) Run R and do the following:

Sys.setenv(http_proxy="http://staff-proxy.ul.ie:8080")

double-check this with:

Sys.getenv("http_proxy")

I am behind university proxy, and this solution worked perfectly. The major issue is to export the items in Terminal before running R, both in upper- and lower-case.

Send HTTP GET request with header

Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.

/**
 * HTTP request types
 */
public static final int POST_TYPE   = 1;
public static final int GET_TYPE    = 2;
public static final int PUT_TYPE    = 3;
public static final int DELETE_TYPE = 4;

/**
 * HTTP request header constants
 */
public static final String CONTENT_TYPE         = "Content-Type";
public static final String ACCEPT_ENCODING      = "Accept-Encoding";
public static final String CONTENT_ENCODING     = "Content-Encoding";
public static final String ENCODING_GZIP        = "gzip";
public static final String MIME_FORM_ENCODED    = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN      = "text/plain";

private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
    final Map<String, String> headers, final Map<String, String> params, final int requestType) 
            throws IOException {

    DefaultHttpClient client = HTTPClientFactory.newClient();

    client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
    }

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }
    if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
        sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
    }
    // request gzip encoding for response
    sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);

    if (sendHeaders.size() > 0) {
        client.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context) throws HttpException,
                IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    //.... code omitted ....//

}

What does "javax.naming.NoInitialContextException" mean?

Just read the docs:

This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.

This exception can be thrown during any interaction with the InitialContext, not only when the InitialContext is constructed. For example, the implementation of the initial context might lazily retrieve the context only when actual methods are invoked on it. The application should not have any dependency on when the existence of an initial context is determined.

But this is explained much better in the docs for InitialContext

Getting HTTP headers with Node.js

I'm not sure how you might do this with Node, but the general idea would be to send an HTTP HEAD request to the URL you're interested in.

HEAD

Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.


Something like this, based it on this question:

var cli = require('cli');
var http = require('http');
var url = require('url');

cli.parse();

cli.main(function(args, opts) {
        this.debug(args[0]);

        var siteUrl = url.parse(args[0]);
        var site = http.createClient(80, siteUrl.host);
        console.log(siteUrl);

        var request = site.request('HEAD', siteUrl.pathname, {'host' : siteUrl.host})
        request.end();

        request.on('response', function(response) {
                response.setEncoding('utf8');
                console.log('STATUS: ' + response.statusCode);
                response.on('data', function(chunk) {
                        console.log("DATA: " + chunk);
                });
        });
});

Set Value of Input Using Javascript Function

The following works in MVC5:

document.getElementById('theID').value = 'new value';

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

Change to older Visual Studio. Weird solution that worked for me. I was using Visual studio 2017, after changing to Visual Studio 2015 ,everything worked.

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

great code; little hint: if you sometimes have to bypass more data and not only the viewmodel ..

 if (model is ViewDataDictionary)
 {
     controller.ViewData = model as ViewDataDictionary;
 } else {
     controller.ViewData.Model = model;
 }

Setting a WebRequest's body data

The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:

var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic   N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

The code above depends on the nuget package RestSharp, which you can easily install.

Restful API service

Lets say I want to start the service on an event - onItemClicked() of a button. The Receiver mechanism would not work in that case because :-
a) I passed the Receiver to the service (as in Intent extra) from onItemClicked()
b) Activity moves to the background. In onPause() I set the receiver reference within the ResultReceiver to null to avoid leaking the Activity.
c) Activity gets destroyed.
d) Activity gets created again. However at this point the Service will not be able to make a callback to the Activity as that receiver reference is lost.
The mechanism of a limited broadcast or a PendingIntent seems to be more usefull in such scenarios- refer to Notify activity from service

Given a URL to a text file, what is the simplest way to read the contents of the text file?

I do think requests is the best option. Also note the possibility of setting encoding manually.

import requests
response = requests.get("http://www.gutenberg.org/files/10/10-0.txt")
# response.encoding = "utf-8"
hehe = response.text

How to add link to flash banner

If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.

on (release) {
  getURL("http://someurl/");
}

To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.

I think it would go too far to explain into depth with pictures how to go about in stackoverflow.

Detecting Back Button/Hash Change in URL

Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.

Ignore .classpath and .project from Git

Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore

Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore

using setTimeout on promise chain

In node.js you can also do the following:

const { promisify } = require('util')
const delay = promisify(setTimeout)

delay(1000).then(() => console.log('hello'))

Explanation of "ClassCastException" in Java

If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException For example

class Animal{
   int age;
   String type;

   public Animal(int age, String type){
      this.age = age;
      this.type = type;
   }
}
public class MainCls{
   public static void main(String[] args){
       Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
       Arrays.sort(arr);
   }
}

Above main method will throw below runtime class cast exception

Exception in thread "main" java.lang.ClassCastException: com.default.Animal cannot be cast to java.lang.Comparable

How to create a file on Android Internal Storage?

You should use ContextWrapper like this:

ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);

As always, refer to documentation, ContextWrapper has a lot to offer.

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

In order to update your project to the latest version of java available in your environment, follow these steps:

  1. Open your pom.xml file
  2. Switch your view to Effective POM tab
  3. Open Find Dialog (ctrl + F) to search for maven-compiler-plugin
  4. Copy the the following lines

_x000D_
_x000D_
<plugin>_x000D_
 <artifactId>maven-compiler-plugin</artifactId>_x000D_
 <version>3.1</version>
_x000D_
_x000D_
_x000D_

  1. Click on pom.xml tab to open your project pom configuration
  2. Inside your <build> ... </build> configuration section, paste the configuration copied and modify it as...

_x000D_
_x000D_
        <plugins>_x000D_
     <plugin>_x000D_
      <artifactId>maven-compiler-plugin</artifactId>_x000D_
      <version>3.1</version>_x000D_
    _x000D_
      <configuration>_x000D_
       <source>1.8</source>_x000D_
       <target>1.8</target>_x000D_
      </configuration>_x000D_
     </plugin>_x000D_
    </plugins>
_x000D_
_x000D_
_x000D_

  1. save your configuration
  2. Right Click in your project Click on [Maven -> Update Project] and Click on OK in the displayed update dialog box.

Done!

memory error in python

Using python 64 bit solves lot of problems.

Update a column in MySQL

You have to use UPDATE instead of INSERT:

For Example:

UPDATE table1 SET col_a='k1', col_b='foo' WHERE key_col='1';
UPDATE table1 SET col_a='k2', col_b='bar' WHERE key_col='2';

slideToggle JQuery right to left

Please try this code

$(this).animate({'width': 'toggle'});

How to read a .xlsx file using the pandas Library in iPython?

Instead of using a sheet name, in case you don't know or can't open the excel file to check in ubuntu (in my case, Python 3.6.7, ubuntu 18.04), I use the parameter index_col (index_col=0 for the first sheet)

import pandas as pd
file_name = 'some_data_file.xlsx' 
df = pd.read_excel(file_name, index_col=0)
print(df.head()) # print the first 5 rows

Volatile vs. Interlocked vs. lock

"volatile" does not replace Interlocked.Increment! It just makes sure that the variable is not cached, but used directly.

Incrementing a variable requires actually three operations:

  1. read
  2. increment
  3. write

Interlocked.Increment performs all three parts as a single atomic operation.

Jquery to get the id of selected value from dropdown

If you are trying to get the id, then please update your code like

  html += '<option id = "' + n.id + "' value="' + i + '">' + n.names + '</option>';

To retrieve id,

$('option:selected').attr("id")

To retrieve Value

$('option:selected').val()

in Javascript

var e = document.getElementById("jobSel");
var job = e.options[e.selectedIndex].value;

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)

modify list of host names for your system:

C:\Windows\System32\drivers\etc\hosts

Make sure that you have the following entry:

127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem

(you may need to change modify permission to modify this file)

This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

Angular2 *ngIf check object array length in template

Maybe slight overkill but created library ngx-if-empty-or-has-items it checks if an object, set, map or array is not empty. Maybe it will help somebody. It has the same functionality as ngIf (then, else and 'as' syntax is supported).

arrayOrObjWithData = ['1'] || {id: 1}

<h1 *ngxIfNotEmpty="arrayOrObjWithData">
  You will see it
</h1>

 or 
 // store the result of async pipe in variable
 <h1 *ngxIfNotEmpty="arrayOrObjWithData$ | async as obj">
  {{obj.id}}
</h1>

 or

noData = [] || {}
<h1 *ngxIfHasItems="noData">
   You will NOT see it
</h1>

How to add an element to Array and shift indexes?

You must make a new array, use System.arraycopy to copy the prefix and suffix, and set that one slot to the new value.

SQL Server Management Studio – tips for improving the TSQL coding process

Being aware of the two(?) different types of windows available in SQL Server Management Studio.

If you right-click a table and select Open it will use an editable grid that you can modify the cells in. If you right-click the database and select New Query it will create a slightly different type of window that you can't modify the grid in but it gives you a few other nice features, such as allowing different code snippets and letting you execute them separately by selection.

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Using regular expressions to do mass replace in Notepad++ and Vim

Everything before the A, B, C, etc.

That seems so simple I must be misinterpreting you. It's just

:%s/<.*>//

Changing the browser zoom level

I could't find a way to change the actual browser zoom level, but you can get pretty close with CSS transform: scale(). Here is my solution based on JavaScript and jQuery:

<!-- Trigger -->
<ul id="zoom_triggers">
    <li><a id="zoom_in">zoom in</a></li>
    <li><a id="zoom_out">zoom out</a></li>
    <li><a id="zoom_reset">reset zoom</a></li>
</ul>

<script>
    jQuery(document).ready(function($)
    {
        // Set initial zoom level
        var zoom_level=100;

        // Click events
        $('#zoom_in').click(function() { zoom_page(10, $(this)) });
        $('#zoom_out').click(function() { zoom_page(-10, $(this)) });
        $('#zoom_reset').click(function() { zoom_page(0, $(this)) });

        // Zoom function
        function zoom_page(step, trigger)
        {
            // Zoom just to steps in or out
            if(zoom_level>=120 && step>0 || zoom_level<=80 && step<0) return;

            // Set / reset zoom
            if(step==0) zoom_level=100;
            else zoom_level=zoom_level+step;

            // Set page zoom via CSS
            $('body').css({
                transform: 'scale('+(zoom_level/100)+')', // set zoom
                transformOrigin: '50% 0' // set transform scale base
            });

            // Adjust page to zoom width
            if(zoom_level>100) $('body').css({ width: (zoom_level*1.2)+'%' });
            else $('body').css({ width: '100%' });

            // Activate / deaktivate trigger (use CSS to make them look different)
            if(zoom_level>=120 || zoom_level<=80) trigger.addClass('disabled');
            else trigger.parents('ul').find('.disabled').removeClass('disabled');
            if(zoom_level!=100) $('#zoom_reset').removeClass('disabled');
            else $('#zoom_reset').addClass('disabled');
        }
    });
</script>

Twitter Bootstrap 3, vertically center content

Option 1 is to use display:table-cell. You need to unfloat the Bootstrap col-* using float:none..

.center {
    display:table-cell;
    vertical-align:middle;
    float:none;
}

http://bootply.com/94394


Option 2 is display:flex to vertical align the row with flexbox:

.row.center {
   display: flex;
   align-items: center;
}

http://www.bootply.com/7rAuLpMCwr


Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456

Finding duplicate values in MySQL

If you want to remove duplicate use DISTINCT

Otherwise use this query:

SELECT users.*,COUNT(user_ID) as user FROM users GROUP BY user_name HAVING user > 1;

Undo git update-index --assume-unchanged <file>

Nothing here that is not covered. But would like to add my 2 cents. At times, I run a build and it changes lot of files and then I want to work on something, so this command really helps me a lot.

git update-index --assume-unchanged `git status | grep modified | sed 's|modified:||g'| xargs`

Hope someone else find it useful as well.

Setting environment variables on OS X

It's simple:

Edit ~/.profile and put your variables as follow

$ vim ~/.profile

In file put:

MY_ENV_VAR=value

  1. Save ( :wq )

  2. Restart the terminal (Quit and open it again)

  3. Make sure that`s all be fine:

$ echo $MY_ENV_VAR

$ value


Read/Write String from/to a File in Android

I'm a bit of a beginner and struggled getting this to work today.

Below is the class that I ended up with. It works but I was wondering how imperfect my solution is. Anyway, I was hoping some of you more experienced folk might be willing to have a look at my IO class and give me some tips. Cheers!

public class HighScore {
    File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
    File file = new File(data, "highscore.txt");
    private int highScore = 0;

    public int readHighScore() {
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            try {
                highScore = Integer.parseInt(br.readLine());
                br.close();
            } catch (NumberFormatException | IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            try {
                file.createNewFile();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            e.printStackTrace();
        }
        return highScore;
    }

    public void writeHighScore(int highestScore) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write(String.valueOf(highestScore));
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I filter date range in DataTables?

Using other posters code with some tweaks:

<table id="MainContent_tbFilterAsp" style="margin-top:-15px;">
        <tbody>
            <tr>
                <td style="vertical-align:initial;"><label for="datepicker_from" id="MainContent_datepicker_from_lbl" style="margin-top:7px;">From date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_from" type="text" id="datepicker_from" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;
                </td>
                
                <td style="vertical-align:initial"><label for="datepicker_to" id="MainContent_datepicker_to_lbl" style="margin-top:7px;">To date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_to" type="text" id="datepicker_to" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;                        
                </td>
                
                <td style="vertical-align:initial"><a onclick="$('#datepicker_from').val(''); $('#datepicker_to').val(''); return false;" id="datepicker_clear_lnk" style="margin-top:7px;">Clear</a></td>
            </tr>
        </tbody>
    </table>
    
    <script>
        $(document).ready(function() {
            $(function() {
                var oTable = $('#tbAD').DataTable({
                "oLanguage": {
                    "sSearch": "Filter Data"
                },
                "iDisplayLength": -1,
                "sPaginationType": "full_numbers",
                "pageLength": 50, 
                });

                $("#datepicker_from").datepicker();
                $("#datepicker_to").datepicker();

                $('#datepicker_from').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_to').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_clear_lnk').click(function (e) {
                    oTable.draw();
                });
            });   

            $.fn.dataTable.ext.search.push(
                function (settings, data, dataIndex) {
                var min = $('#datepicker_from').datepicker("getDate") == null ? null : $('#datepicker_from').datepicker("getDate").setHours(0,0,0,0);
                var max = $('#datepicker_to').datepicker("getDate") == null ? null : $('#datepicker_to').datepicker("getDate").setHours(0,0,0,0);
                var startDate = new Date(data[9]).setHours(0,0,0,0);
                if (min == null && max == null) { return true; }
                if (min == null && startDate <= max) { return true; }
                if (max == null && startDate >= min) { return true; }
                if (startDate <= max && startDate >= min) { return true; }                    
                return false;
                }
            );
        });
</script>

Failed to authenticate on SMTP server error using gmail

Change the .env file as follow

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

And the go to the gmail security section ->Allow Less secure app access

Then run

php artisan config:clear

Refresh the site

The object 'DF__*' is dependent on column '*' - Changing int to double

Try this:

Remove the constraint DF_Movies_Rating__48CFD27E before changing your field type.

The constraint is typically created automatically by the DBMS (SQL Server).

To see the constraint associated with the table, expand the table attributes in Object explorer, followed by the category Constraints as shown below:

Tree of your table

You must remove the constraint before changing the field type.

Paste MS Excel data to SQL Server

The simplest way is to create a computed column in XLS that would generate the syntax of the insert statement. Then copy these insert into a text file and then execute on the SQL. The other alternatives are to buy database connectivity add-on's for Excel and write VBA code to accomplish the same.

How do I check if a variable is of a certain type (compare two types) in C?

From linux/typecheck.h:

/*
 * Check at compile time that something is of a particular type.
 * Always evaluates to 1 so you may use it easily in comparisons.
 */
#define typecheck(type,x) \
({  type __dummy; \
    typeof(x) __dummy2; \
    (void)(&__dummy == &__dummy2); \
    1; \
})

Here you can find explanation which statements from standard and which GNU extensions above code uses.

(Maybe a bit not in scope of the question, since question is not about failure on type mismatch, but anyway, leaving it here).

LF will be replaced by CRLF in git - What is that and is it important?

If you want, you can deactivate this feature in your git core config using

git config core.autocrlf false

But it would be better to just get rid of the warnings using

git config core.autocrlf true

How to pass optional arguments to a method in C++?

With commas separating them, just like parameters without default values.

int func( int x = 0, int y = 0 );

func(); // doesn't pass optional parameters, defaults are used, x = 0 and y = 0

func(1, 2); // provides optional parameters, x = 1 and y = 2

Position DIV relative to another DIV?

You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo

#one
{
    background-color: #EEE;
    margin: 62px 258px;
    padding: 5px;
    width: 200px;
    position: relative;   
}

#two
{
    background-color: #F00;
    display: inline-block;
    height: 30px;
    position: absolute;
    width: 100px;
    top:10px;
}?

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

You can use lodash or Undescore.js range:

var range = require('lodash/range')
range(10)
// -> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Alternatively, if you only need a consecutive range of integers you can do something like:

Array.apply(undefined, { length: 10 }).map(Number.call, Number)
// -> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

In ES6 range can be implemented with generators:

function* range(start=0, end=null, step=1) {
  if (end == null) {
    end = start;
    start = 0;
  }

  for (let i=start; i < end; i+=step) {
    yield i;
  }
}

This implementation saves memory when iterating large sequences, because it doesn't have to materialize all values into an array:

for (let i of range(1, oneZillion)) {
  console.log(i);
}

How to pip install a package with min and max version range?

you can also use:

pip install package==0.5.*

which is more consistent and easy to read.

Check table exist or not before create it in Oracle

Well there are lot of answeres already provided and lot are making sense too.

Some mentioned it is just warning and some giving a temp way to disable warnings. All that will work but add risk when number of transactions in your DB is high.

I came across similar situation today and here is very simple query I came up with...

declare
begin
  execute immediate '
    create table "TBL" ("ID" number not null)';
  exception when others then
    if SQLCODE = -955 then null; else raise; end if;
end;
/

955 is failure code.

This is simple, if exception come while running query it will be suppressed. and you can use same for SQL or Oracle.

Upgrade python in a virtualenv

I moved my home directory from one mac to another (Mountain Lion to Yosemite) and didn't realize about the broken virtualenv until I lost hold of the old laptop. I had the virtualenv point to Python 2.7 installed by brew and since Yosemite came with Python 2.7, I wanted to update my virtualenv to the system python. When I ran virtualenv on top of the existing directory, I was getting OSError: [Errno 17] File exists: '/Users/hdara/bin/python2.7/lib/python2.7/config' error. By trial and error, I worked around this issue by removing a few links and fixing up a few more manually. This is what I finally did (similar to what @Rockalite did, but simpler):

cd <virtualenv-root>
rm lib/python2.7/config
rm lib/python2.7/lib-dynload
rm include/python2.7
rm .Python
cd lib/python2.7
gfind . -type l -xtype l | while read f; do ln -s -f /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/${f#./} $f; done

After this, I was able to just run virtualenv on top of the existing directory.

Detecting EOF in C

while(scanf("%d %d",a,b)!=EOF)
{

//do .....
}

HashSet vs LinkedHashSet

If you take a look at the constructors called from the LinkedHashSet class you will see that internally it's a LinkedHashMap that is used for backing purpose.

Checking if a variable exists in javascript

A variable is declared if accessing the variable name will not produce a ReferenceError. The expression typeof variableName !== 'undefined' will be false in only one of two cases:

  • the variable is not declared (i.e., there is no var variableName in scope), or
  • the variable is declared and its value is undefined (i.e., the variable's value is not defined)

Otherwise, the comparison evaluates to true.

If you really want to test if a variable is declared or not, you'll need to catch any ReferenceError produced by attempts to reference it:

var barIsDeclared = true; 
try{ bar; }
catch(e) {
    if(e.name == "ReferenceError") {
        barIsDeclared = false;
    }
}

If you merely want to test if a declared variable's value is neither undefined nor null, you can simply test for it:

if (variableName !== undefined && variableName !== null) { ... }

Or equivalently, with a non-strict equality check against null:

if (variableName != null) { ... }

Both your second example and your right-hand expression in the && operation tests if the value is "falsey", i.e., if it coerces to false in a boolean context. Such values include null, false, 0, and the empty string, not all of which you may want to discard.

fatal: The current branch master has no upstream branch

First use git pull origin your_branch_name Then use git push origin your_branch_name

PHP $_POST not working?

I had something similar this evening which was driving me batty. Submitting a form was giving me the values in $_REQUEST but not in $_POST.

Eventually I noticed that there were actually two requests going through on the network tab in firebug; first a POST with a 301 response, then a GET with a 200 response.

Hunting about the interwebs it sounded like most people thought this was to do with mod_rewrite causing the POST request to redirect and thus change to a GET.

In my case it wasn't mod_rewrite to blame, it was something far simpler... my URL for the POST also contained a GET query string which was starting without a trailing slash on the URL. It was this causing apache to redirect.

Spot the difference...

Bad: http://blah.de.blah/my/path?key=value&otherkey=othervalue
Good: http://blah.de.blah/my/path/?key=value&otherkey=othervalue

The bottom one doesn't cause a redirect and gives me $_POST!

Detect a finger swipe through JavaScript on the iPhone and Android

I have found @givanse brilliant answer to be the most reliable and compatible across multiple mobile browsers for registering swipe actions.

However, there's a change in his code required to make it work in modern day mobile browsers that are using jQuery.

event.toucheswon't exist if jQuery is used and results in undefined and should be replaced by event.originalEvent.touches. Without jQuery, event.touches should work fine.

So the solution becomes,

document.addEventListener('touchstart', handleTouchStart, false);        
document.addEventListener('touchmove', handleTouchMove, false);

var xDown = null;                                                        
var yDown = null;                                                        

function handleTouchStart(evt) {                                         
    xDown = evt.originalEvent.touches[0].clientX;                                      
    yDown = evt.originalEvent.touches[0].clientY;                                      
};                                                

function handleTouchMove(evt) {
    if ( ! xDown || ! yDown ) {
        return;
    }

    var xUp = evt.originalEvent.touches[0].clientX;                                    
    var yUp = evt.originalEvent.touches[0].clientY;

    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
        if ( xDiff > 0 ) {
            /* left swipe */ 
        } else {
            /* right swipe */
        }                       
    } else {
        if ( yDiff > 0 ) {
            /* up swipe */ 
        } else { 
            /* down swipe */
        }                                                                 
    }
    /* reset values */
    xDown = null;
    yDown = null;                                             
};

Tested on:

  • Android: Chrome, UC Browser
  • iOS: Safari, Chrome, UC Browser

Spark: Add column to dataframe conditionally

Try withColumn with the function when as follows:

val sqlContext = new SQLContext(sc)
import sqlContext.implicits._ // for `toDF` and $""
import org.apache.spark.sql.functions._ // for `when`

val df = sc.parallelize(Seq((4, "blah", 2), (2, "", 3), (56, "foo", 3), (100, null, 5)))
    .toDF("A", "B", "C")

val newDf = df.withColumn("D", when($"B".isNull or $"B" === "", 0).otherwise(1))

newDf.show() shows

+---+----+---+---+
|  A|   B|  C|  D|
+---+----+---+---+
|  4|blah|  2|  1|
|  2|    |  3|  0|
| 56| foo|  3|  1|
|100|null|  5|  0|
+---+----+---+---+

I added the (100, null, 5) row for testing the isNull case.

I tried this code with Spark 1.6.0 but as commented in the code of when, it works on the versions after 1.4.0.

How do I make a matrix from a list of vectors in R?

One option is to use do.call():

 > do.call(rbind, a)
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

Download and save PDF file with Python requests module

You should use response.content in this case:

with open('/tmp/metadata.pdf', 'wb') as f:
    f.write(response.content)

From the document:

You can also access the response body as bytes, for non-text requests:

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

So that means: response.text return the output as a string object, use it when you're downloading a text file. Such as HTML file, etc.

And response.content return the output as bytes object, use it when you're downloading a binary file. Such as PDF file, audio file, image, etc.


You can also use response.raw instead. However, use it when the file which you're about to download is large. Below is a basic example which you can also find in the document:

import requests

url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
r = requests.get(url, stream=True)

with open('/tmp/metadata.pdf', 'wb') as fd:
    for chunk in r.iter_content(chunk_size):
        fd.write(chunk)

chunk_size is the chunk size which you want to use. If you set it as 2000, then requests will download that file the first 2000 bytes, write them into the file, and do this again, again and again, unless it finished.

So this can save your RAM. But I'd prefer use response.content instead in this case since your file is small. As you can see use response.raw is complex.


Relates:

How to replace space with comma using sed?

If you want the output on terminal then,

$sed 's/ /,/g' filename.txt

But if you want to edit the file itself i.e. if you want to replace space with the comma in the file then,

$sed -i 's/ /,/g' filename.txt

How do you do a deep copy of an object in .NET?

The MSDN documentation seems to hint that Clone should perform a deep copy, but it is never explicitly stated:

The ICloneable interface contains one member, Clone, which is intended to support cloning beyond that supplied by MemberWiseClone… The MemberwiseClone method creates a shallow copy…

You can find my post helpful.

http://pragmaticcoding.com/index.php/cloning-objects-in-c/

Process to convert simple Python script into Windows executable

1) Get py2exe from here, according to your Python version.

2) Make a file called "setup.py" in the same folder as the script you want to convert, having the following code:

from distutils.core import setup
import py2exe
setup(console=['myscript.py']) #change 'myscript' to your script

3) Go to command prompt, navigate to that folder, and type:

python setup.py py2exe

4) It will generate a "dist" folder in the same folder as the script. This folder contains the .exe file.

Can I restore a single table from a full mysql mysqldump file?

A simple solution would be to simply create a dump of just the table you wish to restore separately. You can use the mysqldump command to do so with the following syntax:

mysqldump -u [user] -p[password] [database] [table] > [output_file_name].sql

Then import it as normal, and it will only import the dumped table.

Get connection status on Socket.io client

Track the state of the connection yourself. With a boolean. Set it to false at declaration. Use the various events (connect, disconnect, reconnect, etc.) to reassign the current boolean value. Note: Using undocumented API features (e.g., socket.connected), is not a good idea; the feature could get removed in a subsequent version without the removal being mentioned.

Function that creates a timestamp in c#

I believe you can create a unix style datestamp accurate to a second using the following

//Find unix timestamp (seconds since 01/01/1970)
long ticks = DateTime.UtcNow.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks;
ticks /= 10000000; //Convert windows ticks to seconds
timestamp = ticks.ToString();

Adjusting the denominator allows you to choose your level of precision

How to convert SQL Query result to PANDAS Data Structure?

MySQL Connector

For those that works with the mysql connector you can use this code as a start. (Thanks to @Daniel Velkov)

Used refs:


import pandas as pd
import mysql.connector

# Setup MySQL connection
db = mysql.connector.connect(
    host="<IP>",              # your host, usually localhost
    user="<USER>",            # your username
    password="<PASS>",        # your password
    database="<DATABASE>"     # name of the data base
)   

# You must create a Cursor object. It will let you execute all the queries you need
cur = db.cursor()

# Use all the SQL you like
cur.execute("SELECT * FROM <TABLE>")

# Put it all to a data frame
sql_data = pd.DataFrame(cur.fetchall())
sql_data.columns = cur.column_names

# Close the session
db.close()

# Show the data
print(sql_data.head())

what does numpy ndarray shape do?

yourarray.shape or np.shape() or np.ma.shape() returns the shape of your ndarray as a tuple; And you can get the (number of) dimensions of your array using yourarray.ndim or np.ndim(). (i.e. it gives the n of the ndarray since all arrays in NumPy are just n-dimensional arrays (shortly called as ndarrays))

For a 1D array, the shape would be (n,) where n is the number of elements in your array.

For a 2D array, the shape would be (n,m) where n is the number of rows and m is the number of columns in your array.

Please note that in 1D case, the shape would simply be (n, ) instead of what you said as either (1, n) or (n, 1) for row and column vectors respectively.

This is to follow the convention that:

For 1D array, return a shape tuple with only 1 element   (i.e. (n,))
For 2D array, return a shape tuple with only 2 elements (i.e. (n,m))
For 3D array, return a shape tuple with only 3 elements (i.e. (n,m,k))
For 4D array, return a shape tuple with only 4 elements (i.e. (n,m,k,j))

and so on.

Also, please see the example below to see how np.shape() or np.ma.shape() behaves with 1D arrays and scalars:

# sample array
In [10]: u = np.arange(10)

# get its shape
In [11]: np.shape(u)    # u.shape
Out[11]: (10,)

# get array dimension using `np.ndim`
In [12]: np.ndim(u)
Out[12]: 1

In [13]: np.shape(np.mean(u))
Out[13]: ()       # empty tuple (to indicate that a scalar is a 0D array).

# check using `numpy.ndim`
In [14]: np.ndim(np.mean(u))
Out[14]: 0

P.S.: So, the shape tuple is consistent with our understanding of dimensions of space, at least mathematically.

What precisely does 'Run as administrator' do?

UPDATE

"Run as Aministrator" is just a command, enabling the program to continue some operations that require the Administrator privileges, without displaying the UAC alerts.

Even if your user is a member of administrators group, some applications like yours need the Administrator privileges to continue running, because the application is considered not safe, if it is doing some special operation, like editing a system file or something else. This is the reason why Windows needs the Administrator privilege to execute the application and it notifies you with a UAC alert. Not all applications need an Amnistrator account to run, and some applications, like yours, need the Administrator privileges.

If you execute the application with 'run as administrator' command, you are notifying the system that your application is safe and doing something that requires the administrator privileges, with your confirm.

If you want to avoid this, just disable the UAC on Control Panel.

If you want to go further, read the question Difference between "Run as Administrator" and Windows 7 Administrators Group on Microsoft forum or this SuperUser question.

Display back button on action bar

ActionBar actionBar=getActionBar();

actionBar.setDisplayHomeAsUpEnabled(true);

@Override
public boolean onOptionsItemSelected(MenuItem item) { 
        switch (item.getItemId()) {
        case android.R.id.home: 
            onBackPressed();
            return true;
        }

    return super.onOptionsItemSelected(item);
}

If my interface must return Task what is the best way to have a no-operation implementation?

Recently encountered this and kept getting warnings/errors about the method being void.

We're in the business of placating the compiler and this clears it up:

    public async Task MyVoidAsyncMethod()
    {
        await Task.CompletedTask;
    }

This brings together the best of all the advice here so far. No return statement is necessary unless you're actually doing something in the method.

How do I check if a given string is a legal/valid file name under Windows?

I got this idea from someone. - don't know who. Let the OS do the heavy lifting.

public bool IsPathFileNameGood(string fname)
{
    bool rc = Constants.Fail;
    try
    {
        this._stream = new StreamWriter(fname, true);
        rc = Constants.Pass;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Problem opening file");
        rc = Constants.Fail;
    }
    return rc;
}

How to pass the -D System properties while testing on Eclipse?

You can add command line arguments to your run configuration. Just edit the run configuration and add -Dmyprop=value (or whatever) to the VM Arguments Box.

Java reading a file into an ArrayList?

Here's a solution that has worked pretty well for me:

List<String> lines = Arrays.asList(
    new Scanner(new File(file)).useDelimiter("\\Z").next().split("\\r?\\n")
);

If you don't want empty lines, you can also do:

List<String> lines = Arrays.asList(
    new Scanner(new File(file)).useDelimiter("\\Z").next().split("[\\r\\n]+")
);

Android layout replacing a view with another view on run time

You could replace any view at any time.

int optionId = someExpression ? R.layout.option1 : R.layout.option2;

View C = findViewById(R.id.C);
ViewGroup parent = (ViewGroup) C.getParent();
int index = parent.indexOfChild(C);
parent.removeView(C);
C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

If you don't want to replace already existing View, but choose between option1/option2 at initialization time, then you could do this easier: set android:id for parent layout and then:

ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
View C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

You will have to set "index" to proper value depending on views structure. You could also use a ViewStub: add your C view as ViewStub and then:

ViewStub C = (ViewStub) findViewById(R.id.C);
C.setLayoutResource(optionId);
C.inflate();

That way you won't have to worry about above "index" value if you will want to restructure your XML layout.

Set environment variables from file of key/value pairs

Here is another sed solution, which does not run eval or require ruby:

source <(sed -E -n 's/[^#]+/export &/ p' ~/.env)

This adds export, keeping comments on lines starting with a comment.

.env contents

A=1
#B=2

sample run

$ sed -E -n 's/[^#]+/export &/ p' ~/.env
export A=1
#export B=2

I found this especially useful when constructing such a file for loading in a systemd unit file, with EnvironmentFile.

How to send data in request body with a GET when using jQuery $.ajax()

we all know generally that for sending the data according to the http standards we generally use POST request. But if you really want to use Get for sending the data in your scenario I would suggest you to use the query-string or query-parameters.

1.GET use of Query string as. {{url}}admin/recordings/some_id

here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.

2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true

here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.

3.GET Sending arrays {{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]

and you can access those array values at server side like this

let osValues = JSON.parse(req.query.os);
        if(osValues.length > 0)
        {
            for (let i=0; i<osValues.length; i++)
            {
                console.log(osValues[i])
                //do whatever you want to do here
            }
        }

Best way to retrieve variable values from a text file?

A simple way of reading variables from a text file using the standard library:

# Get vars from conf file
var = {}
with open("myvars.conf") as conf:
        for line in conf:
                if ":" in line:
                        name, value = line.split(":")
                        var[name] = str(value).rstrip()
globals().update(var)

CSS Div Background Image Fixed Height 100% Width

But the thing is that the .chapter class is not dynamic you're declaring a height:1200px

so it's better to use background:cover and set with media queries specific height's for popular resolutions.

How to remove all numbers from string?

Try with regex \d:

$words = preg_replace('/\d/', '', $words );

\d is an equivalent for [0-9] which is an equivalent for numbers range from 0 to 9.

How to stop mysqld

There is an alternative way of just killing the daemon process by calling

kill -TERM PID

where PID is the value stored in the file mysqld.pid or the mysqld process id which can be obtained by issuing the command ps -a | grep mysqld.

Carriage Return\Line feed in Java

bw.newLine(); cannot ensure compatibility with all systems.

If you are sure it is going to be opened in windows, you can format it to windows newline.

If you are already using native unix commands, try unix2dos and convert teh already generated file to windows format and then send the mail.

If you are not using unix commands and prefer to do it in java, use ``bw.write("\r\n")` and if it does not complicate your program, have a method that finds out the operating system and writes the appropriate newline.

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

Django - Reverse for '' not found. '' is not a valid view function or pattern name

I was receiving the same error when not specifying the app name before pattern name. In my case:

app-name : Blog

pattern-name : post-delete

reverse_lazy('Blog:post-delete') worked.

Forcing a postback

A postback is triggered after a form submission, so it's related to a client action... take a look here for an explanation: ASP.NET - Is it possible to trigger a postback from server code?

and here for a solution: http://forums.asp.net/t/928411.aspx/1

Best Python IDE on Linux

Probably the new PyCharm from the makers of IntelliJ and ReSharper.

How to get everything after a certain character?

$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"

In a single statement it would be.

echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"

How to export data to an excel file using PHPExcel

Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel. Good Luck.

require('../phpexcel/PHPExcel.php');

require('../phpexcel/PHPExcel/Writer/Excel5.php');

$filename = 'userReport'; //your file name

    $objPHPExcel = new PHPExcel();
    /*********************Add column headings START**********************/
    $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', 'username')
                ->setCellValue('B1', 'city_name');

    /*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
  $user_name = $value['username'];
  $c_code = $value['city_name'];
  $num_row++;
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$num_row, $user_name )
                ->setCellValue('B'.$num_row, $c_code );
}

    /*********************Autoresize column width depending upon contents START**********************/
    foreach(range('A','B') as $columnID) {
        $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
    }
    $objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);



//Make heading font bold

        /*********************Add color to heading START**********************/
        $objPHPExcel->getActiveSheet()
                    ->getStyle('A1:B1')
                    ->getFill()
                    ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
                    ->getStartColor()
                    ->setARGB('99ff99');

        $objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;Filename=$filename.xls");
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

Reactive forms - disabled attribute

Initialization (component) using:

public selector = new FormControl({value: '', disabled: true});

Then instead of using (template):

<ngx-select
[multiple]="true"
[disabled]="errorSelector"
[(ngModel)]="ngxval_selector"
[items]="items"
</ngx-select>

Just remove the attribute disabled:

<ngx-select
[multiple]="true"
[(ngModel)]="ngxval_selector"
[items]="items"
</ngx-select>

And when you have items to show, launch (in component): this.selector.enable();

Convert string to nullable type (int, double, etc...)

Let's add one more similar solution to the stack. This one also parses enums, and it looks nice. Very safe.

/// <summary>
    /// <para>More convenient than using T.TryParse(string, out T). 
    /// Works with primitive types, structs, and enums.
    /// Tries to parse the string to an instance of the type specified.
    /// If the input cannot be parsed, null will be returned.
    /// </para>
    /// <para>
    /// If the value of the caller is null, null will be returned.
    /// So if you have "string s = null;" and then you try "s.ToNullable...",
    /// null will be returned. No null exception will be thrown. 
    /// </para>
    /// <author>Contributed by Taylor Love (Pangamma)</author>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="p_self"></param>
    /// <returns></returns>
    public static T? ToNullable<T>(this string p_self) where T : struct
    {
        if (!string.IsNullOrEmpty(p_self))
        {
            var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
            if (converter.IsValid(p_self)) return (T)converter.ConvertFromString(p_self);
            if (typeof(T).IsEnum) { T t; if (Enum.TryParse<T>(p_self, out t)) return t;}
        }

        return null;
    }

https://github.com/Pangamma/PangammaUtilities-CSharp/blob/master/PangammaUtilities/Extensions/ToNullableStringExtension.cs

JavaScript listener, "keypress" doesn't detect backspace?

The keypress event might be different across browsers.

I created a Jsfiddle to compare keyboard events (using the JQuery shortcuts) on Chrome and Firefox. Depending on the browser you're using a keypress event will be triggered or not -- backspace will trigger keydown/keypress/keyup on Firefox but only keydown/keyup on Chrome.

Single keyclick events triggered

on Chrome

  • keydown/keypress/keyup when browser registers a keyboard input (keypress is fired)

  • keydown/keyup if no keyboard input (tested with alt, shift, backspace, arrow keys)

  • keydown only for tab?

on Firefox

  • keydown/keypress/keyup when browser registers a keyboard input but also for backspace, arrow keys, tab (so here keypress is fired even with no input)

  • keydown/keyup for alt, shift


This shouldn't be surprising because according to https://api.jquery.com/keypress/:

Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

The use of the keypress event type is deprecated by W3C (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keypress)

The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.


Finally, to answer your question, you should use keyup or keydown to detect a backspace across Firefox and Chrome.


Try it out on here:

_x000D_
_x000D_
$(".inputTxt").bind("keypress keyup keydown", function (event) {_x000D_
    var evtType = event.type;_x000D_
    var eWhich = event.which;_x000D_
    var echarCode = event.charCode;_x000D_
    var ekeyCode = event.keyCode;_x000D_
_x000D_
    switch (evtType) {_x000D_
        case 'keypress':_x000D_
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");_x000D_
            break;_x000D_
        case 'keyup':_x000D_
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<p>");_x000D_
            break;_x000D_
        case 'keydown':_x000D_
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");_x000D_
            break;_x000D_
        default:_x000D_
            break;_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input class="inputTxt" type="text" />_x000D_
<div id="log"></div>
_x000D_
_x000D_
_x000D_

How to strip HTML tags from string in JavaScript?

var html = "<p>Hello, <b>World</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, World

That pretty much the best way of doing it, you're letting the browser do what it does best -- parse HTML.


Edit: As noted in the comments below, this is not the most cross-browser solution. The most cross-browser solution would be to recursively go through all the children of the element and concatenate all text nodes that you find. However, if you're using jQuery, it already does it for you:

alert($("<p>Hello, <b>World</b></p>").text());

Check out the text method.

How to configure encoding in Maven?

Try this:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.7</version>
        <configuration>
          ...
          <encoding>UTF-8</encoding>
          ...
        </configuration>
      </plugin>
    </plugins>
    ...
  </build>
  ...
</project>

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

_x000D_
_x000D_
const button = document.querySelector('button');_x000D_
_x000D_
button.addEventListener('click', () => {_x000D_
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);_x000D_
})
_x000D_
button[aria-expanded="true"] {_x000D_
  color: red;_x000D_
}
_x000D_
<button type="button" aria-expanded="false">Click me!</button>
_x000D_
_x000D_
_x000D_

Routing HTTP Error 404.0 0x80070002

Having this in Global.asax.cs solved it for me.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

How to return data from PHP to a jQuery ajax call

Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.

$.ajax({
    type: "POST",
    url: "somescript.php",
    datatype: "html",
    data: dataString,
    success: function(data) {
        doSomething(data);
    }
});

C#: Looping through lines of multiline string

Sometimes I think we can overcomplicate the solution just to avoid repeating one line of code. This is the reason I landed on this question in the first place.

After thinking about it for a bit I came to the conclusion that the simplest solution is to repeat the ReadLine before and inside the loop.

using (var stringReader = new StringReader(input))
{
    var line = await stringReader.ReadLineAsync();

    while (line != null)
    {
        // do something
        line = await stringReader.ReadLineAsync();
    }
}

I realize this might be considered to not follow the DRY principle, but I think it's worth considering given the simplicity.

Sql query to insert datetime in SQL Server

If you are storing values via any programming language

Here is an example in C#

To store date you have to convert it first and then store it

insert table1 (foodate)
   values (FooDate.ToString("MM/dd/yyyy"));

FooDate is datetime variable which contains your date in your format.

How To have Dynamic SQL in MySQL Stored Procedure

You can pass thru outside the dynamic statement using User-Defined Variables

Server version: 5.6.25-log MySQL Community Server (GPL)

mysql> PREPARE stmt FROM 'select "AAAA" into @a';
Query OK, 0 rows affected (0.01 sec)
Statement prepared

mysql> EXECUTE stmt;
Query OK, 1 row affected (0.01 sec)

DEALLOCATE prepare stmt;
Query OK, 0 rows affected (0.01 sec)

mysql> select @a;
+------+
| @a   |
+------+
|AAAA  |
+------+
1 row in set (0.01 sec)

How to add \newpage in Rmarkdown in a smart way?

You can make the pagebreak conditional on knitting to PDF. This worked for me.

```{r, results='asis', eval=(opts_knit$get('rmarkdown.pandoc.to') == 'latex')}
cat('\\pagebreak')
```

Laravel Mail::send() sending to multiple to or bcc addresses

I am using Laravel 5.6 and the Notifications Facade.

If I set a variable with comma separating the e-mails and try to send it, I get the error: "Address in mail given does not comply with RFC 2822, 3.6.2"

So, to solve the problem, I got the solution idea from @Toskan, coding the following.

        // Get data from Database
        $contacts = Contacts::select('email')
            ->get();

        // Create an array element
        $contactList = [];
        $i=0;

        // Fill the array element
        foreach($contacts as $contact){
            $contactList[$i] = $contact->email;
            $i++;
        }

        .
        .
        .

        \Mail::send('emails.template', ['templateTitle'=>$templateTitle, 'templateMessage'=>$templateMessage, 'templateSalutation'=>$templateSalutation, 'templateCopyright'=>$templateCopyright], function($message) use($emailReply, $nameReply, $contactList) {
                $message->from('[email protected]', 'Some Company Name')
                        ->replyTo($emailReply, $nameReply)
                        ->bcc($contactList, 'Contact List')
                        ->subject("Subject title");
            });

It worked for me to send to one or many recipients.

Can we instantiate an abstract class directly?

No, abstract class can never be instantiated.

TypeLoadException says 'no implementation', but it is implemented

I came across the same message and here is what we have found: We use third party dlls in our project. After a new release of those was out we changed our project to point to the new set of dlls and compiled successfully.

The exception was thrown when I tried to instatiate one of the their interfaced classes during run time. We made sure that all the other references were up to date, but still no luck. We needed a while to spot (using the Object Browser) that the return type of the method in the error message was a completely new type from a new, unreferenced assembly.

We added a reference to the assembly and the error disappeared.

  • The error message was quite misleading, but pointed more or less to the right direction (right method, wrong message).
  • The exception ocurred even though we did not use the method in question.
  • Which leads me to the question: If this exception is thrown in any case, why does the compiler not pick it up?

Which JDK version (Language Level) is required for Android Studio?

Answer Clarification - Android Studio supports JDK8

The following is an answer to the question "What version of Java does Android support?" which is different from "What version of Java can I use to run Android Studio?" which is I believe what was actually being asked. For those looking to answer the 2nd question, you might find Using Android Studio with Java 1.7 helpful.

Also: See http://developer.android.com/sdk/index.html#latest for Android Studio system requirements. JDK8 is actually a requirement for PC and linux (as of 5/14/16).


Java 8 update (3/19/14)

Because I'd assume this question will start popping up soon with the release yesterday: As of right now, there's no set date for when Android will support Java 8.

Here's a discussion over at /androiddev - http://www.reddit.com/r/androiddev/comments/22mh0r/does_android_have_any_plans_for_java_8/

If you really want lambda support, you can checkout Retrolambda - https://github.com/evant/gradle-retrolambda. I've never used it, but it seems fairly promising.

Another Update: Android added Java 7 support

Android now supports Java 7 (minus try-with-resource feature). You can read more about the Java 7 features here: https://stackoverflow.com/a/13550632/413254. If you're using gradle, you can add the following in your build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Older response

I'm using Java 7 with Android Studio without any problems (OS X - 10.8.4). You need to make sure you drop the project language level down to 6.0 though. See the screenshot below.

enter image description here

What tehawtness said below makes sense, too. If they're suggesting JDK 6, it makes sense to just go with JDK 6. Either way will be fine.

enter image description here


Update: See this SO post -- https://stackoverflow.com/a/9567402/413254

Android Gradle Could not reserve enough space for object heap

Faced this issue on Android studio 4.1, windows 10.

The solution that worked for me:

1 - Go to gradle.properties file which is in the root directory of the project.

2 - Comment this line or similar one (org.gradle.jvmargs=-Xmx1536m) to let android studio decide on the best compatible option.

3 - Now close any open project from File -> close project.

4 - On the Welcome window, Go to Configure > Settings.

5 - Go to Build, Execution, Deployment > Compiler

6 - Change Build process heap size (Mbytes) to 1024 and VM Options to -Xmx512m.

Now close the android studio and restart it. The issue will be gone.

Windows batch: formatted date into variable

If you have Python installed, you can do

python -c "import datetime;print(datetime.date.today().strftime('%Y-%m-%d'))"

You can easily adapt the format string to your needs.

Simplest code for array intersection in javascript

Using jQuery:

var a = [1,2,3];
var b = [2,3,4,5];
var c = $(b).not($(b).not(a));
alert(c);

How to set the image from drawable dynamically in android?

Here i am setting the frnd_inactive image from drawable to the image

 imageview= (ImageView)findViewById(R.id.imageView);
 imageview.setImageDrawable(getResources().getDrawable(R.drawable.frnd_inactive));

How to use apply a custom drawable to RadioButton?

full solution here:

<RadioGroup
    android:id="@+id/radioGroup1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RadioButton
        android:id="@+id/radio0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:checked="true"
        android:text="RadioButton" />

    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:layout_marginTop="20dp"
        android:text="RadioButton" />

    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:layout_marginTop="20dp"
        android:text="RadioButton" />
</RadioGroup>

selector XML

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected"    android:state_checked="false"/>

 </selector>

How to set DateTime to null

Now, I can't use DateTime?, I am using DBNull.Value for all data types. It works great.

eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
  ? DBNull.Value
  : DateTime.Parse(dateTimeEnd);

Better way to convert file sizes in Python

Instead of a size divisor of 1024 * 1024 you could use the << bitwise shifting operator, i.e. 1<<20 to get megabytes, 1<<30 to get gigabytes, etc.

In the simplest scenario you can have e.g. a constant MBFACTOR = float(1<<20) which can then be used with bytes, i.e.: megas = size_in_bytes/MBFACTOR.

Megabytes are usually all that you need, or otherwise something like this can be used:

# bytes pretty-printing
UNITS_MAPPING = [
    (1<<50, ' PB'),
    (1<<40, ' TB'),
    (1<<30, ' GB'),
    (1<<20, ' MB'),
    (1<<10, ' KB'),
    (1, (' byte', ' bytes')),
]


def pretty_size(bytes, units=UNITS_MAPPING):
    """Get human-readable file sizes.
    simplified version of https://pypi.python.org/pypi/hurry.filesize/
    """
    for factor, suffix in units:
        if bytes >= factor:
            break
    amount = int(bytes / factor)

    if isinstance(suffix, tuple):
        singular, multiple = suffix
        if amount == 1:
            suffix = singular
        else:
            suffix = multiple
    return str(amount) + suffix

print(pretty_size(1))
print(pretty_size(42))
print(pretty_size(4096))
print(pretty_size(238048577))
print(pretty_size(334073741824))
print(pretty_size(96995116277763))
print(pretty_size(3125899904842624))

## [Out] ###########################
1 byte
42 bytes
4 KB
227 MB
311 GB
88 TB
2 PB

How can I directly view blobs in MySQL Workbench

SELECT *, CONVERT( UNCOMPRESS(column) USING "utf8" ) AS column FROM table_name

How do I disable "missing docstring" warnings at a file-level in Pylint?

I think the fix is relative easy without disabling this feature.

def kos_root():
    """Return the pathname of the KOS root directory."""
    global _kos_root
    if _kos_root: return _kos_root

All you need to do is add the triple double quotes string in every function.

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

remap is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:

:map and :noremap are recursive and non-recursive versions of the various mapping commands. For example, if we run:

:map j gg           (moves cursor to first line)
:map Q j            (moves cursor to first line)
:noremap W j        (moves cursor down one line)

Then:

  • j will be mapped to gg.
  • Q will also be mapped to gg, because j will be expanded for the recursive mapping.
  • W will be mapped to j (and not to gg) because j will not be expanded for the non-recursive mapping.

Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.

For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map and :noremap), one that works in normal mode (:nmap and :nnoremap), one in visual mode (:vmap and :vnoremap) and so on.

For more guidance on this, see:

:help :map
:help :noremap
:help recursive_mapping
:help :map-modes

No appenders could be found for logger(log4j)?

Maybe add the relevent project contains log4j in java build path, I add mahout_h2o into it when I met this problem in a mahout project using eclipse, it works!

What's the difference between window.location= and window.location.replace()?

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;

Bootstrap carousel width and height

I had the same problem.

My height changed to its original height while my slide was animating to the left, ( in a responsive website )

so I fixed it with CSS only :

.carousel .item.left img{
    width: 100% !important;
}

Writing your own square root function

Let's say we are trying to find the square root of 2, and you have an estimate of 1.5. We'll say a = 2, and x = 1.5. To compute a better estimate, we'll divide a by x. This gives a new value y = 1.333333. However, we can't just take this as our next estimate (why not?). We need to average it with the previous estimate. So our next estimate, xx will be (x + y) / 2, or 1.416666.

Double squareRoot(Double a, Double epsilon) {
    Double x = 0d;
    Double y = a;
    Double xx = 0d;

    // Make sure both x and y != 0.
    while ((x != 0d || y != 0d) && y - x > epsilon) {
        xx = (x + y) / 2;

        if (xx * xx >= a) {
            y = xx;
        } else {
            x = xx;
        }
    }

    return xx;
}

Epsilon determines how accurate the approximation needs to be. The function should return the first approximation x it obtains that satisfies abs(x*x - a) < epsilon, where abs(x) is the absolute value of x.

square_root(2, 1e-6)
Output: 1.4142141342163086

How to check if a particular service is running on Ubuntu

for Centos 6.10 : /sbin/service serviceNAME status

for Centos 7.6 and ubuntu 18.04: systemctl status NAME.service

works for all of them: service --status-all

How to go from one page to another page using javascript?

Try this,

window.location.href="sample.html";

Here sample.html is a next page. It will go to the next page.

Difference between Interceptor and Filter in Spring MVC

Filter: - A filter as the name suggests is a Java class executed by the servlet container for each incoming HTTP request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.

Interceptor: - Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

wmic can call an uninstaller. I haven't tried this, but I think it might work.

wmic /node:computername /user:adminuser /password:password product where name="name of application" call uninstall

If you don't know exactly what the program calls itself, do

wmic product get name | sort

and look for it. You can also uninstall using SQL-ish wildcards.

wmic /node:computername /user:adminuser /password:password product where "name like '%j2se%'" call uninstall

... for example would perform a case-insensitive search for *j2se* and uninstall "J2SE Runtime Environment 5.0 Update 12". (Note that in the example above, %j2se% is not an environment variable, but simply the word "j2se" with a SQL-ish wildcard on each end. If your search string could conflict with an environment or script variable, use double percents to specify literal percent signs, like %%j2se%%.)

If wmic prompts for y/n confirmation before completing the uninstall, try this:

echo y | wmic /node:computername /user:adminuser /password:password product where name="whatever" call uninstall

... to pass a y to it before it even asks.

I haven't tested this, but it's worth a shot anyway. If it works on one computer, then you can just loop through a text file containing all the computer names within your organization using a for loop, or put it in a domain policy logon script.

What is the maximum number of characters that nvarchar(MAX) will hold?

Max. capacity is 2 gigabytes of space - so you're looking at just over 1 billion 2-byte characters that will fit into a NVARCHAR(MAX) field.

Using the other answer's more detailed numbers, you should be able to store

(2 ^ 31 - 1 - 2) / 2 = 1'073'741'822 double-byte characters

1 billion, 73 million, 741 thousand and 822 characters to be precise

in your NVARCHAR(MAX) column (unfortunately, that last half character is wasted...)

Update: as @MartinMulder pointed out: any variable length character column also has a 2 byte overhead for storing the actual length - so I needed to subtract two more bytes from the 2 ^ 31 - 1 length I had previously stipulated - thus you can store 1 Unicode character less than I had claimed before.

Programmatically add custom event in the iPhone Calendar

Simple.... use tapku library.... you can google that word and use it... its open source... enjoy..... no need of bugging with those codes....

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

JAVA_HOME is not the name of the java executable. But of the directory, java was installed in. The executable should be $JAVA_HOME/bin/java.

The which command is not helpful for you there. It will not give you the java home, but most likely this is just a wrapper or symlink to java installed in a very different directory.

How do I make Git use the editor of my choice for commits?

On Ubuntu and also Debian (thanks @MichielB) changing the default editor is also possible by running:

sudo update-alternatives --config editor

Which will prompt the following:

There are 4 choices for the alternative editor (providing /usr/bin/editor).

  Selection    Path                Priority   Status
------------------------------------------------------------
  0            /bin/nano            40        auto mode
  1            /bin/ed             -100       manual mode
  2            /bin/nano            40        manual mode
* 3            /usr/bin/vim.basic   30        manual mode
  4            /usr/bin/vim.tiny    10        manual mode

Press enter to keep the current choice[*], or type selection number: 

Embedding Windows Media Player for all browsers

Encoding flash video is actually very easy with ffmpeg. You can use one command to convert from just about any video format, ffmpeg is smart enough to figure the rest out, and it'll use every processor on your machine. Invoking it is easy:

ffmpeg -i input.avi output.flv

ffmpeg will guess at the bitrate you want, but if you'd like to specify one, you can use the -b option, so -b 500000 is 500kbps for example. There's a ton of options of course, but I generally get good results without much tinkering. This is a good place to start if you're looking for more options: video options.

You don't need a special web server to show flash video. I've done just fine by simply pushing .flv files up to a standard web server, and linking to them with a good swf player, like flowplayer.

WMVs are fine if you can be sure that all of your users will always use [a recent, up to date version of] Windows only, but even then, Flash is often a better fit for the web. The player is even extremely skinnable and can be controlled with javascript.

Copy a table from one database to another in Postgres

You can also use the backup functionality in pgAdmin II. Just follow these steps:

  • In pgAdmin, right click the table you want to move, select "Backup"
  • Pick the directory for the output file and set Format to "plain"
  • Click the "Dump Options #1" tab, check "Only data" or "only Schema" (depending on what you are doing)
  • Under the Queries section, click "Use Column Inserts" and "User Insert Commands".
  • Click the "Backup" button. This outputs to a .backup file
  • Open this new file using notepad. You will see the insert scripts needed for the table/data. Copy and paste these into the new database sql page in pgAdmin. Run as pgScript - Query->Execute as pgScript F6

Works well and can do multiple tables at a time.

How to check task status in Celery?

Every Task object has a .request property, which contains it AsyncRequest object. Accordingly, the following line gives the state of a Task task:

task.AsyncResult(task.request.id).state

Datepicker: How to popup datepicker when click on edittext

Date Picker Dialog

                Calendar c=Calendar.getInstance();
                Integer month=c.get(Calendar.MONTH);
                Integer day=c.get(Calendar.DAY_OF_MONTH);
                Integer year=c.get(Calendar.YEAR);

                DatePickerDialog datePickerDialog =new DatePickerDialog(Expenture_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        et_from.setText(dayOfMonth+"/"+month+"/"+year);
                    }
                },year,month,day);
                datePickerDialog.show();

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

Is there a function to round a float in C or do I need to write my own?

There is a round() function, also fround(), which will round to the nearest integer expressed as a double. But that is not what you want.

I had the same problem and wrote this:

#include <math.h>

   double db_round(double value, int nsig)
/* ===============
**
** Rounds double <value> to <nsig> significant figures.  Always rounds
** away from zero, so -2.6 to 1 sig fig will become -3.0.
**
** <nsig> should be in the range 1 - 15
*/

{
    double     a, b;
    long long  i;
    int        neg = 0;


    if(!value) return value;

    if(value < 0.0)
    {
        value = -value;
        neg = 1;
    }

    i = nsig - log10(value);

    if(i) a = pow(10.0, (double)i);
    else  a = 1.0;

    b = value * a;
    i = b + 0.5;
    value = i / a;

    return neg ? -value : value;
} 

How to remove all debug logging calls before building the release version of an Android app?

I have improved on the solution above by providing support for different log levels and by changing the log levels automatically depending on if the code is being run on a live device or on the emulator.

public class Log {

final static int WARN = 1;
final static int INFO = 2;
final static int DEBUG = 3;
final static int VERB = 4;

static int LOG_LEVEL;

static
{
    if ("google_sdk".equals(Build.PRODUCT) || "sdk".equals(Build.PRODUCT)) {
        LOG_LEVEL = VERB;
    } else {
        LOG_LEVEL = INFO;
    }

}


/**
 *Error
 */
public static void e(String tag, String string)
{
        android.util.Log.e(tag, string);
}

/**
 * Warn
 */
public static void w(String tag, String string)
{
        android.util.Log.w(tag, string);
}

/**
 * Info
 */
public static void i(String tag, String string)
{
    if(LOG_LEVEL >= INFO)
    {
        android.util.Log.i(tag, string);
    }
}

/**
 * Debug
 */
public static void d(String tag, String string)
{
    if(LOG_LEVEL >= DEBUG)
    {
        android.util.Log.d(tag, string);
    }
}

/**
 * Verbose
 */
public static void v(String tag, String string)
{
    if(LOG_LEVEL >= VERB)
    {
        android.util.Log.v(tag, string);
    }
}


}

Get checkbox list values with jQuery

Try this one..

var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
     console.log($(this).val());
     listCheck .push($(this).val());
});
console.log(listCheck);

Get last 30 day records from today date in SQL Server

This Should Work Fine

SELECT * FROM product 
WHERE pdate BETWEEN datetime('now', '-30 days') AND datetime('now', 'localtime')

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

I wrote the following to print a list of results to standard out based on available charsets. Note that it also tells you what line fails from a 0 based line number in case you are troubleshooting what character is causing issues.

public static void testCharset(String fileName) {
    SortedMap<String, Charset> charsets = Charset.availableCharsets();
    for (String k : charsets.keySet()) {
        int line = 0;
        boolean success = true;
        try (BufferedReader b = Files.newBufferedReader(Paths.get(fileName),charsets.get(k))) {
            while (b.ready()) {
                b.readLine();
                line++;
            }
        } catch (IOException e) {
            success = false;
            System.out.println(k+" failed on line "+line);
        }
        if (success) 
            System.out.println("*************************  Successs "+k);
    }
}

PHP combine two associative arrays into one array

Check out array_merge().

$array3 = array_merge($array1, $array2);

Convert command line argument to string

#include <iostream>

std::string commandLineStr= "";
for (int i=1;i<argc;i++) commandLineStr.append(std::string(argv[i]).append(" "));

What's a good, free serial port monitor for reverse-engineering?

I've been down this road and eventually opted for a hardware data scope that does non-instrusive in-line monitoring. The software solutions that I tried didn't work for me. If you had a spare PC you could probably build one, albeit rather bulky. This software data scope may work, as might this, but I haven't tried either.

Git push results in "Authentication Failed"

May you have changed password recently for you git account You could try the git push with -u option

git push -u origin branch_name_that_you_want_to_push

After executing above command it will ask for password provide your updated password

Hope it may help you

String.Replace(char, char) method in C#

One caveat: in .NET the linefeed is "\r\n". So if you're loading your text from a file, you might have to use that instead of just "\n"

edit> as samuel pointed out in the comments, "\r\n" is not .NET specific, but is windows specific.

How can I undo git reset --hard HEAD~1?

If you are using a JetBrains IDE (anything IntelliJ based), you can recover even your uncommited changes via their "Local History" feature.

Right-click on your top-level directory in your file tree, find "Local History" in the context menu, and choose "Show History". This will open up a view where your recent edits can be found, and once you have found the revision you want to go back to, right click on it and click "Revert".

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

In order to avoid having to fully specify the git push command you could alternatively modify your git config file:

[remote "gerrit"]
    url = https://your.gerrit.repo:44444/repo
    fetch = +refs/heads/master:refs/remotes/origin/master
    push = refs/heads/master:refs/for/master

Now you can simply:

git fetch gerrit
git push gerrit

This is according to Gerrit

How do I install an R package from source?

From cran, you can install directly from a github repository address. So if you want the package at https://github.com/twitter/AnomalyDetection:

library(devtools)
install_github("twitter/AnomalyDetection")

does the trick.

How to check if command line tools is installed

Go to Applications > Xcode > preferences > downloads

You should see the command line tools there for you to install.

Load vs. Stress testing

Load testing :- Load testing is meant to test the system by constantly and steadily increasing the load on the system till the time it reaches the threshold limit.

Stress Testing :- Under stress testing, various activities to overload the existing resources with excess jobs are carried out in an attempt to break the system down.

The basic difference is as under

click here to see the exact difference

Can I use an HTML input type "date" to collect only a year?

There is input type month in HTML5 which allows to select month and year. Month selector works with autocomplete.

Check the example in JSFiddle.

<!DOCTYPE html>
<html>
<body>
    <header>
        <h1>Select a month below</h1>
    </header>
    Month example
    <input type="month" />
</body>
</html>

How to detect the device orientation using CSS media queries?

CSS to detect screen orientation:

 @media screen and (orientation:portrait) { … }
 @media screen and (orientation:landscape) { … }

The CSS definition of a media query is at http://www.w3.org/TR/css3-mediaqueries/#orientation

What is the difference between C and embedded C?

Basically, there isn't one. Embedded refers to the hosting computer / microcontroller, not the language. The embeddded system might have fewer resources and interfaces for the programmer to play with, and hence C will be used differently, but it is still the same ISO defined language.

Java get String CompareTo as a comparator object

Ok this is a few years later but with java 8 you can use Comparator.naturalOrder():

http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#naturalOrder--

From javadoc:

static <T extends Comparable<? super T>> Comparator<T> naturalOrder()

Returns a comparator that compares Comparable objects in natural order. The returned comparator is serializable and throws NullPointerException when comparing null.

C++ Compare char array with string

"dev" is not a string it is a const char * like var1. Thus you are indeed comparing the memory adresses. Being that var1 is a char pointer, *var1 is a single char (the first character of the pointed to character sequence to be precise). You can't compare a char against a char pointer, which is why that did not work.

Being that this is tagged as c++, it would be sensible to use std::string instead of char pointers, which would make == work as expected. (You would just need to do const std::string var1 instead of const char *var1.

Javascript | Set all values of an array

It's 2019 and you should be using this:

let arr = [...Array(20)].fill(10)

So basically 20 is the length or a new instantiated Array.

Toolbar Navigation Hamburger Icon missing

If you want to use the same drawer as lollipop then let me tell you that's not a static image. That image is drawn in real time by a class called DrawerArrowDrawableToggle. So there is no "hamburger" icon for that.

However if you want the hamburger icon with no animation you can find it here:

https://material.io/tools/icons/?icon=menu&style=baseline

enter image description here

git: can't push (unpacker error) related to permission issues

In case anyone else is stuck with this: it just means the write permissions are wrong in the repo that you’re pushing to. Go and chmod -R it so that the user you’re accessing the git server with has write access.

http://blog.shamess.info/2011/05/06/remote-rejected-na-unpacker-error/

It just works.

Align <div> elements side by side

keep it simple

<div align="center">
<div style="display: inline-block"> <img src="img1.png"> </div>
<div style="display: inline-block"> <img src="img2.png"> </div>
</div>

Android View shadow

putting a background of @android:drawable/dialog_holo_light_frame, gives shadow but you can't change background color nor border style, so it's better to benefit from the shadow of it, while still be able to put a background via layer-list

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!--the shadow comes from here-->
    <item
        android:bottom="0dp"
        android:drawable="@android:drawable/dialog_holo_light_frame"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp">

    </item>

    <item
        android:bottom="0dp"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp">
        <!--whatever you want in the background, here i preferred solid white -->
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />

        </shape>
    </item>
</layer-list>

save it in the drawable folder under say shadow.xml

to assign it to a view, in the xml layout file set the background of it

android:background="@drawable/shadow"

Browser Timeouts

You can see the default value in Chrome in this link

int64_t g_used_idle_socket_timeout_s = 300 // 5 minutes

In Chrome, as far as I know, there isn't an easy way (as Firefox do) to change the timeout value.

Removing cordova plugins from the project

I do it with this python one-liner:

python -c "import subprocess as sp;[sp.call('cordova plugin rm ' + p.split()[0], shell=True) for p in sp.check_output('cordova plugin', shell=True).split('\n') if p]"

Obviously it doesn't handle any sort of error conditions, but it gets the job done.

Change a web.config programmatically with C# (.NET)

Since web.config file is xml file you can open web.config using xmldocument class. Get the node from that xml file that you want to update and then save xml file.

here is URL that explains in more detail how you can update web.config file programmatically.

http://patelshailesh.com/index.php/update-web-config-programmatically

Note: if you make any changes to web.config, ASP.NET detects that changes and it will reload your application(recycle application pool) and effect of that is data kept in Session, Application, and Cache will be lost (assuming session state is InProc and not using a state server or database).

wait until all threads finish their work in java

try this, will work.

  Thread[] threads = new Thread[10];

  List<Thread> allThreads = new ArrayList<Thread>();

  for(Thread thread : threads){

        if(null != thread){

              if(thread.isAlive()){

                    allThreads.add(thread);

              }

        }

  }

  while(!allThreads.isEmpty()){

        Iterator<Thread> ite = allThreads.iterator();

        while(ite.hasNext()){

              Thread thread = ite.next();

              if(!thread.isAlive()){

                   ite.remove();
              }

        }

   }

Which regular expression operator means 'Don't' match this character?

You can use negated character classes to exclude certain characters: for example [^abcde] will match anything but a,b,c,d,e characters.

Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w] (lowercase) will match any "word character" (letter, numbers and underscore), [\W] (uppercase) will match anything but word characters; similarly, [\d] will match the 0-9 digits while [\D] matches anything but the 0-9 digits, and so on.

If you use PHP you can take a look at the regex character classes documentation.

How to add a search box with icon to the navbar in Bootstrap 3?

You could use the segmented buttons example from Bootstrap 3:

<form action="" class="navbar-form navbar-right">
   <div class="input-group">
       <input type="Search" placeholder="Search..." class="form-control" />
       <div class="input-group-btn">
           <button class="btn btn-info">
           <span class="glyphicon glyphicon-search"></span>
           </button>
       </div>
   </div>
</form>

Using msbuild to execute a File System Publish Profile

FYI: I had the same issue with Visual Studio 2015. After many of hours trying, I can now do msbuild myproject.csproj /p:DeployOnBuild=true /p:PublishProfile=myprofile.

I had to edit my .csproj file to get it working. It contained a line like this:

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" 
  Condition="false" />

I changed this line as follows:

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v14.0\WebApplications\Microsoft.WebApplication.targets" />

(I changed 10.0 to 14.0, not sure whether this was necessary. But I definitely had to remove the condition part.)

Include of non-modular header inside framework module

I ended up moving the Umbrella Header to bottom of the Headers list after checking the above solutions, and that worked in Xcode 9.3.

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

How to write ternary operator condition in jQuery?

Also, the ternary operator expects expressions, not statements. Do not use semicolons, only at the end of the ternary op.

$("#blackbox").css({'background': 
    $("#blackbox").css('background') === 'pink' ? 'black' : 'pink'});

Flatten nested dictionaries, compressing keys

Using generators:

def flat_dic_helper(prepand,d):
    if len(prepand) > 0:
        prepand = prepand + "_"
    for k in d:
        i=d[k]
        if type(i).__name__=='dict':
            r = flat_dic_helper(prepand+k,i)
            for j in r:
                yield j
        else:
            yield (prepand+k,i)

def flat_dic(d): return dict(flat_dic_helper("",d))

d={'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}
print(flat_dic(d))


>> {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}

Issue with background color and Google Chrome

I had the same thing in both Chrome and Safari aka Webkit browsers. I'm suspecting it's not a bug, but the incorrect use of css which 'breaks' the background.

In the Question above, the body background property is set to:

background: black;

Which is fine, but not entirely correct. There's no image background, thus...

background-color: black;

Deprecation warning in Moment.js - Not in a recognized ISO format

const dateFormat = 'MM-DD-YYYY';

const currentDateStringType = moment(new Date()).format(dateFormat);
    
const currentDate = moment(new Date() ,dateFormat);  // use this 

moment.suppressDeprecationWarnings = true;

How to link html pages in same or different folders?

Within the same folder, just use the file name:

<a href="thefile.html">my link</a>

Within the parent folder's directory:

<a href="../thefile.html">my link</a>

Within a sub-directory:

<a href="subdir/thefile.html">my link</a>

appending array to FormData and send via AJAX

This is an old question but I ran into this problem with posting objects along with files recently. I needed to be able to post an object, with child properties that were objects and arrays as well.

The function below will walk through an object and create the correct formData object.

// formData - instance of FormData object
// data - object to post
function getFormData(formData, data, previousKey) {
  if (data instanceof Object) {
    Object.keys(data).forEach(key => {
      const value = data[key];
      if (value instanceof Object && !Array.isArray(value)) {
        return this.getFormData(formData, value, key);
      }
      if (previousKey) {
        key = `${previousKey}[${key}]`;
      }
      if (Array.isArray(value)) {
        value.forEach(val => {
          formData.append(`${key}[]`, val);
        });
      } else {
        formData.append(key, value);
      }
    });
  }
}

This will convert the following json -

{
  name: 'starwars',
  year: 1977,
  characters: {
    good: ['luke', 'leia'],
    bad: ['vader'],
  },
}

into the following FormData

 name, starwars
 year, 1977
 characters[good][], luke
 characters[good][], leia
 characters[bad][], vader

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

Mysql database sync between two databases

SymmetricDS is the answer. It supports multiple subscribers with one direction or bi-directional asynchronous data replication. It uses web and database technologies to replicate tables between relational databases, in near real time if desired.

Comprehensive and robust Java API to suit your needs.

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

You can use the dumpbin tool to find out the required DLL dependencies:

dumpbin /DEPENDENTS my.dll

This will tell you which DLLs your DLL needs to load. Particularly look out for MSVCR*.dll. I have seen your error code occur when the correct Visual C++ Redistributable is not installed.

You can get the "Visual C++ Redistributable Packages for Visual Studio 2013" from the Microsoft website. It installs c:\windows\system32\MSVCR120.dll

In the file name, 120 = 12.0 = Visual Studio 2013.

Be careful that you have the right Visual Studio version (10.0 = VS 10, 11 = VS 2012, 12.0 = VS 2013...) right architecture (x64 or x86) for your DLL's target platform, and also you need to be careful around debug builds. The debug build of a DLL depends on MSVCR120d.dll which is a debug version of the library, which is installed with Visual Studio but not by the Redistributable Package.

What is the difference between IEnumerator and IEnumerable?

An Enumerator shows you the items in a list or collection. Each instance of an Enumerator is at a certain position (the 1st element, the 7th element, etc) and can give you that element (IEnumerator.Current) or move to the next one (IEnumerator.MoveNext). When you write a foreach loop in C#, the compiler generates code that uses an Enumerator.

An Enumerable is a class that can give you Enumerators. It has a method called GetEnumerator which gives you an Enumerator that looks at its items. When you write a foreach loop in C#, the code that it generates calls GetEnumerator to create the Enumerator used by the loop.

Adding rows dynamically with jQuery

I have Tried something like this and its works fine;

enter image description here

this is the html part :

<table class="dd" width="100%" id="data">
<tr>
<td>Year</td>
<td>:</td>
<td><select name="year1" id="year1" >
<option value="2012">2012</option>
<option value="2011">2011</option>
</select></td>
<td>Month</td>
<td>:</td>
<td width="17%"><select name="month1" id="month1">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8">August</option>
  <option value="9">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12">December</option>
</select></td>
<td width="7%">Week</td>
<td width="3%">:</td>
<td width="17%"><select name="week1" id="week1" >
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select></td>
<td width="8%">&nbsp;</td>
<td colspan="2">&nbsp;</td>
</tr>
<tr>
<td>Actual</td>
<td>:</td>
<td width="17%"><input name="actual1" id="actual1" type="text" /></td>
<td width="7%">Max</td>
<td width="3%">:</td>
<td><input name="max1" id="max1" type="text" /></td>
<td>Target</td>
<td>:</td>
<td><input name="target1" id="target1" type="text" /></td>
</tr>

this is Javascript part;

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year'+currentItem+'" id="year'+currentItem+'" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td>Month</td><td>:</td><td width="17%"><select name="month'+currentItem+'" id="month'+currentItem+'"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week'+currentItem+'" id="week'+currentItem+'" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"></td><td colspan="2"></td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual'+currentItem+'" id="actual'+currentItem+'" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td><td><input name="max'+currentItem+'" id ="max'+currentItem+'"type="text" /></td><td>Target</td><td>:</td><td><input name="target'+currentItem+'" id="target'+currentItem+'" type="text" /></td></tr>';
  $('#data').append(strToAdd);

 });
 });

 //]]>
 </script>

Finaly PHP submit part:

    for( $i = 1; $i <= $count; $i++ )
{
    $year = $_POST['year'.$i];
    $month = $_POST['month'.$i];
    $week = $_POST['week'.$i];
    $actual = $_POST['actual'.$i];
    $max = $_POST['max'.$i];
    $target = $_POST['target'.$i];
    $extreme = $_POST['extreme'.$i];
    $que = "insert INTO table_name(id,year,month,week,actual,max,target) VALUES ('".$_POST['type']."','".$year."','".$month."','".$week."','".$actual."','".$max."','".$target."')";
    mysql_query($que);

}

you can find more details via Dynamic table row inserter

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

How to decode encrypted wordpress admin password?

You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.

There's a good howto here:

https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/

Basically:

  1. generate a new hash from a known password using e.g. http://scriptserver.mainframe8.com/wordpress_password_hasher.php, as described in the above link, or any other product that uses the phpass library,
  2. use your DB interface (e.g. phpMyAdmin) to update the user_pass field with the new hash string.

If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).

Performing a query on a result from another query?

Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:

SELECT COUNT(*), SUM(SUBQUERY.AGE) from
(
  SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
  FROM availables
  INNER JOIN rooms
  ON availables.room_id=rooms.id
  WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
  GROUP BY availables.bookdate
) AS SUBQUERY

Flutter: how to make a TextField with HintText but no Underline?

Here is a supplemental answer that shows some fuller code:

enter image description here

  Container(
    decoration: BoxDecoration(
      color: Colors.tealAccent,
      borderRadius:  BorderRadius.circular(32),
    ),
    child: TextField(
      decoration: InputDecoration(
        hintStyle: TextStyle(fontSize: 17),
        hintText: 'Search your trips',
        suffixIcon: Icon(Icons.search),
        border: InputBorder.none,
        contentPadding: EdgeInsets.all(20),
      ),
    ),
  ),

Notes:

  • The dark background (code not shown) is Colors.teal.
  • InputDecoration also has a filled and fillColor property, but I couldn't get them to have a corner radius, so I used a container instead.

How to discard local changes and pull latest from GitHub repository

To push over old repo. git push -u origin master --force

I think the --force would work for a pull as well.

Getting the index of a particular item in array

try Array.FindIndex(myArray, x => x.Contains("author"));

What do the icons in Eclipse mean?

This is a fairly comprehensive list from the Eclipse documentation. If anyone knows of another list — maybe with more details, or just the most common icons — feel free to add it.

Latest: JDT Icons

2019-06: JDT Icons

2019-03: JDT Icons

2018-12: JDT Icons

2018-09: JDT Icons

Photon: JDT Icons

Oxygen: JDT Icons

Neon: JDT Icons

Mars: JDT Icons

Luna: JDT Icons

Kepler: JDT Icons

Juno: JDT Icons

Indigo: JDT Icons

Helios: JDT Icons

There are also some CDT icons at the bottom of this help page.

If you're a Subversion user, the icons you're looking for may actually belong to Subclipse; see this excellent answer for more on those.

Hide Spinner in Input Number - Firefox 29

I mixed few answers from answers above and from How to remove the arrows from input[type="number"] in Opera in scss:

input[type=number] {
  &,
  &::-webkit-inner-spin-button,
  &::-webkit-outer-spin-button {
    -webkit-appearance: none;
    -moz-appearance: textfield;
    appearance: none;

    &:hover,
    &:focus {
      -moz-appearance: number-input;
    }
  }
}

Tested on chrome, firefox, safari

Correct way to quit a Qt program?

if you need to close your application from main() you can use this code

int main(int argc, char *argv[]){
QApplication app(argc, argv);
...
if(!QSslSocket::supportsSsl()) return app.exit(0);
...
return app.exec();
}

The program will terminated if OpenSSL is not installed

Getting multiple values with scanf()

Could do this, but then the user has to separate the numbers by a space:

#include "stdio.h"

int main()
{
    int minx, x, y, z;

    printf("Enter four ints: ");
    scanf( "%i %i %i %i", &minx, &x, &y, &z);

    printf("You wrote: %i %i %i %i", minx, x, y, z);
}

Comments in .gitignore?

Do git help gitignore

You will get the help page with following line:

A line starting with # serves as a comment.

Formatting doubles for output in C#

Another method, starting with the method:

double i = (10 * 0.69);
Console.Write(ToStringFull(i));       // Output 6.89999999999999946709294817
Console.Write(ToStringFull(-6.9)      // Output -6.90000000000000035527136788
Console.Write(ToStringFull(i - 6.9)); // Output -0.00000000000000088817841970012523233890533

A Drop-In Function...

public static string ToStringFull(double value)
{
    if (value == 0.0) return "0.0";
    if (double.IsNaN(value)) return "NaN";
    if (double.IsNegativeInfinity(value)) return "-Inf";
    if (double.IsPositiveInfinity(value)) return "+Inf";

    long bits = BitConverter.DoubleToInt64Bits(value);
    BigInteger mantissa = (bits & 0xfffffffffffffL) | 0x10000000000000L;
    int exp = (int)((bits >> 52) & 0x7ffL) - 1023;
    string sign = (value < 0) ? "-" : "";

    if (54 > exp)
    {
        double offset = (exp / 3.321928094887362358); //...or =Math.Log10(Math.Abs(value))
        BigInteger temp = mantissa * BigInteger.Pow(10, 26 - (int)offset) >> (52 - exp);
        string numberText = temp.ToString();
        int digitsNeeded = (int)((numberText[0] - '5') / 10.0 - offset);
        if (exp < 0)
            return sign + "0." + new string('0', digitsNeeded) + numberText;
        else
            return sign + numberText.Insert(1 - digitsNeeded, ".");
    }
    return sign + (mantissa >> (52 - exp)).ToString();
}

How it works

To solve this problem I used the BigInteger tools. Large values are simple as they just require left shifting the mantissa by the exponent. For small values we cannot just directly right shift as that would lose the precision bits. We must first give it some extra size by multiplying it by a 10^n and then do the right shifts. After that, we move over the decimal n places to the left. More text/code here.

static and extern global variables in C and C++

Global variables are not extern nor static by default on C and C++. When you declare a variable as static, you are restricting it to the current source file. If you declare it as extern, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern keyword) you will get a link error (symbol not found).

Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal. If you declare it as static, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal.

What you can do in C++, that you can't in C, is to declare the variable as const on the header, like this:

const int varGlobal = 7;

And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define for constants.

If you need a global variable visible on multiple sources and not const, declare it as extern on the header, and then define it, this time without the extern keyword, on a source file:

Header included by multiple files:

extern int varGlobal;

In one of your source files:

int varGlobal = 7;

How to map and remove nil values in Ruby

One more way to accomplish it will be as shown below. Here, we use Enumerable#each_with_object to collect values, and make use of Object#tap to get rid of temporary variable that is otherwise needed for nil check on result of process_x method.

items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}

Complete example for illustration:

items = [1,2,3,4,5]
def process x
    rand(10) > 5 ? nil : x
end

items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}

Alternate approach:

By looking at the method you are calling process_x url, it is not clear what is the purpose of input x in that method. If I assume that you are going to process the value of x by passing it some url and determine which of the xs really get processed into valid non-nil results - then, may be Enumerabble.group_by is a better option than Enumerable#map.

h = items.group_by {|x| (process x).nil? ? "Bad" : "Good"}
#=> {"Bad"=>[1, 2], "Good"=>[3, 4, 5]}

h["Good"]
#=> [3,4,5]

How can I include all JavaScript files in a directory via JavaScript file?

You can't do that in Javascript from the browser... If I were you, I would use something like browserify. Write your code using commonjs modules and then compile the javascript file into one.

In your html load the javascript file that you compiled.

How do I run .sh or .bat files from Terminal?

Based on IsmailS' comment the command which worked for me on OSX was:

sudo sh ./startup.sh

Can Json.NET serialize / deserialize to / from a stream?

I arrived at this question looking for a way to stream an open ended list of objects onto a System.IO.Stream and read them off the other end, without buffering the entire list before sending. (Specifically I'm streaming persisted objects from MongoDB over Web API.)

@Paul Tyng and @Rivers did an excellent job answering the original question, and I used their answers to build a proof of concept for my problem. I decided to post my test console app here in case anyone else is facing the same issue.

using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace TestJsonStream {
    class Program {
        static void Main(string[] args) {
            using(var writeStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.None)) {
                string pipeHandle = writeStream.GetClientHandleAsString();
                var writeTask = Task.Run(() => {
                    using(var sw = new StreamWriter(writeStream))
                    using(var writer = new JsonTextWriter(sw)) {
                        var ser = new JsonSerializer();
                        writer.WriteStartArray();
                        for(int i = 0; i < 25; i++) {
                            ser.Serialize(writer, new DataItem { Item = i });
                            writer.Flush();
                            Thread.Sleep(500);
                        }
                        writer.WriteEnd();
                        writer.Flush();
                    }
                });
                var readTask = Task.Run(() => {
                    var sw = new Stopwatch();
                    sw.Start();
                    using(var readStream = new AnonymousPipeClientStream(pipeHandle))
                    using(var sr = new StreamReader(readStream))
                    using(var reader = new JsonTextReader(sr)) {
                        var ser = new JsonSerializer();
                        if(!reader.Read() || reader.TokenType != JsonToken.StartArray) {
                            throw new Exception("Expected start of array");
                        }
                        while(reader.Read()) {
                            if(reader.TokenType == JsonToken.EndArray) break;
                            var item = ser.Deserialize<DataItem>(reader);
                            Console.WriteLine("[{0}] Received item: {1}", sw.Elapsed, item);
                        }
                    }
                });
                Task.WaitAll(writeTask, readTask);
                writeStream.DisposeLocalCopyOfClientHandle();
            }
        }

        class DataItem {
            public int Item { get; set; }
            public override string ToString() {
                return string.Format("{{ Item = {0} }}", Item);
            }
        }
    }
}

Note that you may receive an exception when the AnonymousPipeServerStream is disposed, I ignored this as it isn't relevant to the problem at hand.

Convert CString to const char*

To convert a TCHAR CString to ASCII, use the CT2A macro - this will also allow you to convert the string to UTF8 (or any other Windows code page):

// Convert using the local code page
CString str(_T("Hello, world!"));
CT2A ascii(str);
TRACE(_T("ASCII: %S\n"), ascii.m_psz);

// Convert to UTF8
CString str(_T("Some Unicode goodness"));
CT2A ascii(str, CP_UTF8);
TRACE(_T("UTF8: %S\n"), ascii.m_psz);

// Convert to Thai code page
CString str(_T("Some Thai text"));
CT2A ascii(str, 874);
TRACE(_T("Thai: %S\n"), ascii.m_psz);

There is also a macro to convert from ASCII -> Unicode (CA2T) and you can use these in ATL/WTL apps as long as you have VS2003 or greater.

See the MSDN for more info.

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.

Taking screenshot on Emulator from Android Studio

You can capture a screenshot from Android Studio as shown in the image below. You can take capture from Android Studio

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

The fundamental misunderstanding here is in thinking that range is a generator. It's not. In fact, it's not any kind of iterator.

You can tell this pretty easily:

>>> a = range(5)
>>> print(list(a))
[0, 1, 2, 3, 4]
>>> print(list(a))
[0, 1, 2, 3, 4]

If it were a generator, iterating it once would exhaust it:

>>> b = my_crappy_range(5)
>>> print(list(b))
[0, 1, 2, 3, 4]
>>> print(list(b))
[]

What range actually is, is a sequence, just like a list. You can even test this:

>>> import collections.abc
>>> isinstance(a, collections.abc.Sequence)
True

This means it has to follow all the rules of being a sequence:

>>> a[3]         # indexable
3
>>> len(a)       # sized
5
>>> 3 in a       # membership
True
>>> reversed(a)  # reversible
<range_iterator at 0x101cd2360>
>>> a.index(3)   # implements 'index'
3
>>> a.count(3)   # implements 'count'
1

The difference between a range and a list is that a range is a lazy or dynamic sequence; it doesn't remember all of its values, it just remembers its start, stop, and step, and creates the values on demand on __getitem__.

(As a side note, if you print(iter(a)), you'll notice that range uses the same listiterator type as list. How does that work? A listiterator doesn't use anything special about list except for the fact that it provides a C implementation of __getitem__, so it works fine for range too.)


Now, there's nothing that says that Sequence.__contains__ has to be constant time—in fact, for obvious examples of sequences like list, it isn't. But there's nothing that says it can't be. And it's easier to implement range.__contains__ to just check it mathematically ((val - start) % step, but with some extra complexity to deal with negative steps) than to actually generate and test all the values, so why shouldn't it do it the better way?

But there doesn't seem to be anything in the language that guarantees this will happen. As Ashwini Chaudhari points out, if you give it a non-integral value, instead of converting to integer and doing the mathematical test, it will fall back to iterating all the values and comparing them one by one. And just because CPython 3.2+ and PyPy 3.x versions happen to contain this optimization, and it's an obvious good idea and easy to do, there's no reason that IronPython or NewKickAssPython 3.x couldn't leave it out. (And in fact CPython 3.0-3.1 didn't include it.)


If range actually were a generator, like my_crappy_range, then it wouldn't make sense to test __contains__ this way, or at least the way it makes sense wouldn't be obvious. If you'd already iterated the first 3 values, is 1 still in the generator? Should testing for 1 cause it to iterate and consume all the values up to 1 (or up to the first value >= 1)?

How do I bind to list of checkbox values with AngularJS?

You can combine AngularJS and jQuery. For example, you need to define an array, $scope.selected = [];, in the controller.

<label ng-repeat="item in items">
    <input type="checkbox" ng-model="selected[$index]" ng-true-value="'{{item}}'">{{item}}
</label>

You can get an array owning the selected items. Using method alert(JSON.stringify($scope.selected)), you can check the selected items.

Jmeter - get current date and time

Use __time function:

  • ${__time(dd/MM/yyyy,)}

  • ${__time(hh:mm a,)}

Since JMeter 3.3, there are two new functions that let you compute a time:

__timeShift

  "The timeShift function returns a date in the given format with the specified amount of seconds, minutes, hours, days or months added" and 

__RandomDate

  "The RandomDate function returns a random date that lies between the given start date and end date values." 

Since JMeter 4.0:

dateTimeConvert

Convert a date or time from source to target format

If you're looking to learn jmeter correctly, this book will help you.

How do I turn a python datetime into a string, with readable format date?

The datetime class has a method strftime. The Python docs documents the different formats it accepts:

For this specific example, it would look something like:

my_datetime.strftime("%B %d, %Y")

Install pdo for postgres Ubuntu

Try the packaged pecl version instead (the advantage of the packaged installs is that they're easier to upgrade):

apt-get install php5-dev
pecl install pdo
pecl install pdo_pgsql

or, if you just need a driver for PHP, but that it doesn't have to be the PDO one:

apt-get install php5-pgsql

Otherwise, that message most likely means you need to install a more recent libpq package. You can check which version you have by running:

dpkg -s libpq-dev

How to copy directories in OS X 10.7.3?

tl;dr

cp -R "/src/project 1/App" "/src/project 2"

Explanation:

Using quotes will cater for spaces in the directory names

cp -R "/src/project 1/App" "/src/project 2"

If the App directory is specified in the destination directory:

cp -R "/src/project 1/App" "/src/project 2/App"

and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"

Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.

Inside a bash script:

cp -R "${1}/App" "${2}"

Javascript receipt printing using POS Printer

I printed form javascript to a Star Micronics Webprnt TSP 654ii thermal printer. This printer is a wired network printer and you can draw the content to a HTML canvas and make a HTTP request to print. The only caveat is that, this printer does not support HTTPS protocol yet, so you will get a mixed content warning in production. Contacted Star micronics support and they said, they are working on HTTPS support and soon a firmware upgrade will be available. Also, looks like Epson Omnilink TM-88V printer with TM-I will support javascript printing.

Here is a sample code: https://github.com/w3cloud/starwebprint

jQuery add blank option to top of list and make selected to existing dropdown

Solution native Javascript :

document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);

example : http://codepen.io/anon/pen/GprybL

C# LINQ find duplicates in List

Linq query:

var query = from s2 in (from s in someList group s by new { s.Column1, s.Column2 } into sg select sg) where s2.Count() > 1 select s2;

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

Set the table column width constant regardless of the amount of text in its cells?

It also helps, to put in the last "filler cell", with width:auto. This will occupy remaining space, and will leave all other dimensions as specified.

Reflection generic get field value

Although it's not really clear to me what you're trying to achieve, I spotted an obvious error in your code: Field.get() expects the object which contains the field as argument, not some (possible) value of that field. So you should have field.get(object).

Since you appear to be looking for the field value, you can obtain that as:

Object objectValue = field.get(object);

No need to instantiate the field type and create some empty/default value; or maybe there's something I missed.

What is the id( ) function used for?

id() does return the address of the object being referenced (in CPython), but your confusion comes from the fact that python lists are very different from C arrays. In a python list, every element is a reference. So what you are doing is much more similar to this C code:

int *arr[3];
arr[0] = malloc(sizeof(int));
*arr[0] = 1;
arr[1] = malloc(sizeof(int));
*arr[1] = 2;
arr[2] = malloc(sizeof(int));
*arr[2] = 3;
printf("%p %p %p", arr[0], arr[1], arr[2]);

In other words, you are printing the address from the reference and not an address relative to where your list is stored.

In my case, I have found the id() function handy for creating opaque handles to return to C code when calling python from C. Doing that, you can easily use a dictionary to look up the object from its handle and it's guaranteed to be unique.

bash echo number of lines of file given in a bash variable without the file name

wc can't get the filename if you don't give it one.

wc -l < "$JAVA_TAGS_FILE"

When is del useful in Python?

Just another thinking.

When debugging http applications in framework like Django, the call stack full of useless and messed up variables previously used, especially when it's a very long list, could be very painful for developers. so, at this point, namespace controlling could be useful.

passing JSON data to a Spring MVC controller

Add the following dependencies

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.7</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.7</version>
</dependency>

Modify request as follows

$.ajax({ 
    url:urlName,    
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser          
    processData:false, //To avoid making query String instead of JSON
    success: function(resposeJsonObject){
        // Success Message Handler
    }
});

Controller side

@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Person save(@RequestBody Person jsonString) {

   Person person=personService.savedata(jsonString);
   return person;
}

@RequestBody - Covert Json object to java
@ResponseBody- convert Java object to json