Programs & Examples On #Coroutine

Coroutines are a general control structure whereby flow control is cooperatively passed between two different routines without returning.

What does the "yield" keyword do?

Yield gives you a generator.

def get_odd_numbers(i):
    return range(1, i, 2)
def yield_odd_numbers(i):
    for x in range(1, i, 2):
       yield x
foo = get_odd_numbers(10)
bar = yield_odd_numbers(10)
foo
[1, 3, 5, 7, 9]
bar
<generator object yield_odd_numbers at 0x1029c6f50>
bar.next()
1
bar.next()
3
bar.next()
5

As you can see, in the first case foo holds the entire list in memory at once. It's not a big deal for a list with 5 elements, but what if you want a list of 5 million? Not only is this a huge memory eater, it also costs a lot of time to build at the time that the function is called.

In the second case, bar just gives you a generator. A generator is an iterable--which means you can use it in a for loop, etc, but each value can only be accessed once. All the values are also not stored in memory at the same time; the generator object "remembers" where it was in the looping the last time you called it--this way, if you're using an iterable to (say) count to 50 billion, you don't have to count to 50 billion all at once and store the 50 billion numbers to count through.

Again, this is a pretty contrived example, you probably would use itertools if you really wanted to count to 50 billion. :)

This is the most simple use case of generators. As you said, it can be used to write efficient permutations, using yield to push things up through the call stack instead of using some sort of stack variable. Generators can also be used for specialized tree traversal, and all manner of other things.

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

use Object.keys:

Object.keys(this.formErrors).map(key => {
  this.formErrors[key] = '';
  const control = form.get(key);

  if(control && control.dirty && !control.valid) {
    const messages = this.validationMessages[key];
    Object.keys(control.errors).map(key2 => {
      this.formErrors[key] += messages[key2] + ' ';
    });
  }
});

How can I add new dimensions to a Numpy array?

I followed this approach:

import numpy as np
import cv2

ls = []

for image in image_paths:
    ls.append(cv2.imread('test.jpg'))

img_np = np.array(ls) # shape (100, 480, 640, 3)
img_np = np.rollaxis(img_np, 0, 4) # shape (480, 640, 3, 100).

Correct way to synchronize ArrayList in java

Yes it is the correct way, but the synchronised block is required if you want all the removals together to be safe - unless the queue is empty no removals allowed. My guess is that you just want safe queue and dequeue operations, so you can remove the synchronised block.

However, there are far advanced concurrent queues in Java such as ConcurrentLinkedQueue

Folder structure for a Node.js project

More example from my project architecture you can see here:

+-- Dockerfile
+-- README.md
+-- config
¦   +-- production.json
+-- package.json
+-- schema
¦   +-- create-db.sh
¦   +-- db.sql
+-- scripts
¦   +-- deploy-production.sh 
+-- src
¦   +-- app -> Containes API routes
¦   +-- db -> DB Models (ORM)
¦   +-- server.js -> the Server initlializer.
+-- test

Basically, the logical app separated to DB and APP folders inside the SRC dir.

Parse String to Date with Different Format in Java

A Date object has no format, it is a representation. The date can be presented by a String with the format you like.

E.g. "yyyy-MM-dd", "yy-MMM-dd", "dd-MMM-yy" and etc.

To acheive this you can get the use of the SimpleDateFormat

Try this,

        String inputString = "19/05/2009"; // i.e. (dd/MM/yyyy) format

        SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy"); 
        SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date dateFromUser = fromUser.parse(inputString); // Parse it to the exisitng date pattern and return Date type
            String dateMyFormat = myFormat.format(dateFromUser); // format it to the date pattern you prefer
            System.out.println(dateMyFormat); // outputs : 2009-05-19

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

This outputs : 2009-05-19

Implicit type conversion rules in C++ operators

In C++ operators (for POD types) always act on objects of the same type.
Thus if they are not the same one will be promoted to match the other.
The type of the result of the operation is the same as operands (after conversion).

If either is      long          double the other is promoted to      long          double
If either is                    double the other is promoted to                    double
If either is                    float  the other is promoted to                    float
If either is long long unsigned int    the other is promoted to long long unsigned int
If either is long long          int    the other is promoted to long long          int
If either is long      unsigned int    the other is promoted to long      unsigned int
If either is long               int    the other is promoted to long               int
If either is           unsigned int    the other is promoted to           unsigned int
If either is                    int    the other is promoted to                    int
Both operands are promoted to int

Note. The minimum size of operations is int. So short/char are promoted to int before the operation is done.

In all your expressions the int is promoted to a float before the operation is performed. The result of the operation is a float.

int + float =>  float + float = float
int * float =>  float * float = float
float * int =>  float * float = float
int / float =>  float / float = float
float / int =>  float / float = float
int / int                     = int
int ^ float =>  <compiler error>

Enable/disable buttons with Angular

    <div class="col-md-12">
      <p style="color: #28a745; font-weight: bold; font-size:25px; text-align: right " >Total Productos a pagar= {{ getTotal() }} {{ getResult() | currency }}
      <button class="btn btn-success" type="submit" [disabled]="!getResult()" (click)="onSubmit()">
        Ver Pedido
      </button>
     </p>
    </div>

MVC 4 Razor File Upload

View Page

@using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
 { 
   <input type="file" name="file" />
   <input type="submit" value="Upload" class="save" id="btnid" />
 }

script file

$(document).on("click", "#btnid", function (event) {
        event.preventDefault();
        var fileOptions = {
            success: res,
            dataType: "json"
        }
        $("#formid").ajaxSubmit(fileOptions);
    });

In Controller

    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase file)
    {

    }

What are the differences between numpy arrays and matrices? Which one should I use?

As others have mentioned, perhaps the main advantage of matrix was that it provided a convenient notation for matrix multiplication.

However, in Python 3.5 there is finally a dedicated infix operator for matrix multiplication: @.

With recent NumPy versions, it can be used with ndarrays:

A = numpy.ones((1, 3))
B = numpy.ones((3, 3))
A @ B

So nowadays, even more, when in doubt, you should stick to ndarray.

Why in C++ do we use DWORD rather than unsigned int?

DWORD is not a C++ type, it's defined in <windows.h>.

The reason is that DWORD has a specific range and format Windows functions rely on, so if you require that specific range use that type. (Or as they say "When in Rome, do as the Romans do.") For you, that happens to correspond to unsigned int, but that might not always be the case. To be safe, use DWORD when a DWORD is expected, regardless of what it may actually be.

For example, if they ever changed the range or format of unsigned int they could use a different type to underly DWORD to keep the same requirements, and all code using DWORD would be none-the-wiser. (Likewise, they could decide DWORD needs to be unsigned long long, change it, and all code using DWORD would be none-the-wiser.)


Also note unsigned int does not necessary have the range 0 to 4,294,967,295. See here.

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

In my instance at least this seems to be a harmless "not ready" condition that the API retries until it succeeds.

I get anywhere from two to nine of these (on my worst-case-tester, a 2009 FossilBook with 20 tabs open via cellular hotspot).... but then the video functions properly. Once it's running my postMessage-based calls to seekTo definitely work, haven't tested others.

removeEventListener on anonymous functions in JavaScript

I believe that is the point of an anonymous function, it lacks a name or a way to reference it.

If I were you I would just create a named function, or put it in a variable so you have a reference to it.

var t = {};
var handler = function(e) {
    t.scroll = function(x, y) {
        window.scrollBy(x, y);
    };
    t.scrollTo = function(x, y) {
        window.scrollTo(x, y);
    };
};
window.document.addEventListener("keydown", handler);

You can then remove it by

window.document.removeEventListener("keydown", handler);   

convert streamed buffers to utf8-string

Single Buffer

If you have a single Buffer you can use its toString method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8 if you don't provide a parameter, but I've explicitly set the encoding in this example.

var req = http.request(reqOptions, function(res) {
    ...

    res.on('data', function(chunk) {
        var textChunk = chunk.toString('utf8');
        // process utf8 text chunk
    });
});

Streamed Buffers

If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8-character may be contained in the first Buffer (chunk) and the second byte in the second Buffer then you should use a StringDecoder. :

var StringDecoder = require('string_decoder').StringDecoder;

var req = http.request(reqOptions, function(res) {
    ...
    var decoder = new StringDecoder('utf8');

    res.on('data', function(chunk) {
        var textChunk = decoder.write(chunk);
        // process utf8 text chunk
    });
});

This way bytes of incomplete characters are buffered by the StringDecoder until all required bytes were written to the decoder.

jquery .on() method with load event

I'm not sure what you're going for here--by the time jQuery(document).ready() has executed, it has already loaded, and thus document's load event will already have been called. Attaching the load event handler at this point will have no effect and it will never be called. If you're attempting to alert "started" once the document has loaded, just put it right in the (document).ready() call, like this:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {
        $('body').append(x);
    });

    alert('started');

});?

If, as your code also appears to insinuate, you want to fire the alert when .abc has loaded, put it in an individual .load handler:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {
        $('body').append(x);
    });

    $(".abc").on("load", function() {
        alert('started');
    }
});?

Finally, I see little point in using jQuery in one place and $ in another. It's generally better to keep your code consistent, and either use jQuery everywhere or $ everywhere, as the two are generally interchangeable.

htaccess redirect all pages to single page

This will direct everything from the old host to the root of the new host:

RewriteEngine on
RewriteCond %{http_host} ^www.old.com [NC,OR]
RewriteCond %{http_host} ^old.com [NC]
RewriteRule ^(.*)$ http://www.thenewdomain.org/ [R=301,NC,L]

What are the differences between WCF and ASMX web services?

There's a lot of talks going on regarding the simplicity of asmx web services over WCF. Let me clarify few points here.

  • Its true that novice web service developers will get started easily in asmx web services. Visual Studio does all the work for them and readily creates a Hello World project.
  • But if you can learn WCF (which off course wont take much time) then you can get to see that WCF is also quite simple, and you can go ahead easily.
  • Its important to remember that these said complexities in WCF are actually attributed to the beautiful features that it brings along with it. There are addressing, bindings, contracts and endpoints, services & clients all mentioned in the config file. The beauty is your business logic is segregated and maintained safely. Tomorrow if you need to change the binding from basicHttpBinding to netTcpBinding you can easily create a binding in config file and use it. So all the changes related to clients, communication channels, bindings etc are to be done in the configuration leaving the business logic safe & intact, which makes real good sense.
  • WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
  • Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. You can host your WCF services in Console, Windows Services, IIS & WAS, which are again different ways of creating new projects in Visual Studio.
  • ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
  • You will always like to use Visual Studio for NET 4.0 or 4.5 as it makes life easy while creating WCF services.
  • The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer. That's why WCF performs way better than other communication technology counterparts from .NET like asmx, .NET remoting etc.

Not to forget that I was one of those guys who liked asmx services more than WCF, but that time I was not well aware of WCF services and its capabilities. I was scared of the WCF configurations. But I dared and and tried writing few WCF services of my own, and when I learnt more of WCF, now I have no inhibitions about WCF and I recommend them to anyone & everyone. Happy coding!!!

How to send a pdf file directly to the printer using JavaScript?

I think this Library of JavaScript might Help you:

It's called Print.js

First Include

<script src="print.js"></script>
<link rel="stylesheet" type="text/css" href="print.css">

It's basic usage is to call printJS() and just pass in a PDF document url: printJS('docs/PrintJS.pdf')

What I did was something like this, this will also show "Loading...." if PDF document is too large.

<button type="button" onclick="printJS({printable:'docs/xx_large_printjs.pdf', type:'pdf', showModal:true})">
    Print PDF with Message
</button>

However keep in mind that:

Firefox currently doesn't allow printing PDF documents using iframes. There is an open bug in Mozilla's website about this. When using Firefox, Print.js will open the PDF file into a new tab.

How to initialize an array in Java?

Maybe this will work:

public class Array {

    int data[] = new int[10]; 
    /* Creates a new instance of Array */
    public Array() {
        data= {10,20,30,40,50,60,71,80,90,91};
    }
}

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

For Jackson versions < 2.0 use this annotation on the class being serialized:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

I think this is the better way to keep backwards compatibility if we go with this approach, it is working for my case and hope will work for you. Also pretty easy to understand.

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
}

Correct way to initialize HashMap and can HashMap hold different value types?

A HashMap can hold any object as a value, even if it is another HashMap. Eclipse is suggesting that you declare the types because that is the recommended practice for Collections. under Java 5. You are free to ignore Eclipse's suggestions.

Under Java 5, an int (or any primitive type) will be autoboxed into an Integer (or other corresponding type) when you add it to a collection. Be careful with this though, as there are some catches to using autoboxing.

Does "git fetch --tags" include "git fetch"?

In most situations, git fetch should do what you want, which is 'get anything new from the remote repository and put it in your local copy without merging to your local branches'. git fetch --tags does exactly that, except that it doesn't get anything except new tags.

In that sense, git fetch --tags is in no way a superset of git fetch. It is in fact exactly the opposite.

git pull, of course, is nothing but a wrapper for a git fetch <thisrefspec>; git merge. It's recommended that you get used to doing manual git fetching and git mergeing before you make the jump to git pull simply because it helps you understand what git pull is doing in the first place.

That being said, the relationship is exactly the same as with git fetch. git pull is the superset of git pull --tags.

How to format DateTime to 24 hours time?

Use upper-case HH for 24h format:

String s = curr.ToString("HH:mm");

See DateTime.ToString Method.

Programmatically switching between tabs within Swift

Just to update, following iOS 13, we now have SceneDelegates. So one might choose to put the desired tab selection in SceneDelegate.swift as follows:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, 
               willConnectTo session: UISceneSession, 
               options connectionOptions: UIScene.ConnectionOptions) {

        guard let _ = (scene as? UIWindowScene) else { return }

        if let tabBarController = self.window!.rootViewController as? UITabBarController {
            tabBarController.selectedIndex = 1
        }

    }

How to run a python script from IDLE interactive shell?

Try this

import os
import subprocess

DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'helloword.py')

subprocess.call(['python', DIR])

react hooks useEffect() cleanup for only componentWillUnmount?

function LegoComponent() {

  const [lego, setLegos] = React.useState([])

  React.useEffect(() => {
    let isSubscribed = true
    fetchLegos().then( legos=> {
      if (isSubscribed) {
        setLegos(legos)
      }
    })
    return () => isSubscribed = false
  }, []);

  return (
    <ul>
    {legos.map(lego=> <li>{lego}</li>)}
    </ul>
  )
}

In the code above, the fetchLegos function returns a promise. We can “cancel” the promise by having a conditional in the scope of useEffect, preventing the app from setting state after the component has unmounted.

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

How to get the first day of the current week and month?

You should be able to convert your number to a Java Calendar, e.g.:

 Calendar.getInstance().setTimeInMillis(myDate);

From there, the comparison shouldn't be too hard.

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

bootstrap.yml or bootstrap.properties

It's only used/needed if you're using Spring Cloud and your application's configuration is stored on a remote configuration server (e.g. Spring Cloud Config Server).

From the documentation:

A Spring Cloud application operates by creating a "bootstrap" context, which is a parent context for the main application. Out of the box it is responsible for loading configuration properties from the external sources, and also decrypting properties in the local external configuration files.

Note that the bootstrap.yml or bootstrap.properties can contain additional configuration (e.g. defaults) but generally you only need to put bootstrap config here.

Typically it contains two properties:

  • location of the configuration server (spring.cloud.config.uri)
  • name of the application (spring.application.name)

Upon startup, Spring Cloud makes an HTTP call to the config server with the name of the application and retrieves back that application's configuration.

application.yml or application.properties

Contains standard application configuration - typically default configuration since any configuration retrieved during the bootstrap process will override configuration defined here.

Representing null in JSON

There is only one way to represent null; that is with null.

console.log(null === null);   // true
console.log(null === true);   // false
console.log(null === false);  // false
console.log(null === 'null'); // false
console.log(null === "null"); // false
console.log(null === "");     // false
console.log(null === []);     // false
console.log(null === 0);      // false

That is to say; if any of the clients that consume your JSON representation use the === operator; it could be a problem for them.

no value

If you want to convey that you have an object whose attribute myCount has no value:

{ "myCount": null }

no attribute / missing attribute

What if you to convey that you have an object with no attributes:

{}

Client code will try to access myCount and get undefined; it's not there.

empty collection

What if you to convey that you have an object with an attribute myCount that is an empty list:

{ "myCount": [] }

How to search a list of tuples in Python

[k for k,v in l if v =='delicia']

here l is the list of tuples-[(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

And instead of converting it to a dict, we are using llist comprehension.

*Key* in Key,Value in list, where value = **delicia**

Creating a generic method in C#

I know, I know, but...

public static bool TryGetQueryString<T>(string key, out T queryString)

Style input type file?

Same solution via Jquery. Works if you have more than one file input in the page.

$j(".filebutton").click(function() {
    var input = $j(this).next().find('input');
    input.click();
});

$j(".fileinput").change(function(){

    var file = $j(this).val();
    var fileName = file.split("\\");
    var pai =$j(this).parent().parent().prev();
    pai.html(fileName[fileName.length-1]);
    event.preventDefault();
});

How to consume REST in Java

You can able to consume a Restful Web service in Spring using RestTemplate.class.

Example :

public class Application {

    public static void main(String args[]) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> call= restTemplate.getForEntity("http://localhost:8080/SpringExample/hello",String.class);
        System.out.println(call.getBody())
    }

}

Reference

How can you undo the last git add?

So the real answer to

Can this programmer now unstage his last changes with some magical git command?

is actually: No, you cannot unstage just the last git add.

That is if we interpret the question as in the following situation:

Initial file:

void foo() {

}

main() {
    foo();
}

First change followed by git add:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

Second change followed by git add:

void foo(int bar, String baz) {
    print("$bar $baz");
}

main() {
    foo(1337, "h4x0r");
}

In this case, git reset -p will not help, since its smallest granularity is lines. git doesn't know that about the intermediate state of:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

any more.

How to read file contents into a variable in a batch file?

You can read multiple variables from file like this:

for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H

where param.txt:

PARAM1=value1
PARAM2=value2
...

Replacing all non-alphanumeric characters with empty strings

return value.replaceAll("[^A-Za-z0-9 ]", "");

This will leave spaces intact. I assume that's what you want. Otherwise, remove the space from the regex.

H.264 file size for 1 hr of HD video

For a good quality x264 encoding of 1060i, done by a computer, not a mobile device, not in real time, you could use a bitrate at about 5 MBps. That means 2250 MB/hour of encoded material. Recommend you deinterlace the footage and compress as progressive.

Is there a way to select sibling nodes?

There are a few ways to do it.

Either one of the following should do the trick.

// METHOD A (ARRAY.FILTER, STRING.INDEXOF)
var siblings = function(node, children) {
    siblingList = children.filter(function(val) {
        return [node].indexOf(val) != -1;
    });
    return siblingList;
}

// METHOD B (FOR LOOP, IF STATEMENT, ARRAY.PUSH)
var siblings = function(node, children) {
    var siblingList = [];
    for (var n = children.length - 1; n >= 0; n--) {
        if (children[n] != node) {
            siblingList.push(children[n]);
        }  
    }
    return siblingList;
}

// METHOD C (STRING.INDEXOF, ARRAY.SPLICE)
var siblings = function(node, children) {
   siblingList = children;
   index = siblingList.indexOf(node);
   if(index != -1) {
       siblingList.splice(index, 1);
   }
   return siblingList;
}

FYI: The jQuery code-base is a great resource for observing Grade A Javascript.

Here is an excellent tool that reveals the jQuery code-base in a very streamlined way. http://james.padolsey.com/jquery/

How can I get the length of text entered in a textbox using jQuery?

var myLength = $("#myTextbox").val().length;

How to replace existing value of ArrayList element in Java

If you are unaware of the position to replace, use list iterator to find and replace element ListIterator.set(E e)

ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
     String next = iterator.next();
     if (next.equals("Two")) {
         //Replace element
         iterator.set("New");
     }
 }

How to keep two folders automatically synchronized?

You can take advantage of fschange. It’s a Linux filesystem change notification. The source code is downloadable from the above link, you can compile it yourself. fschange can be used to keep track of file changes by reading data from a proc file (/proc/fschange). When data is written to a file, fschange reports the exact interval that has been modified instead of just saying that the file has been changed. If you are looking for the more advanced solution, I would suggest checking Resilio Connect. It is cross-platform, provides extended options for use and monitoring. Since it’s BitTorrent-based, it is faster than any other existing sync tool. It was written on their behalf.

Android: how to parse URL String with spaces to URI object?

You should in fact URI-encode the "invalid" characters. Since the string actually contains the complete URL, it's hard to properly URI-encode it. You don't know which slashes / should be taken into account and which not. You cannot predict that on a raw String beforehand. The problem really needs to be solved at a higher level. Where does that String come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.

At any way, if you can ensure that it are only the spaces in URLs which makes it invalid, then you can also just do a string-by-string replace with %20:

URI uri = new URI(string.replace(" ", "%20"));

Or if you can ensure that it's only the part after the last slash which needs to be URI-encoded, then you can also just do so with help of android.net.Uri utility class:

int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + Uri.encode(string.substring(pos)));

Do note that URLEncoder is insuitable for the task as it's designed to encode query string parameter names/values as per application/x-www-form-urlencoded rules (as used in HTML forms). See also Java URL encoding of query string parameters.

XMLHttpRequest module not defined/found

With the xhr2 library you can globally overwrite XMLHttpRequest from your JS code. This allows you to use external libraries in node, that were intended to be run from browsers / assume they are run in a browser.

global.XMLHttpRequest = require('xhr2');

Simulator or Emulator? What is the difference?

In computer science both a simulation and emulation produce the same outputs, from the same inputs, that the original system does; However, an emulation also uses the same processes to achieve it and is made out of the same materials. A simulation uses different processes from the original system. Also worth noting is the term replication, which is the intermediate of the two - using the same processes but being made out of a different material.

So if I want to run my old Super Mario Bros game on my PC I use an SNES emulator, because it is using the same or similar computer code (processes) to run the game, and uses the same or similar materials (silicon chip). However, if I want to fly a Boeing 747 jet on my PC I use a flight simulator because it uses completely different processes from the original (there are no actual wings, lift or aerodynamics involved!).

Here are the exact definitions taken from a computer science glossary:

A simulation is a model of a system that captures the functional connections between inputs and outputs of the system, but without necessarily being based on processes that are the same as, or similar to, those of the system itself.

A replication is a model of a system that captures the functional connections between inputs and outputs of the system and is based on processes that are the same as, or similar to, those of the system itself.

An emulation is a model of some system that captures the functional connections between inputs and outputs of the system, based on processes that are the same as, or similar to, those of that system, and that is built of the same materials as that system.

Reference: The Open University, M366 Glossary 1.1, 2007

Replace all whitespace with a line break/paragraph mark to make a word list

You could use POSIX [[:blank:]] to match a horizontal white-space character.

sed 's/[[:blank:]]\+/\n/g' file

or you may use [[:space:]] instead of [[:blank:]] also.

Example:

$ echo 'this  is a sentence' | sed 's/[[:blank:]]\+/\n/g'
this
is
a
sentence

Rails 3 migrations: Adding reference column?

EDIT: This is an outdated answer and should not be applied for Rails 4.x+

You don't need to add references when you can use an integer id to your referenced class.

I'd say the advantage of using references instead of a plain integer is that the model will be predefined with belongs_to and since the model is already created and will not be affected when you migrate something existing, the purpose is kind of lost.

So I would do like this instead:

rails g migration add_user_id_to_tester user_id:integer

And then manually add belongs_to :user in the Tester model

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).

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)
lst

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

How to scanf only integer?

Using fgets() is better.

To solve only using scanf() for input, scan for an int and the following char.

int ReadUntilEOL(void) {
  char ch;
  int count;
  while ((count = scanf("%c", &ch)) == 1 && ch != '\n')
    ; // Consume char until \n or EOF or IO error
  return count;
}

#include<stdio.h>
int main(void) {
  int n;

  for (;;) {
    printf("Please enter an integer: ");
    char NextChar = '\n';
    int count = scanf("%d%c", &n, &NextChar);
    if (count >= 1 && NextChar == '\n') 
      break;
    if (ReadUntilEOL() == EOF) 
      return 1;  // No valid input ever found
  }
  printf("You entered: %d\n", n);
  return 0;
}

This approach does not re-prompt if user only enters white-space such as only Enter.

Box shadow in IE7 and IE8

use this for fixing issue with shadow box

filter: progid:DXImageTransform.Microsoft.dropShadow (OffX='2', OffY='2', Color='#F13434', Positive='true');

Javascript split regex question

or just use for date strings 2015-05-20 or 2015.05.20

date.split(/\.|-/);

Restoring Nuget References?

You need to Enable NuGet package restore at the VS solution level for the restore missing package to work.

enter image description here

How do I convert a calendar week into a date in Excel?

=(MOD(R[-1]C-1,100)*7+DATE(INT(R[-1]C/100+2000),1,1)-2)

yyww as the given week exp:week 51 year 2014 will be 1451

Method with a bool return

Use this code:

public bool roomSelected()
{
    foreach (RadioButton rb in GroupBox1.Controls)
    {
        if (rb.Checked == true)
        {
            return true;
        }
    }
    return false;
}

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

The warning message

[WARNING] The requested profile "pom.xml" could not be activated because it does not exist.

means that you somehow passed -P pom.xml to Maven which means "there is a profile called pom.xml; find it and activate it". Check your environment and your settings.xml for this flag and also look at all <profile> elements inside the various XML files.

Usually, mvn help:effective-pom is also useful to see what the real POM would look like.

Now the error means that you tried to configure Maven to build Java 8 code but you're not using a Java 8 runtime. Solutions:

  1. Install Java 8
  2. Make sure Maven uses Java 8 if you have it installed. JAVA_HOME is your friend
  3. Configure the Java compiler in your pom.xml to a Java version which you actually have.

Related:

Count multiple columns with group by in one query

It's hard to know how to help you without understanding the context / structure of your data, but I believe this might help you:

SELECT 
     SUM(CASE WHEN column1 IS NOT NULL THEN 1 ELSE 0 END) AS column1_count
    ,SUM(CASE WHEN column2 IS NOT NULL THEN 1 ELSE 0 END) AS column2_count
    ,SUM(CASE WHEN column3 IS NOT NULL THEN 1 ELSE 0 END) AS column3_count
FROM table

How do I add a new class to an element dynamically?

Yes you can - first capture the event using onmouseover, then set the class name using Element.className.

If you like to add or remove classes - use the more convenient Element.classList method.

_x000D_
_x000D_
.active {
  background: red;
}
_x000D_
<div onmouseover=className="active">
  Hover this!
</div>
_x000D_
_x000D_
_x000D_

How to customize the background color of a UITableViewCell?

Subclass UITableViewCell and add this in the implementation:

-(void)layoutSubviews
{
    [super layoutSubviews];
    self.backgroundColor = [UIColor blueColor];
}

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

If you're on a shared server like me the host said it was a result of hitting memory limits, so they kill scripts which results in the "Premature end of script headers" seen in this error. They referred me to this:

https://help.dreamhost.com/hc/en-us/articles/216540488-Why-did-procwatch-kill-processes-on-my-Shared-serv

Given an increase in memory, the issues went. I think a backup plugin Updraft on wordpress was perhaps over zealous in its duty/settings.

How to capitalize the first letter in a String in Ruby

You can use mb_chars. This respects umlaute:

class String

  # Only capitalize first letter of a string
  def capitalize_first
    self[0] = self[0].mb_chars.upcase
    self
  end

end

Example:

"ümlaute".capitalize_first
#=> "Ümlaute"

SQL: How to properly check if a record exists

It's better to use either of the following:

-- Method 1.
SELECT 1
FROM table_name
WHERE unique_key = value;

-- Method 2.
SELECT COUNT(1)
FROM table_name
WHERE unique_key = value;

The first alternative should give you no result or one result, the second count should be zero or one.

How old is the documentation you're using? Although you've read good advice, most query optimizers in recent RDBMS's optimize SELECT COUNT(*) anyway, so while there is a difference in theory (and older databases), you shouldn't notice any difference in practice.

How to re-index all subarray elements of a multidimensional array?

To reset the keys of all arrays in an array:

$arr = array_map('array_values', $arr);

In case you just want to reset first-level array keys, use array_values() without array_map.

Launch Minecraft from command line - username and password as prefix

To run Minecraft with Forge (change C:\Users\nov11\AppData\Roaming/.minecraft/to your MineCraft path :) [Just for people who are a bit too lazy to search on Google...] Special thanks to ammarx for his TagAPI_3 (Github) which was used to create this command. Arguments are separated line by line to make it easier to find useful ones.

java
-Xms1024M
-Xmx1024M
-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump
-Djava.library.path=C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/natives
-cp
C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraftforge/forge/1.12.2-14.23.5.2775/forge-1.12.2-14.23.5.2775.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/ow2/asm/asm-all/5.2/asm-all-5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/jline/jline/3.5.1/jline-3.5.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/akka/akka-actor_2.11/2.3.3/akka-actor_2.11-2.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/config/1.2.1/config-1.2.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-actors-migration_2.11/1.1.0/scala-actors-migration_2.11-1.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-compiler/2.11.1/scala-compiler-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-library_2.11/1.0.2/scala-continuations-library_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-plugin_2.11.1/1.0.2/scala-continuations-plugin_2.11.1-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-library/2.11.1/scala-library-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-parser-combinators_2.11/1.0.1/scala-parser-combinators_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-reflect/2.11.1/scala-reflect-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-swing_2.11/1.0.1/scala-swing_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-xml_2.11/1.0.2/scala-xml_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/lzma/lzma/0.0.1/lzma-0.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/java3d/vecmath/1.5.2/vecmath-1.5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/trove4j/trove4j/3.0.3/trove4j-3.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/maven/maven-artifact/3.5.3/maven-artifact-3.5.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/patchy/1.1/patchy-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/oshi-project/oshi-core/1.1/oshi-core-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/platform/3.4.0/platform-3.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/ibm/icu/icu4j-core-mojang/51.2/icu4j-core-mojang-51.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecjorbis/20101023/codecjorbis-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecwav/20101023/codecwav-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/libraryjavasound/20101123/libraryjavasound-20101123.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/librarylwjglopenal/20100824/librarylwjglopenal-20100824.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/soundsystem/20120107/soundsystem-20120107.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/io/netty/netty-all/4.1.9.Final/netty-all-4.1.9.Final.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/guava/guava/21.0/guava-21.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-lang3/3.5/commons-lang3-3.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-io/commons-io/2.5/commons-io-2.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-codec/commons-codec/1.10/commons-codec-1.10.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jinput/jinput/2.0.5/jinput-2.0.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jutils/jutils/1.0.0/jutils-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/code/gson/gson/2.8.0/gson-2.8.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/authlib/1.5.25/authlib-1.5.25.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/realms/1.10.22/realms-1.10.22.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-compress/1.8.1/commons-compress-1.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpclient/4.3.3/httpclient-4.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpcore/4.3.2/httpcore-4.3.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/it/unimi/dsi/fastutil/7.1.0/fastutil-7.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-api/2.8.1/log4j-api-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-core/2.8.1/log4j-core-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.4-nightly-20150209/lwjgl-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.4-nightly-20150209/lwjgl_util-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl-platform/2.9.4-nightly-20150209/lwjgl-platform-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.2-nightly-20140822/lwjgl-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.2-nightly-20140822/lwjgl_util-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/1.12.2.jar
net.minecraft.launchwrapper.Launch
--width
854
--height
480
--username
Ishikawa
--version
1.12.2-forge1.12.2-14.23.5.2775
--gameDir
C:\Users\nov11\AppData\Roaming/.minecraft
--assetsDir
C:\Users\nov11\AppData\Roaming/.minecraft/assets
--assetIndex
1.12
--uuid
N/A
--accessToken
aeef7bc935f9420eb6314dea7ad7e1e5
--userType
mojang
--tweakClass
net.minecraftforge.fml.common.launcher.FMLTweaker
--versionType
Forge

Just when other solutions don't work. accessToken and uuid can be acquired from Mojang Servers, check other anwsers for details.

Edit (26.11.2018): I've also created Launcher Framework in C# (.NET Framework 3.5), which you can also check to see how launcher should work Available Here

Force div element to stay in same place, when page is scrolled

There is something wrong with your code.

position : absolute makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll

This can be solved with position : fixed This property will make the element position fixed and still relative to the scroll.

Or

You can check it out Here

How to get last inserted id?

You can create a SqlCommand with CommandText equal to

INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)

and execute int id = (int)command.ExecuteScalar.

This MSDN article will give you some additional techniques.

How to open port in Linux

First, you should disable selinux, edit file /etc/sysconfig/selinux so it looks like this:

SELINUX=disabled
SELINUXTYPE=targeted

Save file and restart system.

Then you can add the new rule to iptables:

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

and restart iptables with /etc/init.d/iptables restart

If it doesn't work you should check other network settings.

Add row to query result using select

You use it like this:

SELECT  age, name
FROM    users
UNION
SELECT  25 AS age, 'Betty' AS name

Use UNION ALL to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION.

How to create a HTTP server in Android?

This can be done using ServerSocket, same as on JavaSE. This class is available on Android. android.permission.INTERNET is required.

The only more tricky part, you need a separate thread wait on the ServerSocket, servicing sub-sockets that come from its accept method. You also need to stop and resume this thread as needed. The simplest approach seems to kill the waiting thread by closing the ServerSocket. If you only need a server while your activity is on the top, starting and stopping ServerSocket thread can be rather elegantly tied to the activity life cycle methods. Also, if the server has multiple users, it may be good to service requests in the forked threads. If there is only one user, this may not be necessary.

If you need to tell the user on which IP is the server listening,use NetworkInterface.getNetworkInterfaces(), this question may tell extra tricks.

Finally, here there is possibly the complete minimal Android server that is very short, simple and may be easier to understand than finished end user applications, recommended in other answers.

Removing character in list of strings

A faster way is to join the list, replace 8 and split the new string:

mylist = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylist = ' '.join(mylist).replace('8','').split()
print mylist

Jenkins: Is there any way to cleanup Jenkins workspace?

Beside above solutions, there is a more "COMMON" way - directly delete the largest space consumer from Linux machine. You can follow the below steps:

  1. Login to Jenkins machine (Putty) enter image description here
  2. cd to the Jenkins installation path

Using ls -lart to list out hidden folder also, normally jenkin installation is placed in .jenkins/ folder

[xxxxx ~]$ ls -lart

drwxrwxr-x 12 xxxx  4096 Feb  8 02:08 .jenkins/
  1. list out the folders spaces

Use df -h to show Disk space in high level

du -sh ./*/ to list out total memory for each subfolder in current path.

du -a /etc/ | sort -n -r | head -n 10 will list top 10 directories eating disk space in /etc/

  1. Delete old build or other large size folder

Normally ./job/ folder or ./workspace/ folder can be the largest folder. Please go inside and delete base on you need (DO NOT delete entire folder).

rm -rf theFolderToDelete

enter image description here

jQuery 'if .change() or .keyup()'

you can bind to multiple events by separating them with a space:

$(":input").on("keyup change", function(e) {
    // do stuff!
})

docs here.

hope that helps. cheers!

How to create a file in Android?

I used the following code to create a temporary file for writing bytes. And its working fine.

File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
     OutputStream fo = new FileOutputStream(file);              
     fo.write(data1);
     fo.close();
     System.out.println("file created: "+file);
}               

//deleting the file             
file.delete();
System.out.println("file deleted");

How to split a string, but also keep the delimiters?

I will post my working versions also(first is really similar to Markus).

public static String[] splitIncludeDelimeter(String regex, String text){
    List<String> list = new LinkedList<>();
    Matcher matcher = Pattern.compile(regex).matcher(text);

    int now, old = 0;
    while(matcher.find()){
        now = matcher.end();
        list.add(text.substring(old, now));
        old = now;
    }

    if(list.size() == 0)
        return new String[]{text};

    //adding rest of a text as last element
    String finalElement = text.substring(old);
    list.add(finalElement);

    return list.toArray(new String[list.size()]);
}

And here is second solution and its round 50% faster than first one:

public static String[] splitIncludeDelimeter2(String regex, String text){
    List<String> list = new LinkedList<>();
    Matcher matcher = Pattern.compile(regex).matcher(text);

    StringBuffer stringBuffer = new StringBuffer();
    while(matcher.find()){
        matcher.appendReplacement(stringBuffer, matcher.group());
        list.add(stringBuffer.toString());
        stringBuffer.setLength(0); //clear buffer
    }

    matcher.appendTail(stringBuffer); ///dodajemy reszte  ciagu
    list.add(stringBuffer.toString());

    return list.toArray(new String[list.size()]);
}

How can I avoid Java code in JSP files, using JSP 2?

Technically, JSP are all converted to Servlets during runtime.

JSP was initially created for the purpose of the decoupling the business logic and the design logic, following the MVC pattern. So JSP is technically all Java code during runtime.

But to answer the question, tag libraries are usually used for applying logic (removing Java code) to JSP pages.

What's the "average" requests per second for a production web application?

Note that hit-rate graphs will be sinusoidal patterns with 'peak hours' maybe 2x or 3x the rate that you get while users are sleeping. (Can be useful when you're scheduling the daily batch-processing stuff to happen on servers)

You can see the effect even on 'international' (multilingual, localised) sites like wikipedia

Original purpose of <input type="hidden">?

The values of form elements including type='hidden' are submitted to the server when the form is posted. input type="hidden" values are not visible in the page. Maintaining User IDs in hidden fields, for example, is one of the many uses.

SO uses a hidden field for the upvote click.

<input value="16293741" name="postId" type="hidden">

Using this value, the server-side script can store the upvote.

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

Eclipse hooks Dynamic Web projects into tomcat and maintains it's own configuration but does not deploy the standard tomcat ROOT.war. As http://localhost:8085/ link returns 404 does indeed show that tomcat is up and running, just can't find a web app deployed to root.

By default, any deployed dynamic web projects use their project name as context root, so you should see http://localhost:8085/yourprojectname working properly, but check the Servers tab first to ensure that your web project has actually been deployed.

Hope that helps.

Force index use in Oracle

There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.

Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.

begin 
   DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
                                 , INDNAME=>IndexName);
end;

For table.

begin 
   DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
                                 , TABNAME=>TableName);
end;

In extreme cases, you can try setting up the statistics on your own.

Replacing a character from a certain index

Strings in Python are immutable meaning you cannot replace parts of them.

You can however create a new string that is modified. Mind that this is not semantically equivalent since other references to the old string will not be updated.

You could for instance write a function:

def replace_str_index(text,index=0,replacement=''):
    return '%s%s%s'%(text[:index],replacement,text[index+1:])

And then for instance call it with:

new_string = replace_str_index(old_string,middle)

If you do not feed a replacement, the new string will not contain the character you want to remove, you can feed it a string of arbitrary length.

For instance:

replace_str_index('hello?bye',5)

will return 'hellobye'; and:

replace_str_index('hello?bye',5,'good')

will return 'hellogoodbye'.

What is __future__ in Python used for and how/when to use it, and how it works

With __future__ module's inclusion, you can slowly be accustomed to incompatible changes or to such ones introducing new keywords.

E.g., for using context managers, you had to do from __future__ import with_statement in 2.5, as the with keyword was new and shouldn't be used as variable names any longer. In order to use with as a Python keyword in Python 2.5 or older, you will need to use the import from above.

Another example is

from __future__ import division
print 8/7  # prints 1.1428571428571428
print 8//7 # prints 1

Without the __future__ stuff, both print statements would print 1.

The internal difference is that without that import, / is mapped to the __div__() method, while with it, __truediv__() is used. (In any case, // calls __floordiv__().)

Apropos print: print becomes a function in 3.x, losing its special property as a keyword. So it is the other way round.

>>> print

>>> from __future__ import print_function
>>> print
<built-in function print>
>>>

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

What is the most efficient string concatenation method in python?

Inspired by @JasonBaker's benchmarks, here's a simple one comparing 10 "abcdefghijklmnopqrstuvxyz" strings, showing that .join() is faster; even with this tiny increase in variables:

Catenation

>>> x = timeit.Timer(stmt='"abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz"')
>>> x.timeit()
0.9828147209324385

Join

>>> x = timeit.Timer(stmt='"".join(["abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz"])')
>>> x.timeit()
0.6114138159765048

Failed to execute 'createObjectURL' on 'URL':

If you are using ajax, it is possible to add the options xhrFields: { responseType: 'blob' }:

$.ajax({
  url: 'yourURL',
  type: 'POST',
  data: yourData,
  xhrFields: { responseType: 'blob' },
  success: function (data, textStatus, jqXHR) {
    let src = window.URL.createObjectURL(data);
  }
});

Parsing HTTP Response in Python

When I printed response.read() I noticed that b was preprended to the string (e.g. b'{"a":1,..). The "b" stands for bytes and serves as a declaration for the type of the object you're handling. Since, I knew that a string could be converted to a dict by using json.loads('string'), I just had to convert the byte type to a string type. I did this by decoding the response to utf-8 decode('utf-8'). Once it was in a string type my problem was solved and I was easily able to iterate over the dict.

I don't know if this is the fastest or most 'pythonic' way of writing this but it works and theres always time later of optimization and improvement! Full code for my solution:

from urllib.request import urlopen
import json

# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)

# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)

print(json_obj['source_name']) # prints the string with 'source_name' key

Export data from Chrome developer tool

I had same issue for which I came here. With some trials, I figured out for copying multiple pages of chrome data as in the question I zoomed out till I got all the data in one page, that is, without scroll, with very small font size. Now copy and paste that in excel which copies all the records and in normal font. This is good for few pages of data I think.

When and how should I use a ThreadLocal variable?

Essentially, when you need a variable's value to depend on the current thread and it isn't convenient for you to attach the value to the thread in some other way (for example, subclassing thread).

A typical case is where some other framework has created the thread that your code is running in, e.g. a servlet container, or where it just makes more sense to use ThreadLocal because your variable is then "in its logical place" (rather than a variable hanging from a Thread subclass or in some other hash map).

On my web site, I have some further discussion and examples of when to use ThreadLocal that may also be of interest.

Some people advocate using ThreadLocal as a way to attach a "thread ID" to each thread in certain concurrent algorithms where you need a thread number (see e.g. Herlihy & Shavit). In such cases, check that you're really getting a benefit!

How do I cancel an HTTP fetch() request?

TL/DR:

fetch now supports a signal parameter as of 20 September 2017, but not all browsers seem support this at the moment.

2020 UPDATE: Most major browsers (Edge, Firefox, Chrome, Safari, Opera, and a few others) support the feature, which has become part of the DOM living standard. (as of 5 March 2020)

This is a change we will be seeing very soon though, and so you should be able to cancel a request by using an AbortControllers AbortSignal.

Long Version

How to:

The way it works is this:

Step 1: You create an AbortController (For now I just used this)

const controller = new AbortController()

Step 2: You get the AbortControllers signal like this:

const signal = controller.signal

Step 3: You pass the signal to fetch like so:

fetch(urlToFetch, {
    method: 'get',
    signal: signal, // <------ This is our AbortSignal
})

Step 4: Just abort whenever you need to:

controller.abort();

Here's an example of how it would work (works on Firefox 57+):

_x000D_
_x000D_
<script>_x000D_
    // Create an instance._x000D_
    const controller = new AbortController()_x000D_
    const signal = controller.signal_x000D_
_x000D_
    /*_x000D_
    // Register a listenr._x000D_
    signal.addEventListener("abort", () => {_x000D_
        console.log("aborted!")_x000D_
    })_x000D_
    */_x000D_
_x000D_
_x000D_
    function beginFetching() {_x000D_
        console.log('Now fetching');_x000D_
        var urlToFetch = "https://httpbin.org/delay/3";_x000D_
_x000D_
        fetch(urlToFetch, {_x000D_
                method: 'get',_x000D_
                signal: signal,_x000D_
            })_x000D_
            .then(function(response) {_x000D_
                console.log(`Fetch complete. (Not aborted)`);_x000D_
            }).catch(function(err) {_x000D_
                console.error(` Err: ${err}`);_x000D_
            });_x000D_
    }_x000D_
_x000D_
_x000D_
    function abortFetching() {_x000D_
        console.log('Now aborting');_x000D_
        // Abort._x000D_
        controller.abort()_x000D_
    }_x000D_
_x000D_
</script>_x000D_
_x000D_
_x000D_
_x000D_
<h1>Example of fetch abort</h1>_x000D_
<hr>_x000D_
<button onclick="beginFetching();">_x000D_
    Begin_x000D_
</button>_x000D_
<button onclick="abortFetching();">_x000D_
    Abort_x000D_
</button>
_x000D_
_x000D_
_x000D_

Sources:

How do I return multiple values from a function in C?

I don't know what your string is, but I'm going to assume that it manages its own memory.

You have two solutions:

1: Return a struct which contains all the types you need.

struct Tuple {
    int a;
    string b;
};

struct Tuple getPair() {
    Tuple r = { 1, getString() };
    return r;
}

void foo() {
    struct Tuple t = getPair();
}

2: Use pointers to pass out values.

void getPair(int* a, string* b) {
    // Check that these are not pointing to NULL
    assert(a);
    assert(b);
    *a = 1;
    *b = getString();
}

void foo() {
    int a, b;
    getPair(&a, &b);
}

Which one you choose to use depends largely on personal preference as to whatever semantics you like more.

String concatenation with Groovy

Reproducing tim_yates answer on current hardware and adding leftShift() and concat() method to check the finding:

  'String leftShift' {
    foo << bar << baz
  }
  'String concat' {
    foo.concat(bar)
       .concat(baz)
       .toString()
  }

The outcome shows concat() to be the faster solution for a pure String, but if you can handle GString somewhere else, GString template is still ahead, while honorable mention should go to leftShift() (bitwise operator) and StringBuffer() with initial allocation:

Environment
===========
* Groovy: 2.4.8
* JVM: OpenJDK 64-Bit Server VM (25.191-b12, Oracle Corporation)
    * JRE: 1.8.0_191
    * Total Memory: 238 MB
    * Maximum Memory: 3504 MB
* OS: Linux (4.19.13-300.fc29.x86_64, amd64)

Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On

                                    user  system  cpu  real

String adder                         453       7  460   469
String leftShift                     287       2  289   295
String concat                        169       1  170   173
GString template                      24       0   24    24
Readable GString template             32       0   32    32
GString template toString            400       0  400   406
Readable GString template toString   412       0  412   419
StringBuilder                        325       3  328   334
StringBuffer                         390       1  391   398
StringBuffer with Allocation         259       1  260   265

Is there any way I can define a variable in LaTeX?

If you want to use \newcommand, you can also include \usepackage{xspace} and define command by \newcommand{\newCommandName}{text to insert\xspace}. This can allow you to just use \newCommandName rather than \newCommandName{}.

For more detail, http://www.math.tamu.edu/~harold.boas/courses/math696/why-macros.html

How to extract this specific substring in SQL Server?

Assuming they always exist and are not part of your data, this will work:

declare @string varchar(8000) = '23;chair,red [$3]'
select substring(@string, charindex(';', @string) + 1, charindex(' [', @string) - charindex(';', @string) - 1)

Why does my Eclipse keep not responding?

Last night at 2am I closed my Eclipse (Juno) just fine. This morning I open it up and I get nothing but "Not Responding" on my 64bit Windows 7 machine.

I looked in [workspace]\.metadata\.log and it showed an error with Invalid property category path: ValidationPropertiesPage

I cuss it out pretty good and then show it who's the boss :

  1. delete [workspace]\.metadata folder
  2. delete [workspace]\[project]\.settings
  3. Open up Eclipse to the same workspace as before, re-import your project.

Which brings me to another topic... Eclipse -> import -> Android -> Existing Android code into workspace... seems to be broken once again. But that's a different topic.

How I can delete in VIM all text from current line to end of file?

dG will delete from the current line to the end of file

dCtrl+End will delete from the cursor to the end of the file

But if this file is as large as you say, you may be better off reading the first few lines with head rather than editing and saving the file.

head hugefile > firstlines

(If you are on Windows you can use the Win32 port of head)

Where is the default log location for SharePoint/MOSS?

For Sharepoint 2007

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS

How to detect installed version of MS-Office?

To whoever it might concern, here's my version that checks for Office 95-2019 & O365, both MSI based and ClickAndRun are supported, on both 32 and 64 bit systems (falls back to 32 bits when 64 bit version is not installed).

Written in Python 3.5 but of course you can always use that logic in order to write your own code in another language:

from winreg import *
from typing import Tuple, Optional, List

# Let's make sure the dictionnary goes from most recent to oldest
KNOWN_VERSIONS = {
    '16.0': '2016/2019/O365',
    '15.0': '2013',
    '14.0': '2010',
    '12.0': '2007',
    '11.0': '2003',
    '10.0': '2002',
    '9.0': '2000',
    '8.0': '97',
    '7.0': '95',
}


def get_value(hive: int, key: str, value: Optional[str], arch: int = 0) -> str:
    """
    Returns a value from a given registry path

    :param hive: registry hive (windows.registry.HKEY_LOCAL_MACHINE...)
    :param key:  which registry key we're searching for
    :param value: which value we query, may be None if unnamed value is searched
    :param arch: which registry architecture we seek (0 = default, windows.registry.KEY_WOW64_64KEY, windows.registry.KEY_WOW64_32KEY)
                 Giving multiple arches here will return first result
    :return: value
    """

    def _get_value(hive: int, key: str, value: Optional[str], arch: int) -> str:
        try:
            open_reg = ConnectRegistry(None, hive)
            open_key = OpenKey(open_reg, key, 0, KEY_READ | arch)
            value, type = QueryValueEx(open_key, value)
            # Return the first match
            return value
        except (FileNotFoundError, TypeError, OSError) as exc:
            raise FileNotFoundError('Registry key [%s] with value [%s] not found. %s' % (key, value, exc))

    # 768 = 0 | KEY_WOW64_64KEY | KEY_WOW64_32KEY (where 0 = default)
    if arch == 768:
        for _arch in [KEY_WOW64_64KEY, KEY_WOW64_32KEY]:
            try:
                return _get_value(hive, key, value, _arch)
            except FileNotFoundError:
                pass
        raise FileNotFoundError
    else:
        return _get_value(hive, key, value, arch)


def get_keys(hive: int, key: str, arch: int = 0, open_reg: HKEYType = None, recursion_level: int = 1,
             filter_on_names: List[str] = None, combine: bool = False) -> dict:
    """
    :param hive: registry hive (windows.registry.HKEY_LOCAL_MACHINE...)
    :param key: which registry key we're searching for
    :param arch: which registry architecture we seek (0 = default, windows.registry.KEY_WOW64_64KEY, windows.registry.KEY_WOW64_32KEY)
    :param open_reg: (handle) handle to already open reg key (for recursive searches), do not give this in your function call
    :param recursion_level: recursivity level
    :param filter_on_names: list of strings we search, if none given, all value names are returned
    :param combine: shall we combine multiple arch results or return first match
    :return: list of strings
    """
    def _get_keys(hive: int, key: str, arch: int, open_reg: HKEYType, recursion_level: int, filter_on_names: List[str]):
        try:
            if not open_reg:
                open_reg = ConnectRegistry(None, hive)
            open_key = OpenKey(open_reg, key, 0, KEY_READ | arch)
            subkey_count, value_count, _ = QueryInfoKey(open_key)

            output = {}
            values = []
            for index in range(value_count):
                name, value, type = EnumValue(open_key, index)
                if isinstance(filter_on_names, list) and name not in filter_on_names:
                    pass
                else:
                    values.append({'name': name, 'value': value, 'type': type})
            if not values == []:
                output[''] = values

            if recursion_level > 0:
                for subkey_index in range(subkey_count):
                    try:
                        subkey_name = EnumKey(open_key, subkey_index)
                        sub_values = get_keys(hive=0, key=key + '\\' + subkey_name, arch=arch,
                                              open_reg=open_reg, recursion_level=recursion_level - 1,
                                              filter_on_names=filter_on_names)
                        output[subkey_name] = sub_values
                    except FileNotFoundError:
                        pass

            return output

        except (FileNotFoundError, TypeError, OSError) as exc:
            raise FileNotFoundError('Cannot query registry key [%s]. %s' % (key, exc))

    # 768 = 0 | KEY_WOW64_64KEY | KEY_WOW64_32KEY (where 0 = default)
    if arch == 768:
        result = {}
        for _arch in [KEY_WOW64_64KEY, KEY_WOW64_32KEY]:
            try:
                if combine:
                    result.update(_get_keys(hive, key, _arch, open_reg, recursion_level, filter_on_names))
                else:
                    return _get_keys(hive, key, _arch, open_reg, recursion_level, filter_on_names)
            except FileNotFoundError:
                pass
        return result
    else:
        return _get_keys(hive, key, arch, open_reg, recursion_level, filter_on_names)


def get_office_click_and_run_ident():
    # type: () -> Optional[str]
    """
    Try to find the office product via clickandrun productID
    """
    try:
        click_and_run_ident = get_value(HKEY_LOCAL_MACHINE,
                                                 r'Software\Microsoft\Office\ClickToRun\Configuration',
                                                 'ProductReleaseIds',
                                                 arch=KEY_WOW64_64KEY |KEY_WOW64_32KEY,)
    except FileNotFoundError:
        click_and_run_ident = None
    return click_and_run_ident


def _get_used_word_version():
    # type: () -> Optional[int]
    """
    Try do determine which version of Word is used (in case multiple versions are installed)
    """
    try:
        word_ver = get_value(HKEY_CLASSES_ROOT, r'Word.Application\CurVer', None)
    except FileNotFoundError:
        word_ver = None
    try:
        version = int(word_ver.split('.')[2])
    except (IndexError, ValueError, AttributeError):
        version = None
    return version


def _get_installed_office_version():
    # type: () -> Optional[str, bool]
    """
    Try do determine which is the highest current version of Office installed
    """
    for possible_version, _ in KNOWN_VERSIONS.items():
        try:
            office_keys = get_keys(HKEY_LOCAL_MACHINE,
                                               r'SOFTWARE\Microsoft\Office\{}'.format(possible_version),
                                               recursion_level=2,
                                               arch=KEY_WOW64_64KEY |KEY_WOW64_32KEY,
                                               combine=True)

            try:
                is_click_and_run = True if office_keys['ClickToRunStore'] is not None else False
            except:
                is_click_and_run = False

            try:
                is_valid = True if office_keys['Word'] is not None else False
                if is_valid:
                    return possible_version, is_click_and_run
            except KeyError:
                pass
        except FileNotFoundError:
            pass
    return None, None


def get_office_version():
    # type: () -> Tuple[str, Optional[str]]
    """
    It's plain horrible to get the office version installed
    Let's use some tricks, ie detect current Word used
    """

    word_version = _get_used_word_version()
    office_version, is_click_and_run = _get_installed_office_version()

    # Prefer to get used word version instead of installed one
    if word_version is not None:
        office_version = word_version

    version = float(office_version)
    click_and_run_ident = get_office_click_and_run_ident()

    def _get_office_version():
        # type: () -> str
        if version:
            if version < 16:
                try:
                    return KNOWN_VERSIONS['{}.0'.format(version)]
                except KeyError:
                    pass
            # Special hack to determine which of 2016, 2019 or O365 it is
            if version == 16:
                if isinstance(click_and_run_ident, str):
                    if '2016' in click_and_run_ident:
                        return '2016'
                    if '2019' in click_and_run_ident:
                        return '2019'
                    if 'O365' in click_and_run_ident:
                        return 'O365'
                return '2016/2019/O365'
        # Let's return whatever we found out
        return 'Unknown: {}'.format(version, click_and_run_ident)

    if isinstance(click_and_run_ident, str) or is_click_and_run:
        click_and_run_suffix = 'ClickAndRun'
    else:
        click_and_run_suffix = None

    return _get_office_version(), click_and_run_suffix

You can than use the code like the following example:

office_version, click_and_run = get_office_version()
print('Office {} {}'.format(office_version, click_and_run))

Remarks

  • Didn't test with office < 2010 though
  • Python typing is different between the registry functions and the office functions since I wrote the registry ones before finding out that pypy / python2 does not like typing... On those python interpreters you might just remove typing completly
  • Any improvements are highly welcome

How do I count cells that are between two numbers in Excel?

If you have Excel 2007 or later use COUNTIFS with an "S" on the end, i.e.

=COUNTIFS(B2:B292,">10",B2:B292,"<10000")

You may need to change commas , to semi-colons ;

In earlier versions of excel use SUMPRODUCT like this

=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))

Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=

Check whether $_POST-value is empty

isset() will return true if the variable has been initialised. If you have a form field with its name value set to userName, when that form is submitted the value will always be "set", although there may not be any data in it.

Instead, trim() the string and test its length

if("" == trim($_POST['userName'])){
    $username = 'Anonymous';
}      

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Call js-function using JQuery timer

Might want to check out jQuery Timer to manage one or multiple timers.

http://code.google.com/p/jquery-timer/

var timer = $.timer(yourfunction, 10000);

function yourfunction() { alert('test'); }

Then you can control it with:

timer.play();
timer.pause();
timer.toggle();
timer.once();
etc...

Removing numbers from string

Say st is your unformatted string, then run

st_nodigits=''.join(i for i in st if i.isalpha())

as mentioned above. But my guess that you need something very simple so say s is your string and st_res is a string without digits, then here is your code

l = ['0','1','2','3','4','5','6','7','8','9']
st_res=""
for ch in s:
 if ch not in l:
  st_res+=ch

XAMPP: Couldn't start Apache (Windows 10)

Actually, by default IIS (Microsoft, .NET, etc.) is installed.

  • Go to Control Panel
  • Turn Windows features on or off...
  • Under (IIS) Internet Information Services, uncheck the (WWWS) world wide web services.
  • Click OK.

This could be a permanent solution. :)

Changing precision of numeric column in Oracle

If the table is compressed this will work:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES move nocompress;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

alter table EVAPP_FEES compress;

what does "error : a nonstatic member reference must be relative to a specific object" mean?

EncodeAndSend is not a static function, which means it can be called on an instance of the class CPMSifDlg. You cannot write this:

 CPMSifDlg::EncodeAndSend(/*...*/);  //wrong - EncodeAndSend is not static

It should rather be called as:

 CPMSifDlg dlg; //create instance, assuming it has default constructor!
 dlg.EncodeAndSend(/*...*/);   //correct 

About .bash_profile, .bashrc, and where should alias be written in?

The reason you separate the login and non-login shell is because the .bashrc file is reloaded every time you start a new copy of Bash. The .profile file is loaded only when you either log in or use the appropriate flag to tell Bash to act as a login shell.

Personally,

  • I put my PATH setup into a .profile file (because I sometimes use other shells);
  • I put my Bash aliases and functions into my .bashrc file;
  • I put this

    #!/bin/bash
    #
    # CRM .bash_profile Time-stamp: "2008-12-07 19:42"
    #
    # echo "Loading ${HOME}/.bash_profile"
    source ~/.profile # get my PATH setup
    source ~/.bashrc  # get my Bash aliases
    

    in my .bash_profile file.

Oh, and the reason you need to type bash again to get the new alias is that Bash loads your .bashrc file when it starts but it doesn't reload it unless you tell it to. You can reload the .bashrc file (and not need a second shell) by typing

source ~/.bashrc

which loads the .bashrc file as if you had typed the commands directly to Bash.

How to copy data to clipboard in C#

For console projects in a step-by-step fashion, you'll have to first add the System.Windows.Forms reference. The following steps work in Visual Studio Community 2013 with .NET 4.5:

  1. In Solution Explorer, expand your console project.
  2. Right-click References, then click Add Reference...
  3. In the Assemblies group, under Framework, select System.Windows.Forms.
  4. Click OK.

Then, add the following using statement in with the others at the top of your code:

using System.Windows.Forms;

Then, add either of the following Clipboard.SetText statements to your code:

Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);

And lastly, add STAThreadAttribute to your Main method as follows, to avoid a System.Threading.ThreadStateException:

[STAThreadAttribute]
static void Main(string[] args)
{
  // ...
}

Tablix: Repeat header rows on each page not working - Report Builder 3.0

I have 2.0 and found the above to help; however, the selecting of a static did not highlight the cell for some reason. I followed these steps:

  1. Under column groups select the advanced and the statics will show up
  2. Click on the static which shows up in the row groups
  3. Set KeepWithGroup to After and RepeatOnNewPage to true

Now your column headers should repeat on each page.

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

If it is going to be a web based application, you can also use the ServletContextListener interface.

public class SLF4JBridgeListener implements ServletContextListener {

   @Autowired 
   ThreadPoolTaskExecutor executor;

   @Autowired 
   ThreadPoolTaskScheduler scheduler;

    @Override
    public void contextInitialized(ServletContextEvent sce) {

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
         scheduler.shutdown();
         executor.shutdown();     

    }

}

How to extract request http headers from a request using NodeJS connect

var host = req.headers['host']; 

The headers are stored in a JavaScript object, with the header strings as object keys.

Likewise, the user-agent header could be obtained with

var userAgent = req.headers['user-agent']; 

How to retrieve data from sqlite database in android and display it in TextView

TextView tekst = (TextView) findViewById(R.id.editText1); 

You cannot cast EditText to TextView.

Undo scaffolding in Rails

When we generate scaffold, following files will be created:

Command: rails generate scaffold Game

Files created:

>       invoke  active_record
>       create    db/migrate/20160905064128_create_games.rb
>       create    app/models/game.rb
>       invoke    test_unit
>       create      test/models/game_test.rb
>       create      test/fixtures/games.yml
>       invoke  resource_route
>        route    resources :games
>       invoke  inherited_resources_controller
>       create    app/controllers/games_controller.rb
>       invoke    erb
>       create      app/views/games
>       create      app/views/games/index.html.erb
>       create      app/views/games/edit.html.erb
>       create      app/views/games/show.html.erb
>       create      app/views/games/new.html.erb
>       create      app/views/games/_form.html.erb
>       invoke    test_unit
>       create      test/controllers/games_controller_test.rb
>       invoke    helper
>       create      app/helpers/games_helper.rb
>       invoke      test_unit
>       create        test/helpers/games_helper_test.rb
>       invoke    jbuilder
>       create      app/views/games/index.json.jbuilder
>       create      app/views/games/show.json.jbuilder
>       invoke  assets
>       invoke    coffee
>       create      app/assets/javascripts/games.js.coffee
>       invoke    scss
>       create      app/assets/stylesheets/games.css.scss
>       invoke  scss
>       create    app/assets/stylesheets/scaffolds.css.scss

If we have run the migration after this then we have to rollback the migration first as the deletion of scaffold will remove the migration file too and we will not able to revert that migration.

Incase we have run the migration:

rake db:rollback

and after this we can safely remove the scaffold by this commad.

rails d scaffold Game

This command will remove all the files created by the scaffold in your project.

Are HTTP cookies port specific?

An alternative way to go around the problem, is to make the name of the session cookie be port related. For example:

  • mysession8080 for the server running on port 8080
  • mysession8000 for the server running on port 8000

Your code could access the webserver configuration to find out which port your server uses, and name the cookie accordingly.

Keep in mind that your application will receive both cookies, and you need to request the one that corresponds to your port.

There is no need to have the exact port number in the cookie name, but this is more convenient.

In general, the cookie name could encode any other parameter specific to the server instance you use, so it can be decoded by the right context.

Python string.replace regular expression

As a summary

import sys
import re

f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
     s=myfile.read()
ret = re.sub(find,replace, s)   # <<< This is where the magic happens
print ret

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

Gmail: OAuth

  • Goto the link
  • Login with your gmail username password
  • Click on the google menu at the top left
  • Click API Manager
  • Click on Credentials
  • Click Create Credentials and select OAuth Client
  • Select Web Application as Application type and Enter the Name-> Enter Authorised Redirect URL (Eg: http://localhost:53922/signin-google) ->Click on Create button. This will create the credentials. Pls make a note of Client ID and Secret ID. Finally click OK to close the credentials pop up.
  • Next important step is to enable the Google API. Click on Overview in the left pane.
  • Click on the Google API under Social APIs section.
  • Click Enable.

That’s all from the Google part.

Come back to your application, open App_start/Startup.Auth.cs and uncomment the following snippet

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "",
            ClientSecret = ""
        });

Update the ClientId and ClientSecret with the values from Google API credentials which you have created already.

  • Run your application
  • Click Login
  • You will see the Google button under ‘Use Another Section to log in’ section
  • Click on the Google button
  • Application will prompt you to enter the username and password
  • Enter the gmail username and password and click Sign In
  • This will perform the OAuth and come back to your application and prompting you to register with the Gmail id.
  • Click register to register the Gmail id into your application database.
  • You will see the Identity details appear in the top as normal registration
  • Try logout and login again thru Gmail. This will automatically logs you into the app.

How to create a Multidimensional ArrayList in Java?

Once I required 2-D arrayList and I created using List and ArrayList and the code is as follows:

import java.util.*;

public class ArrayListMatrix {

    public static void main(String args[]){

        List<ArrayList<Integer>> a = new ArrayList<>();

        ArrayList<Integer> a1 = new ArrayList<Integer>();
        ArrayList<Integer> a2 = new ArrayList<Integer>();
        ArrayList<Integer> a3 = new ArrayList<Integer>();


        a1.add(1);
        a1.add(2);
        a1.add(3);

        a2.add(4);
        a2.add(5);
        a2.add(6);

        a3.add(7);
        a3.add(8);
        a3.add(9);

        a.add(a1);
        a.add(a2);
        a.add(a3);


        for(ArrayList obj:a){

            ArrayList<Integer> temp = obj;

            for(Integer job : temp){
                System.out.print(job+" ");
            }
            System.out.println();
        }
    }
}

Output:

1 2 3

4 5 6

7 8 9

Source : https://www.codepuran.com/java/2d-matrix-arraylist-collection-class-java/

Finding an elements XPath using IE Developer tool

Are you trying to find some work around getting xpath in IE?

There are many add-ons for other browsers like xpather for Chrome or xpather, xpath-checker and firebug for FireFox that will give you the xpath of an element in a second. But sadly there is no add-on or tool available that will do this for IE. For most cases you can get the xpath of the elements that fall in your script using the above tools in Firefox and tweak them a little (if required) to make them work in IE.

But if you are testing an application that will work only in IE or the specific scenario or page that has this element will open-up/play-out only in IE then you cannot use any of the above mention tools to find the XPATH. Well the only thing that works in this case is the Bookmarklets that were coded just for this purpose. Bookmarklets are JavaScript code that you will add in IE as bookmarks and later use to get the XPATH of the element you desire. Using these you can get the XPATH as easily as you get using xpather or any other firefox addon.

STEPS TO INSTALL BOOKMARKLETS

1)Open IE

2)Type about:blank in the address bar and hit enter

3)From Favorites main menu select ---> Add favorites

4) In the Add a favorite popup window enter name GetXPATH1.

5)Click add button in the add a favorite popup window.

6)Open the Favorites menu and right click the newly added favorite and select properties option.

7)GetXPATH1 Properties will open up. Select the web Document Tab.

8)Enter the following in the URL field.

javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}

9)Click Ok. Click YES on the popup alert.

10)Add another favorite by following steps 3 to 5, Name this favorite GetXPATH2 (step4)

11)Repeat steps 6 and 7 for GetXPATH2 that you just created.

12)Enter the following in the URL field for GetXPATH2

javascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');clipboardData.setData("Text", xpath);}o__o();

13)Repeat Step 9.

You are all done!!

Now to get the XPATH of elements just select the element with your mouse. This would involve clicking the left mouse button just before the element (link, button, image, checkbox, text etc) begins and dragging it till the element ends. Once you do this first select the favorite GetXPATH1 from the favorites menu and then select the second favorite GetXPATH2. At this point you will get a confirmation, hit allow access button. Now open up a notepad file, right click and select paste option. This will give you the XPATH of the element you seek.

Can we pass parameters to a view in SQL?

A hacky way to do it without stored procedures or functions would be to create a settings table in your database, with columns Id, Param1, Param2, etc. Insert a row into that table containing the values Id=1,Param1=0,Param2=0, etc. Then you can add a join to that table in your view to create the desired effect, and update the settings table before running the view. If you have multiple users updating the settings table and running the view concurrently things could go wrong, but otherwise it should work OK. Something like:

CREATE VIEW v_emp 
AS 
SELECT      * 
FROM        emp E
INNER JOIN  settings S
ON          S.Id = 1 AND E.emp_id = S.Param1

Deleting an element from an array in PHP

Two ways for removing the first item of an array with keeping order of the index and also if you don't know the key name of the first item.

Solution #1

// 1 is the index of the first object to get
// NULL to get everything until the end
// true to preserve keys
$array = array_slice($array, 1, null, true);

Solution #2

// Rewinds the array's internal pointer to the first element
// and returns the value of the first array element.
$value = reset($array);
// Returns the index element of the current array position
$key = key($array);
unset($array[$key]);

For this sample data:

$array = array(10 => "a", 20 => "b", 30 => "c");

You must have this result:

array(2) {
  [20]=>
  string(1) "b"
  [30]=>
  string(1) "c"
}

How do I generate a random integer between min and max in Java?

Using the Random class is the way to go as suggested in the accepted answer, but here is a less straight-forward correct way of doing it if you didn't want to create a new Random object :

min + (int) (Math.random() * (max - min + 1));

Android Open External Storage directory(sdcard) for storing file

I had been having the exact same problem!

To get the internal SD card you can use

String extStore = System.getenv("EXTERNAL_STORAGE");
File f_exts = new File(extStore);

To get the external SD card you can use

String secStore = System.getenv("SECONDARY_STORAGE");
File f_secs = new File(secStore);

On running the code

 extStore = "/storage/emulated/legacy"
 secStore = "/storage/extSdCarcd"

works perfectly!

Dark Theme for Visual Studio 2010 With Productivity Power Tools

So, I tested above themes and found out none of them are showing proper color combination when using Productivity Power Tools in Visual Studio.
Ultimately, being a fan of dark themes, I created one myself which is fully supported from VS2005 to VS2013.
Here's the screenshot

enter image description here

Download this dark theme from here: Obsidian Meets Visual Studio

To use this theme go to Tools -> Import and Export Setting... -> import selected environment settings -> (optional to save current settings) -> Browse select and then Finish.

Replace words in a string - Ruby

First, you don't declare the type in Ruby, so you don't need the first string.

To replace a word in string, you do: sentence.gsub(/match/, "replacement").

How to convert IPython notebooks to PDF and HTML?

You can use this simple online service. It supports both HTML and PDF.

Loop through files in a folder in matlab

At first, you must specify your path, the path that your *.csv files are in there

path = 'f:\project\dataset'

You can change it based on your system.

then,

use dir function :

files = dir (strcat(path,'\*.csv'))

L = length (files);

for i=1:L
   image{i}=csvread(strcat(path,'\',file(i).name));   
   % process the image in here
end

pwd also can be used.

Read next word in java

Using Scanners, you will end up spawning a lot of objects for every line. You will generate a decent amount of garbage for the GC with large files. Also, it is nearly three times slower than using split().

On the other hand, If you split by space (line.split(" ")), the code will fail if you try to read a file with a different whitespace delimiter. If split() expects you to write a regular expression, and it does matching anyway, use split("\\s") instead, that matches a "bit" more whitespace than just a space character.

P.S.: Sorry, I don't have right to comment on already given answers.

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

ListenForClients is getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in Main. When two instances of the TcpListener try to listen on the same port, you get that error.

Using other keys for the waitKey() function of opencv

For C++:

In case of using keyboard characters/numbers, an easier solution would be:

int key = cvWaitKey();

switch(key)
{
   case ((int)('a')):
   // do something if button 'a' is pressed
   break;
   case ((int)('h')):
   // do something if button 'h' is pressed
   break;
}

WCF Service, the type provided as the service attribute values…could not be found

Change the following line in your Eval.svc file from:

<%@ ServiceHost Language="C#" Debug="true" Service="EvalServiceLibary.Eval" %> 

to:

<%@ ServiceHost Language="C#" Debug="true" Service="EvalServiceLibary.EvalService" %>

Npm install cannot find module 'semver'

Faced this issue when I ran npm install using a lower version of node. Then later when I upgraded to latest version of node and ran gulp, it has shown this error.

To resolve, deleted node_modules and re-ran npm install. Then gulp ran fine.

Contain an image within a div?

Here is javascript I wrote to do just this.

function ImageTile(parentdiv, imagediv) {
imagediv.style.position = 'absolute';

function load(image) {
    //
    // Reset to auto so that when the load happens it resizes to fit our image and that
    // way we can tell what size our image is. If we don't do that then it uses the last used
    // values to auto-size our image and we don't know what the actual size of the image is.
    //
    imagediv.style.height = "auto";
    imagediv.style.width = "auto";
    imagediv.style.top = 0;
    imagediv.style.left = 0;

    imagediv.src = image;
}

//bind load event (need to wait for it to finish loading the image)
imagediv.onload = function() {
    var vpWidth = parentdiv.clientWidth;
    var vpHeight = parentdiv.clientHeight;
    var imgWidth = this.clientWidth;
    var imgHeight = this.clientHeight;

    if (imgHeight > imgWidth) {
        this.style.height = vpHeight + 'px';
        var width = ((imgWidth/imgHeight) * vpHeight);
        this.style.width = width + 'px';
        this.style.left = ((vpWidth - width)/2) + 'px';
    } else {
        this.style.width = vpWidth + 'px';
        var height = ((imgHeight/imgWidth) * vpWidth);
        this.style.height = height + 'px';
        this.style.top = ((vpHeight - height)/2) + 'px';
    }
};

return {
    "load": load
};

}

And to use it just do something like this:

 var tile1 = ImageTile(document.documentElement, document.getElementById("tile1"));
 tile1.load(url);

I use this for a slideshow in which I have two of these "tiles" and I fade one out and the other in. The loading is done on the "tile" that is not visible to avoid the jarring visual affect of the resetting of the style back to "auto".

How to set custom location for local installation of npm package?

TL;DR

You can do this by using the --prefix flag and the --global* flag.

pje@friendbear:~/foo $ npm install bower -g --prefix ./vendor/node_modules
[email protected] /Users/pje/foo/vendor/node_modules/bower

*Even though this is a "global" installation, installed bins won't be accessible through the command line unless ~/foo/vendor/node_modules exists in PATH.

TL;DR

Every configurable attribute of npm can be set in any of six different places. In order of priority:

  • Command-Line Flags: --prefix ./vendor/node_modules
  • Environment Variables: NPM_CONFIG_PREFIX=./vendor/node_modules
  • User Config File: $HOME/.npmrc or userconfig param
  • Global Config File: $PREFIX/etc/npmrc or userconfig param
  • Built-In Config File: path/to/npm/itself/npmrc
  • Default Config: node_modules/npmconf/config-defs.js

By default, locally-installed packages go into ./node_modules. global ones go into the prefix config variable (/usr/local by default).

You can run npm config list to see your current config and npm config edit to change it.

PS

In general, npm's documentation is really helpful. The folders section is a good structural overview of npm and the config section answers this question.

Check last modified date of file in C#

Just use File.GetLastWriteTime. There's a sample on that page showing how to use it.

Adding placeholder text to textbox

txtUsuario.Attributes.Add("placeholder", "Texto");

Bash Script : what does #!/bin/bash mean?

That is called a shebang, it tells the shell what program to interpret the script with, when executed.

In your example, the script is to be interpreted and run by the bash shell.

Some other example shebangs are:

(From Wikipedia)

#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell
#!/bin/csh — Execute the file using csh, the C shell, or a compatible shell
#!/usr/bin/perl -T — Execute using Perl with the option for taint checks
#!/usr/bin/php — Execute the file using the PHP command line interpreter
#!/usr/bin/python -O — Execute using Python with optimizations to code
#!/usr/bin/ruby — Execute using Ruby

and a few additional ones I can think off the top of my head, such as:

#!/bin/ksh
#!/bin/awk
#!/bin/expect

In a script with the bash shebang, for example, you would write your code with bash syntax; whereas in a script with expect shebang, you would code it in expect syntax, and so on.

Response to updated portion:

It depends on what /bin/sh actually points to on your system. Often it is just a symlink to /bin/bash. Sometimes portable scripts are written with #!/bin/sh just to signify that it's a shell script, but it uses whichever shell is referred to by /bin/sh on that particular system (maybe it points to /bin/bash, /bin/ksh or /bin/zsh)

SyntaxError: missing ; before statement

I got this error, hope this will help someone:

const firstName = 'Joe';
const lastName = 'Blogs';
const wholeName = firstName + ' ' lastName + '.';

The problem was that I was missing a plus (+) between the empty space and lastName. This is a super simplified example: I was concatenating about 9 different parts so it was hard to spot the error.

Summa summarum: if you get "SyntaxError: missing ; before statement", don't look at what is wrong with the the semicolon (;) symbols in your code, look for an error in syntax on that line.

Hash Table/Associative Array in VBA

I've used Francesco Balena's HashTable class several times in the past when a Collection or Dictionary wasn't a perfect fit and i just needed a HashTable.

java.io.IOException: Server returned HTTP response code: 500

This Status Code 500 is an Internal Server Error. This code indicates that a part of the server (for example, a CGI program) has crashed or encountered a configuration error.

i think the problem does'nt lie on your side, but rather on the side of the Http server. the resources you used to access may have been moved or get corrupted, or its configuration just may have altered or spoiled

How can I manually set an Angular form field as invalid?

Here is an example that works:

MatchPassword(AC: FormControl) {
  let dataForm = AC.parent;
  if(!dataForm) return null;

  var newPasswordRepeat = dataForm.get('newPasswordRepeat');
  let password = dataForm.get('newPassword').value;
  let confirmPassword = newPasswordRepeat.value;

  if(password != confirmPassword) {
    /* for newPasswordRepeat from current field "newPassword" */
    dataForm.controls["newPasswordRepeat"].setErrors( {MatchPassword: true} );
    if( newPasswordRepeat == AC ) {
      /* for current field "newPasswordRepeat" */
      return {newPasswordRepeat: {MatchPassword: true} };
    }
  } else {
    dataForm.controls["newPasswordRepeat"].setErrors( null );
  }
  return null;
}

createForm() {
  this.dataForm = this.fb.group({
    password: [ "", Validators.required ],
    newPassword: [ "", [ Validators.required, Validators.minLength(6), this.MatchPassword] ],
    newPasswordRepeat: [ "", [Validators.required, this.MatchPassword] ]
  });
}

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

for me , using export PYTHONIOENCODING=UTF-8 before executing python command worked .

MySQL Server has gone away when importing large sql file

If you are running with default values then you have a lot of room to optimize your mysql configuration.

The first step I recommend is to increase the max_allowed_packet to 128M.

Then download the MySQL Tuning Primer script and run it. It will provide recommendations to several facets of your config for better performance.

Also look into adjusting your timeout values both in MySQL and PHP.

How big (file size) is the file you are importing and are you able to import the file using the mysql command line client instead of PHPMyAdmin?

How to load CSS Asynchronously

2020 Update


The simple answer (full browser support):

<link rel="stylesheet" href="style.css" media="print" onload="this.media='all'">

The documented answer (with optional preloading and script-disabled fallback):

 <!-- Optional, if we want the stylesheet to get preloaded. Note that this line causes stylesheet to get downloaded, but not applied to the page. Use strategically — while preloading will push this resource up the priority list, it may cause more important resources to be pushed down the priority list. This may not be the desired effect for non-critical CSS, depending on other resources your app needs. -->
 <link rel="preload" href="style.css" as="style">

 <!-- Media type (print) doesn't match the current environment, so browser decides it's not that important and loads the stylesheet asynchronously (without delaying page rendering). On load, we change media type so that the stylesheet gets applied to screens. -->
 <link rel="stylesheet" href="style.css" media="print" onload="this.media='all'">

 <!-- Fallback that only gets inserted when JavaScript is disabled, in which case we can't load CSS asynchronously. -->
 <noscript><link rel="stylesheet" href="style.css"></noscript>

Preloading and async combined:

If you need preloaded and async CSS, this solution simply combines two lines from the documented answer above, making it slightly cleaner. But this won't work in Firefox until they support the preload keyword. And again, as detailed in the documented answer above, preloading may not actually be beneficial.

<link href="style.css" rel="preload" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="style.css"></noscript>

Additional considerations:

Note that, in general, if you're going to load CSS asynchronously, it's generally recommended that you inline critical CSS, since CSS is a render-blocking resource for a reason.

Credit to filament group for their many async CSS solutions.

Session TimeOut in web.xml

If you don't want a timeout happening for some purpose:

<session-config>
    <session-timeout>0</session-timeout>
</session-config>

Should result in no timeout at all -> infinite

Removing a Fragment from the back stack

You add to the back state from the FragmentTransaction and remove from the backstack using FragmentManager pop methods:

FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(myFrag);
trans.commit();
manager.popBackStack();

How to increase the execution timeout in php?

Test if you are is safe mode - if not - set the time limit (Local Value) to what you want:

if(!ini_get('safe_mode')){

    echo "safe mode off";
    set_time_limit(180);// seconds

    phpinfo();// see 'max_execution_time'
}

*You cannot set time limit this way if safe mode 'on'.

preg_match in JavaScript?

var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');

if(!thisRegex.test(text)){
    alert('fail');
}

I found test to act more preg_match as it provides a Boolean return. However you do have to declare a RegExp var.

TIP: RegExp adds it's own / at the start and finish, so don't pass them.

What does MissingManifestResourceException mean and how to fix it?

From the Microsoft support page:

This problem occurs if you use a localized resource that exists in a satellite assembly that you created by using a .resources file that has an inappropriate file name. This problem typically occurs if you manually create a satellite assembly.

To work around this problem, specify the file name of the .resources file when you run Resgen.exe. While you specify the file name of the .resources file, make sure that the file name starts with the namespace name of your application. For example, run the following command at the Microsoft Visual Studio .NET command prompt to create a .resources file that has the namespace name of your application at the beginning of the file name:

Resgen strings.CultureIdentifier.resx 
MyApp.strings.CultureIdentifier.resources

How to enable SOAP on CentOS

For my point of view, First thing is to install soap into Centos

yum install php-soap


Second, see if the soap package exist or not

yum search php-soap

third, thus you must see some result of soap package you installed, now type a command in your terminal in the root folder for searching the location of soap for specific path

find -name soap.so

fourth, you will see the exact path where its installed/located, simply copy the path and find the php.ini to add the extension path,

usually the path of php.ini file in centos 6 is in

/etc/php.ini

fifth, add a line of code from below into php.ini file

extension='/usr/lib/php/modules/soap.so'

and then save the file and exit.

sixth run apache restart command in Centos. I think there is two command that can restart your apache ( whichever is easier for you )

service httpd restart

OR

apachectl restart

Lastly, check phpinfo() output in browser, you should see SOAP section where SOAP CLIENT, SOAP SERVER etc are listed and shown Enabled.

How can I debug git/git-shell related problems?

For even more verbose output use following:

GIT_CURL_VERBOSE=1 GIT_TRACE=1 git pull origin master

How can I throw CHECKED exceptions from inside Java 8 streams?

Here is a different view or solution for the original problem. Here I show that we have an option to write a code that will process only a valid subset of values with an option to detect and handle caseses when the exception was thrown.

    @Test
    public void getClasses() {

        String[] classNames = {"java.lang.Object", "java.lang.Integer", "java.lang.Foo"};
        List<Class> classes =
                Stream.of(classNames)
                        .map(className -> {
                            try {
                                return Class.forName(className);
                            } catch (ClassNotFoundException e) {
                                // log the error
                                return null;
                            }
                        })
                        .filter(c -> c != null)
                        .collect(Collectors.toList());

        if (classes.size() != classNames.length) {
            // add your error handling here if needed or process only the resulting list
            System.out.println("Did not process all class names");
        }

        classes.forEach(System.out::println);
    }

How to add message box with 'OK' button?

The code compiles ok for me. May be you have forgotten to add the import:

import android.app.AlertDialog;

Anyway, you have a good tutorial here.

How to display a list using ViewBag

To put it all together, this is what it should look like:

In the controller:

List<Fund> fundList = db.Funds.ToList();
ViewBag.Funds = fundList;

Then in the view:

@foreach (var item in ViewBag.Funds)
{
    <span> @item.FundName </span>
}

How to change workspace and build record Root Directory on Jenkins?

By default, Jenkins stores all of its data in this directory on the file system.

There are a few ways to change the Jenkins home directory:

  • Edit the JENKINS_HOME variable in your Jenkins configuration file (e.g. /etc/sysconfig/jenkins on Red Hat Linux).
  • Use your web container's admin tool to set the JENKINS_HOME environment variable.
  • Set the environment variable JENKINS_HOME before launching your web container, or before launching Jenkins directly from the WAR file.
  • Set the JENKINS_HOME Java system property when launching your web container, or when launching Jenkins directly from the WAR file.
  • Modify web.xml in jenkins.war (or its expanded image in your web container). This is not recommended. This value cannot be changed while Jenkins is running. It is shown here to help you ensure that your configuration is taking effect.

Compare dates in MySQL

You can try below query,

select * from players
where 
    us_reg_date between '2000-07-05'
and
    DATE_ADD('2011-11-10',INTERVAL 1 DAY)

Escape quote in web.config connection string

Odeds answer is almost complete. Just one thing to add.

  1. Escape xml special chars like Emanuele Greco said.
  2. Put the password in single quotes like Oded said
  3. (this one is new) Escape single ticks with another single tick (ref)

having this password="'; this sould be a valid connection string:

connectionString='Server=dbsrv;User ID=myDbUser;Password='&quot;&amp;&amp;;'

How do I wrap text in a pre tag?

The <pre>-Element stands for "pre-formatted-text" and is intended to keep the formatting of the text (or whatever) between its tags. Therefore it is actually not inteded to have automatic word-wrapping or line-breaks within the <pre>-Tag

Text in a element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks.

source: w3schools.com, emphasises made by myself.

How to get error information when HttpWebRequest.GetResponse() fails

HttpWebRequest myHttprequest = null;
HttpWebResponse myHttpresponse = null;
myHttpRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpRequest.Method = "POST";
myHttpRequest.ContentType = "application/x-www-form-urlencoded";
myHttpRequest.ContentLength = urinfo.Length;
StreamWriter writer = new StreamWriter(myHttprequest.GetRequestStream());
writer.Write(urinfo);
writer.Close();
myHttpresponse = (HttpWebResponse)myHttpRequest.GetResponse();
if (myHttpresponse.StatusCode == HttpStatusCode.OK)
 {
   //Perform necessary action based on response
 }
myHttpresponse.Close(); 

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

Auto select file in Solution Explorer from its open tab

Another option is to bind 'View.TrackActivityInSolutionExplorer' to a keyboard short-cut, which is the same as 'Tools-->Options-->Projects and Solutions-->Track Active Item in Solution Explorer'

If you activate the short-cut twice the file is selected in the solution explorer, and the tracking is disabled again.

Visual Studio 2013+

There is now a feature built in to the VS2013 solution explorer called Sync with Active Document. The icon is two arrows in the solution explorer, and has the hotkey Ctrl + [, S to show the current document in the solution explorer. Does not enable the automatic setting mentioned above, and only happens once.

How to check if an array element exists?

You can use the function array_key_exists to do that.

For example,

$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }

PS : Example taken from here.

How to set space between listView Items in Android

Also one more way to increase the spacing between the list items is that you add an empty view to your adapter code by providing the layout_height attribute with the spacing you require. For e.g. in order to increase the bottom spacing between your list items add this dummy view(empty view) to the end of your list items.

<View
    android:layout_width="match_parent"
    android:layout_height="15dp"/>

So this will provide a bottom spacing of 15 dp between list view items. You can directly add this if the parent layout is LinearLayout and orientation is vertical or take appropriate steps for other layout. Hope this helps :-)

CodeIgniter 404 Page Not Found, but why?

  1. Change your controller name first letter to uppercase.
  2. Change your url same as your controller name.

e.g:

Your controller name is YourController

Your url must be:

http://example.com/index.php/YourController/method

Not be:

http://example.com/index.php/yourcontroller/method

NSCameraUsageDescription in iOS 10.0 runtime crash?

Alternatively open Info.plist as source code and add this:

<key>NSCameraUsageDescription</key>
<string>Camera usage description</string>

Repeat each row of data.frame the number of times specified in a column

Use expandRows() from the splitstackshape package:

library(splitstackshape)
expandRows(df, "freq")

Simple syntax, very fast, works on data.frame or data.table.

Result:

    var1 var2
1      a    d
2      b    e
2.1    b    e
3      c    f
3.1    c    f
3.2    c    f

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

Saving the PuTTY session logging

I always have to check my cheatsheet :-)

Step 1: right-click on the top of putty window and select 'Change settings'.

Step 2: type the name of the session and save.

That's it!. Enjoy!

Find the line number where a specific word appears with "grep"

Use grep -n to get the line number of a match.

I don't think there's a way to get grep to start on a certain line number. For that, use sed. For example, to start at line 10 and print the line number and line for matching lines, use:

sed -n '10,$ { /regex/ { =; p; } }' file

To get only the line numbers, you could use

grep -n 'regex' | sed 's/^\([0-9]\+\):.*$/\1/'

Or you could simply use sed:

sed -n '/regex/=' file

Combining the two sed commands, you get:

sed -n '10,$ { /regex/= }' file

Duplicate and rename Xcode project & associated folders

I'm using simple BASH script for renaming.

Usage: ./rename.sh oldName newName

#!/bin/sh

OLDNAME=$1
NEWNAME=$2

export LC_CTYPE=C 
export LANG=C
find . -type f ! -path ".*/.*" -exec sed -i '' -e "s/${OLDNAME}/${NEWNAME}/g" {} +

mv "${OLDNAME}.xcodeproj" "${NEWNAME}.xcodeproj"
mv "${OLDNAME}" "${NEWNAME}"

Notes:

  1. This script will ignore all files like .git and .DS_Store
  2. Will not work if old name/new name contains spaces
  3. May not work if you use pods (not tested)
  4. Scheme name will not be changed (anyway project runs and compiles normally)

What's the best way to add a drop shadow to my UIView

You can set shadow to your view from storyboard also

enter image description here

Socket accept - "Too many open files"

I had this problem too. You have a file handle leak. You can debug this by printing out a list of all the open file handles (on POSIX systems):

void showFDInfo()
{
   s32 numHandles = getdtablesize();

   for ( s32 i = 0; i < numHandles; i++ )
   {
      s32 fd_flags = fcntl( i, F_GETFD ); 
      if ( fd_flags == -1 ) continue;


      showFDInfo( i );
   }
}

void showFDInfo( s32 fd )
{
   char buf[256];

   s32 fd_flags = fcntl( fd, F_GETFD ); 
   if ( fd_flags == -1 ) return;

   s32 fl_flags = fcntl( fd, F_GETFL ); 
   if ( fl_flags == -1 ) return;

   char path[256];
   sprintf( path, "/proc/self/fd/%d", fd );

   memset( &buf[0], 0, 256 );
   ssize_t s = readlink( path, &buf[0], 256 );
   if ( s == -1 )
   {
        cerr << " (" << path << "): " << "not available";
        return;
   }
   cerr << fd << " (" << buf << "): ";

   if ( fd_flags & FD_CLOEXEC )  cerr << "cloexec ";

   // file status
   if ( fl_flags & O_APPEND   )  cerr << "append ";
   if ( fl_flags & O_NONBLOCK )  cerr << "nonblock ";

   // acc mode
   if ( fl_flags & O_RDONLY   )  cerr << "read-only ";
   if ( fl_flags & O_RDWR     )  cerr << "read-write ";
   if ( fl_flags & O_WRONLY   )  cerr << "write-only ";

   if ( fl_flags & O_DSYNC    )  cerr << "dsync ";
   if ( fl_flags & O_RSYNC    )  cerr << "rsync ";
   if ( fl_flags & O_SYNC     )  cerr << "sync ";

   struct flock fl;
   fl.l_type = F_WRLCK;
   fl.l_whence = 0;
   fl.l_start = 0;
   fl.l_len = 0;
   fcntl( fd, F_GETLK, &fl );
   if ( fl.l_type != F_UNLCK )
   {
      if ( fl.l_type == F_WRLCK )
         cerr << "write-locked";
      else
         cerr << "read-locked";
      cerr << "(pid:" << fl.l_pid << ") ";
   }
}

By dumping out all the open files you will quickly figure out where your file handle leak is.

If your server spawns subprocesses. E.g. if this is a 'fork' style server, or if you are spawning other processes ( e.g. via cgi ), you have to make sure to create your file handles with "cloexec" - both for real files and also sockets.

Without cloexec, every time you fork or spawn, all open file handles are cloned in the child process.

It is also really easy to fail to close network sockets - e.g. just abandoning them when the remote party disconnects. This will leak handles like crazy.

python - if not in list

You better do this syntax

if not (item in mylist):  
    Code inside the if

Python object deleting itself

I think I've finally got it!
NOTE: You should not use this in normal code, but it is possible. This is only meant as a curiosity, see other answers for real-world solutions to this problem.


Take a look at this code:

# NOTE: This is Python 3 code, it should work with python 2, but I haven't tested it.
import weakref

class InsaneClass(object):
    _alive = []
    def __new__(cls):
        self = super().__new__(cls)
        InsaneClass._alive.append(self)

        return weakref.proxy(self)

    def commit_suicide(self):
        self._alive.remove(self)

instance = InsaneClass()
instance.commit_suicide()
print(instance)

# Raises Error: ReferenceError: weakly-referenced object no longer exists

When the object is created in the __new__ method, the instance is replaced by a weak reference proxy and the only strong reference is kept in the _alive class attribute.

What is a weak-reference?

Weak-reference is a reference which does not count as a reference when the garbage collector collects the object. Consider this example:

>>> class Test(): pass

>>> a = Test()
>>> b = Test()

>>> c = a
>>> d = weakref.proxy(b)
>>> d
<weakproxy at 0x10671ae58 to Test at 0x10670f4e0> 
# The weak reference points to the Test() object

>>> del a
>>> c
<__main__.Test object at 0x10670f390> # c still exists

>>> del b
>>> d
<weakproxy at 0x10671ab38 to NoneType at 0x1002050d0> 
# d is now only a weak-reference to None. The Test() instance was garbage-collected

So the only strong reference to the instance is stored in the _alive class attribute. And when the commit_suicide() method removes the reference the instance is garbage-collected.

Div table-cell vertical align not working

This is how I do it:

CSS:

html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table
}
#content {
    display: table-cell;
    text-align: center;
    vertical-align: middle
}

HTML:

<div id="content">
    Content goes here
</div>

See

Example of vertical centering

and

CSS: centering things.

What is the syntax for adding an element to a scala.collection.mutable.Map?

var map:Map[String, String] = Map()

var map1 = map + ("red" -> "#FF0000")

println(map1)

VBA Check if variable is empty

To check if a Variant is Null, you need to do it like:

Isnull(myvar) = True

or

Not Isnull(myvar)

window.location.href and window.open () methods in JavaScript

window.location.href is not a method, it's a property that will tell you the current URL location of the browser. Changing the value of the property will redirect the page.

window.open() is a method that you can pass a URL to that you want to open in a new window. For example:

window.location.href example:

window.location.href = 'http://www.google.com'; //Will take you to Google.

window.open() example:

window.open('http://www.google.com'); //This will open Google in a new window.

Additional Information:

window.open() can be passed additional parameters. See: window.open tutorial

Adding a month to a date in T SQL

DateAdd(m,1,reference_dt)

will add a month to the column value

How to Execute SQL Script File in Java?

If you use Spring you can use DataSourceInitializer:

@Bean
public DataSourceInitializer dataSourceInitializer(@Qualifier("dataSource") final DataSource dataSource) {
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("/data.sql"));
    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
    dataSourceInitializer.setDataSource(dataSource);
    dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
    return dataSourceInitializer;
}

Used to set up a database during initialization and clean up a database during destruction.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/init/DataSourceInitializer.html

Practical uses for AtomicInteger

I usually use AtomicInteger when I need to give Ids to objects that can be accesed or created from multiple threads, and i usually use it as an static attribute on the class that i access in the constructor of the objects.

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

How to work on UAC when installing XAMPP

Basically there's three things you can do

  1. Ensure that your user account has administrator privilege.
  2. Disable User Account Control (UAC).
  3. Install in C://xampp.

I've just writen an answer to a very similar answer here where I explain how you can disable UAC since Windows 8.

Predicate Delegates in C#

What is Predicate Delegate?

1) Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework. 2) It is being used with lambda expression (=>). It takes generic type as an argument. 3) It allows a predicate function to be defined and passed as a parameter to another function. 4) It is a special case of a Func, in that it takes only a single parameter and always returns a bool.

In C# namespace:

namespace System
{   
    public delegate bool Predicate<in T>(T obj);
}

It is defined in the System namespace.

Where should we use Predicate Delegate?

We should use Predicate Delegate in the following cases:

1) For searching items in a generic collection. e.g.

var employeeDetails = employees.Where(o=>o.employeeId == 1237).FirstOrDefault();

2) Basic example that shortens the code and returns true or false:

Predicate<int> isValueOne = x => x == 1;

now, Call above predicate:

Console.WriteLine(isValueOne.Invoke(1)); // -- returns true.

3) An anonymous method can also be assigned to a Predicate delegate type as below:

Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
    bool result = isUpper("Hello Chap!!");

Any best practices about predicates?

Use Func, Lambda Expressions and Delegates instead of Predicates.

SQL Server: converting UniqueIdentifier to string in a case statement

I think I found the answer:

convert(nvarchar(50), RequestID)

Here's the link where I found this info:

http://msdn.microsoft.com/en-us/library/ms187928.aspx

align right in a table cell with CSS

Don't forget about CSS3's 'nth-child' selector. If you know the index of the column you wish to align text to the right on, you can just specify

table tr td:nth-child(2) {
    text-align: right;
}

In cases with large tables this can save you a lot of extra markup!

here's a fiddle for ya.... https://jsfiddle.net/w16c2nad/

React this.setState is not a function

Now ES6 have arrow function it really helpful if you really confuse with bind(this) expression you can try arrow function

This is how I do.

componentWillMount() {
        ListApi.getList()
            .then(JsonList => this.setState({ List: JsonList }));
    }

 //Above method equalent to this...
     componentWillMount() {
         ListApi.getList()
             .then(function (JsonList) {
                 this.setState({ List: JsonList });
             }.bind(this));
 }

extract the date part from DateTime in C#

you can use a formatstring

DateTime time = DateTime.Now;              
String format = "MMM ddd d HH:mm yyyy";     
Console.WriteLine(time.ToString(format));

@Autowired and static method

Use AppContext. Make sure you create a bean in your context file.

private final static Foo foo = AppContext.getApplicationContext().getBean(Foo.class);

public static void randomMethod() {
     foo.doStuff();
}

Checking during array iteration, if the current element is the last element

I know this is old, and using SPL iterator maybe just an overkill, but anyway, another solution here:

$ary = array(1, 2, 3, 4, 'last');
$ary = new ArrayIterator($ary);
$ary = new CachingIterator($ary);
foreach ($ary as $each) {
    if (!$ary->hasNext()) { // we chain ArrayIterator and CachingIterator
                            // just to use this `hasNext()` method to see
                            // if this is the last element
       echo $each;
    }
}

Angular - How to apply [ngStyle] conditions

[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"

How to bind Events on Ajax loaded Content?

For ASP.NET try this:

<script type="text/javascript">
    Sys.Application.add_load(function() { ... });
</script>

This appears to work on page load and on update panel load

Please find the full discussion here.

Checking if a folder exists (and creating folders) in Qt, C++

To both check if it exists and create if it doesn't, including intermediaries:

QDir dir("path/to/dir");
if (!dir.exists())
    dir.mkpath(".");

Initialising a multidimensional array in Java

 int[][] myNums = { {1, 2, 3, 4, 5, 6, 7}, {5, 6, 7, 8, 9, 10, 11} };
 for (int x = 0; x < myNums.length; ++x) {
    for(int y = 0; y < myNums[i].length; ++y) {
       System.out.print(myNums[x][y]);
    }
 }

Output

1 2 3 4 5 6 7 5 6 7 8 9 10 11

Wait for page load in Selenium

Use this function

public void waitForPageLoad(ChromeDriver d){
        String s="";
        while(!s.equals("complete")){
        s=(String) d.executeScript("return document.readyState");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }

    }

What's the best way of scraping data from a website?

You will definitely want to start with a good web scraping framework. Later on you may decide that they are too limiting and you can put together your own stack of libraries but without a lot of scraping experience your design will be much worse than pjscrape or scrapy.

Note: I use the terms crawling and scraping basically interchangeable here. This is a copy of my answer to your Quora question, it's pretty long.

Tools

Get very familiar with either Firebug or Chrome dev tools depending on your preferred browser. This will be absolutely necessary as you browse the site you are pulling data from and map out which urls contain the data you are looking for and what data formats make up the responses.

You will need a good working knowledge of HTTP as well as HTML and will probably want to find a decent piece of man in the middle proxy software. You will need to be able to inspect HTTP requests and responses and understand how the cookies and session information and query parameters are being passed around. Fiddler (http://www.telerik.com/fiddler) and Charles Proxy (http://www.charlesproxy.com/) are popular tools. I use mitmproxy (http://mitmproxy.org/) a lot as I'm more of a keyboard guy than a mouse guy.

Some kind of console/shell/REPL type environment where you can try out various pieces of code with instant feedback will be invaluable. Reverse engineering tasks like this are a lot of trial and error so you will want a workflow that makes this easy.

Language

PHP is basically out, it's not well suited for this task and the library/framework support is poor in this area. Python (Scrapy is a great starting point) and Clojure/Clojurescript (incredibly powerful and productive but a big learning curve) are great languages for this problem. Since you would rather not learn a new language and you already know Javascript I would definitely suggest sticking with JS. I have not used pjscrape but it looks quite good from a quick read of their docs. It's well suited and implements an excellent solution to the problem I describe below.

A note on Regular expressions: DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML. A lot of beginners do this because they are already familiar with regexes. It's a huge mistake, use xpath or css selectors to navigate html and only use regular expressions to extract data from actual text inside an html node. This might already be obvious to you, it becomes obvious quickly if you try it but a lot of people waste a lot of time going down this road for some reason. Don't be scared of xpath or css selectors, they are WAY easier to learn than regexes and they were designed to solve this exact problem.

Javascript-heavy sites

In the old days you just had to make an http request and parse the HTML reponse. Now you will almost certainly have to deal with sites that are a mix of standard HTML HTTP request/responses and asynchronous HTTP calls made by the javascript portion of the target site. This is where your proxy software and the network tab of firebug/devtools comes in very handy. The responses to these might be html or they might be json, in rare cases they will be xml or something else.

There are two approaches to this problem:

The low level approach:

You can figure out what ajax urls the site javascript is calling and what those responses look like and make those same requests yourself. So you might pull the html from http://example.com/foobar and extract one piece of data and then have to pull the json response from http://example.com/api/baz?foo=b... to get the other piece of data. You'll need to be aware of passing the correct cookies or session parameters. It's very rare, but occasionally some required parameters for an ajax call will be the result of some crazy calculation done in the site's javascript, reverse engineering this can be annoying.

The embedded browser approach:

Why do you need to work out what data is in html and what data comes in from an ajax call? Managing all that session and cookie data? You don't have to when you browse a site, the browser and the site javascript do that. That's the whole point.

If you just load the page into a headless browser engine like phantomjs it will load the page, run the javascript and tell you when all the ajax calls have completed. You can inject your own javascript if necessary to trigger the appropriate clicks or whatever is necessary to trigger the site javascript to load the appropriate data.

You now have two options, get it to spit out the finished html and parse it or inject some javascript into the page that does your parsing and data formatting and spits the data out (probably in json format). You can freely mix these two options as well.

Which approach is best?

That depends, you will need to be familiar and comfortable with the low level approach for sure. The embedded browser approach works for anything, it will be much easier to implement and will make some of the trickiest problems in scraping disappear. It's also quite a complex piece of machinery that you will need to understand. It's not just HTTP requests and responses, it's requests, embedded browser rendering, site javascript, injected javascript, your own code and 2-way interaction with the embedded browser process.

The embedded browser is also much slower at scale because of the rendering overhead but that will almost certainly not matter unless you are scraping a lot of different domains. Your need to rate limit your requests will make the rendering time completely negligible in the case of a single domain.

Rate Limiting/Bot behaviour

You need to be very aware of this. You need to make requests to your target domains at a reasonable rate. You need to write a well behaved bot when crawling websites, and that means respecting robots.txt and not hammering the server with requests. Mistakes or negligence here is very unethical since this can be considered a denial of service attack. The acceptable rate varies depending on who you ask, 1req/s is the max that the Google crawler runs at but you are not Google and you probably aren't as welcome as Google. Keep it as slow as reasonable. I would suggest 2-5 seconds between each page request.

Identify your requests with a user agent string that identifies your bot and have a webpage for your bot explaining it's purpose. This url goes in the agent string.

You will be easy to block if the site wants to block you. A smart engineer on their end can easily identify bots and a few minutes of work on their end can cause weeks of work changing your scraping code on your end or just make it impossible. If the relationship is antagonistic then a smart engineer at the target site can completely stymie a genius engineer writing a crawler. Scraping code is inherently fragile and this is easily exploited. Something that would provoke this response is almost certainly unethical anyway, so write a well behaved bot and don't worry about this.

Testing

Not a unit/integration test person? Too bad. You will now have to become one. Sites change frequently and you will be changing your code frequently. This is a large part of the challenge.

There are a lot of moving parts involved in scraping a modern website, good test practices will help a lot. Many of the bugs you will encounter while writing this type of code will be the type that just return corrupted data silently. Without good tests to check for regressions you will find out that you've been saving useless corrupted data to your database for a while without noticing. This project will make you very familiar with data validation (find some good libraries to use) and testing. There are not many other problems that combine requiring comprehensive tests and being very difficult to test.

The second part of your tests involve caching and change detection. While writing your code you don't want to be hammering the server for the same page over and over again for no reason. While running your unit tests you want to know if your tests are failing because you broke your code or because the website has been redesigned. Run your unit tests against a cached copy of the urls involved. A caching proxy is very useful here but tricky to configure and use properly.

You also do want to know if the site has changed. If they redesigned the site and your crawler is broken your unit tests will still pass because they are running against a cached copy! You will need either another, smaller set of integration tests that are run infrequently against the live site or good logging and error detection in your crawling code that logs the exact issues, alerts you to the problem and stops crawling. Now you can update your cache, run your unit tests and see what you need to change.

Legal Issues

The law here can be slightly dangerous if you do stupid things. If the law gets involved you are dealing with people who regularly refer to wget and curl as "hacking tools". You don't want this.

The ethical reality of the situation is that there is no difference between using browser software to request a url and look at some data and using your own software to request a url and look at some data. Google is the largest scraping company in the world and they are loved for it. Identifying your bots name in the user agent and being open about the goals and intentions of your web crawler will help here as the law understands what Google is. If you are doing anything shady, like creating fake user accounts or accessing areas of the site that you shouldn't (either "blocked" by robots.txt or because of some kind of authorization exploit) then be aware that you are doing something unethical and the law's ignorance of technology will be extraordinarily dangerous here. It's a ridiculous situation but it's a real one.

It's literally possible to try and build a new search engine on the up and up as an upstanding citizen, make a mistake or have a bug in your software and be seen as a hacker. Not something you want considering the current political reality.

Who am I to write this giant wall of text anyway?

I've written a lot of web crawling related code in my life. I've been doing web related software development for more than a decade as a consultant, employee and startup founder. The early days were writing perl crawlers/scrapers and php websites. When we were embedding hidden iframes loading csv data into webpages to do ajax before Jesse James Garrett named it ajax, before XMLHTTPRequest was an idea. Before jQuery, before json. I'm in my mid-30's, that's apparently considered ancient for this business.

I've written large scale crawling/scraping systems twice, once for a large team at a media company (in Perl) and recently for a small team as the CTO of a search engine startup (in Python/Javascript). I currently work as a consultant, mostly coding in Clojure/Clojurescript (a wonderful expert language in general and has libraries that make crawler/scraper problems a delight)

I've written successful anti-crawling software systems as well. It's remarkably easy to write nigh-unscrapable sites if you want to or to identify and sabotage bots you don't like.

I like writing crawlers, scrapers and parsers more than any other type of software. It's challenging, fun and can be used to create amazing things.

Change border-bottom color using jquery?

$("selector").css("border-bottom-color", "#fff");
  1. construct your jQuery object which provides callable methods first. In this case, say you got an #mydiv, then $("#mydiv")
  2. call the .css() method provided by jQuery to modify specified object's css property values.

Moment JS - check if a date is today or in the future

If you only need to know which one is bigger, you can also compare them directly:

var SpecialToDate = '31/01/2014'; // DD/MM/YYYY

var SpecialTo = moment(SpecialToDate, "DD/MM/YYYY");
if (moment() > SpecialTo) {
    alert('date is today or in future');
} else {
    alert('date is in the past');
}

Hope this helps!

Initialize static variables in C++ class?

Optionally, move all your constants to .cpp file without declaration in .h file. Use anonymous namespace to make them invisible beyond the cpp module.

// MyClass.cpp

#include "MyClass.h"

// anonymous namespace
namespace
{
    string RE_ANY = "([^\\n]*)";
    string RE_ANY_RELUCTANT = "([^\\n]*?)";
}

// member function (static or not)
bool MyClass::foo()
{
    // logic that uses constants
    return RE_ANY_RELUCTANT.size() > 0;
}

c# dictionary How to add multiple values for single key?

When you add a string, do it differently depending on whether the key exists already or not. To add the string value for the key key:

List<string> list;
if (dictionary.ContainsKey(key)) {
  list = dictionary[key];
} else {
  list = new List<string>();
  dictionary.Add(ley, list);
}
list.Add(value);

How to change line color in EditText

drawable/bg_edittext.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>

    <item
        android:left="-2dp"
        android:right="-2dp"
        android:top="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="1dp"
                android:color="@color/colorDivider" />
        </shape>
    </item>
</layer-list>

Set to EditText

<android.support.v7.widget.AppCompatEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_edittext"/>

Import-CSV and Foreach

$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
    $IP
}

Get-content Filename returns an array of strings for each line.

On the first string only, I split it based on ",". Dumping it into $IP_Array.

$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
  if ($IP -eq "2.2.2.2") {
    Write-Host "Found $IP"
  }
}