Programs & Examples On #Cue

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.

The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.

Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.


  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.

Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.

Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

How to increase Bootstrap Modal Width?

In my case,

  1. Giving a static width to the modal hurts the responsiveness.
  2. The modal-lg class was not wide enough.

so the solution was

@media (min-width: 1200px) {
   .modal-xlg {
      width: 90%; 

and use the above class instead of modal-lg class


There is another scenario where this issue reproduces (as in my case). When THE CLIENT REQUEST doesn't contain the right extension on the url, the controller can't identify the desired result format.

For example: the controller is set to respond_to :json (as a single option, without a HTML response)- while the client call is set to /reservations instead of /reservations.json.

Bottom line, change the client call to /reservations.json.

How to vertically align text with icon font?

You can use this property : vertical-align:middle;

.selector-class { 

Package doesn't exist error in intelliJ

Tried all the above approaches, didn't work. Finally running maven clean install solved it!

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

File to import not found or unreadable: compass

Compass adjusts the way partials are imported. It allows importing components based solely on their name, without specifying the path.

Before you can do @import 'compass';, you should:

Install Compass as a Ruby gem:

gem install compass

After that, you should use Compass's own command line tool to compile your SASS code:

cd path/to/your/project/
compass compile

Note that Compass reqiures a configuration file called config.rb. You should create it for Compass to work.

The minimal config.rb can be as simple as this:

css_dir =   "css"
sass_dir =  "sass"

And your SASS code should reside in sass/.

Instead of creating a configuration file manually, you can create an empty Compass project with compass create <project-name> and then copy your SASS code inside it.

Note that if you want to use Compass extensions, you will have to:

  1. require them from the config.rb;
  2. import them from your SASS file.

More info here:

Postgres could not connect to server

For me it was an apache upgrade that caused the problem. I could still run psql in console or call db directly from kdevelop. Also it worked to add "host=localhost" to connection string.

BUT the real problem was that apache had changed to private tmp.

Solution: Update /usr/lib/systemd/system/apache2.service and change PrivateTmp=true to PrivateTmp=false.

I am working on OpenSuse OS, but I guess that something similar could happen on Mac.

The requested resource does not support HTTP method 'GET'

just use this attribute


not need this line of code:

[System.Web.Http.AcceptVerbs("GET", "POST")]

Why is it bad style to `rescue Exception => e` in Ruby?

This blog post explains it perfectly: Ruby's Exception vs StandardError: What's the difference?

Why you shouldn't rescue Exception

The problem with rescuing Exception is that it actually rescues every exception that inherits from Exception. Which is....all of them!

That's a problem because there are some exceptions that are used internally by Ruby. They don't have anything to do with your app, and swallowing them will cause bad things to happen.

Here are a few of the big ones:

  • SignalException::Interrupt - If you rescue this, you can't exit your app by hitting control-c.

  • ScriptError::SyntaxError - Swallowing syntax errors means that things like puts("Forgot something) will fail silently.

  • NoMemoryError - Wanna know what happens when your program keeps running after it uses up all the RAM? Me neither.

rescue Exception => e
  # Don't do this. This will swallow every single exception. Nothing gets past it. 

I'm guessing that you don't really want to swallow any of these system-level exceptions. You only want to catch all of your application level errors. The exceptions caused YOUR code.

Luckily, there's an easy way to to this.

Rescue StandardError Instead

All of the exceptions that you should care about inherit from StandardError. These are our old friends:

NoMethodError - raised when you try to invoke a method that doesn't exist

TypeError - caused by things like 1 + ""

RuntimeError - who could forget good old RuntimeError?

To rescue errors like these, you'll want to rescue StandardError. You COULD do it by writing something like this:

rescue StandardError => e
  # Only your app's exceptions are swallowed. Things like SyntaxErrror are left alone. 

But Ruby has made it much easier for use.

When you don't specify an exception class at all, ruby assumes you mean StandardError. So the code below is identical to the above code:

rescue => e
  # This is the same as rescuing StandardError

sudo: port: command not found

On my machine, port is in /opt/local/bin/port - try typing that into a terminal on its own.

Target a css class inside another css class

I use div instead of tables and am able to target classes within the main class, as below:


.main {
    .width: 800px;
    .margin: 0 auto;
    .text-align: center;
.main .table {
    width: 80%;
.main .row {
   / ***something ***/
.main .column {
    font-size: 14px;
    display: inline-block;
.main .left {
    width: 140px;
    margin-right: 5px;
    font-size: 12px;
.main .right {
    width: auto;
    margin-right: 20px;
    color: #fff;
    font-size: 13px;
    font-weight: normal;


<div class="main">
    <div class="table">
        <div class="row">
            <div class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>

If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:

.main #red { color: red; }

<div class="main">
    <div class="table">
        <div class="row">
            <div id="red" class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

Another good way of dealing with Lion's hidden scroll bars is to display a prompt to scroll down. It doesn't work with small scroll areas such as text fields but well with large scroll areas and keeps the overall style of the site. One site doing this is, just check this example page and wait 1.5 seconds to see the prompt:

The implementation isn't hard but you have to take care, that you don't display the prompt when the user has already scrolled.

You need jQuery + Underscore and

$(window).scroll to check if the user already scrolled by himself,

_.delay() to trigger a delay before you display the prompt -- the prompt shouldn't be to obtrusive

$('#prompt_div').fadeIn('slow') to fade in your prompt and of course

$('#prompt_div').fadeOut('slow') to fade out when the user scrolled after he saw the prompt

In addition, you can bind Google Analytics events to track user's scrolling behavior.

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

Importing a function from a class in another file?

You can use the below syntax -

from FolderName.FileName import Classname

Test if string is a number in Ruby on Rails

In rails 4, you need to put require File.expand_path('../../lib', __FILE__) + '/ext/string' in your config/application.rb

incompatible character encodings: ASCII-8BIT and UTF-8

I solved it by following these steps:

  • Make sure config.encoding = "utf-8" is in the application.rb file.
  • Make sure you are using the 'mysql2' gem.
  • Put # encoding: utf-8 at the top of file containing UTF-8 characters.
  • Above the <App Name>::Application.initialize! line in the environment.rb file, add following two lines:

    Encoding.default_external = Encoding::UTF_8
    Encoding.default_internal = Encoding::UTF_8

Begin, Rescue and Ensure in Ruby?

FYI, even if an exception is re-raised in the rescue section, the ensure block will be executed before the code execution continues to the next exception handler. For instance:

  raise "Error!!"
  puts "test1"
  raise # Reraise exception
  puts "Ensure block"

How to break out from a ruby block?

next and break seem to do the correct thing in this simplified example!

class Bar
  def self.do_things
      Foo.some_method(1..10) do |x|
            next if x == 2
            break if x == 9
            print "#{x} "

class Foo
    def self.some_method(targets, &block)
      targets.each do |target|
          r = yield(target)
        rescue  => x
          puts "rescue #{x}"


output: 1 3 4 5 6 7 8

Is there a Visual Basic 6 decompiler?

For the final, compiled code of your application, the short answer is “no”. Different tools are able to extract different information from the code (e.g. the forms setups) and there are P code decompilers (see Edgar's excellent link for such tools). However, up to this day, there is no decompiler for native code. I'm not aware of anything similar for other high-level languages either.

How to find unused/dead code in java projects

CodePro was recently released by Google with the Eclipse project. It is free and highly effective. The plugin has a 'Find Dead Code' feature with one/many entry point(s). Works pretty well.

Asynchronous vs synchronous execution, what does it really mean?

When executing a sequence like: a>b>c>d>, if we get a failure in the middle of execution like:


Then we re-start from the beginning:


this is synchronous

If, however, we have the same sequence to execute: a>b>c>d>, and we have a failure in the middle:


...but instead of restarting from the beginning, we re-start from the point of failure:


...this is know as asynchronous.

Filter Linq EXCEPT on properties

ColinE's answer is simple and elegant. If your lists are larger and provided that the excluded apps list is sorted, BinarySearch<T> may prove faster than Contains.


unfilteredApps.Where(i => excludedAppIds.BinarySearch(i.Id) < 0);

Setting paper size in FPDF

/*$mpdf = new mPDF('',    // mode - default ''
 '',    // format - A4, for example, default ''
 0,     // font size - default 0
 '',    // default font family
 15,    // margin_left
 15,    // margin right
 16,     // margin top
 16,    // margin bottom
 9,     // margin header
 9,     // margin footer
 'L');  // L - landscape, P - portrait*/

How to convert any date format to yyyy-MM-dd

You can write your possible date formats in array and parse date as following:

public static void Main(string[] args)
            string dd = "12/31/2015"; //or 31/12/2015
            DateTime startDate;
            string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
                                "dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy", "MM/dd/yyyy"};
            DateTime.TryParseExact(dd, formats, 
            System.Globalization.DateTimeStyles.None, out startDate);

How to put img inline with text

Images have display: inline by default.
You might want to put the image inside the paragraph.
<p><img /></p>

How to download excel (.xls) file from API in postman?

If the endpoint really is a direct link to the .xls file, you can try the following code to handle downloading:

public static boolean download(final File output, final String source) {
    try {
        if (!output.createNewFile()) {
            throw new RuntimeException("Could not create new file!");
        URL url = new URL(source);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // Comment in the code in the following line in case the endpoint redirects instead of it being a direct link
        // connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("AUTH-KEY-PROPERTY-NAME", "yourAuthKey");
        final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        final FileOutputStream fos = new FileOutputStream(output);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        return true;
    } catch (final Exception e) {
    return false;

All you should need to do is set the proper name for the auth token and fill it in.

Example usage:

download(new File("C:\\output.xls"), "");

Adding Python Path on Windows 7

Try adding this python.bat file to System32 folder and the command line will now run python when you type in python


@C:\Python27\python.exe %*


Iterating through all nodes in XML file

This is what I quickly wrote for myself:

public static class XmlDocumentExtensions
    public static void IterateThroughAllNodes(
        this XmlDocument doc, 
        Action<XmlNode> elementVisitor)
        if (doc != null && elementVisitor != null)
            foreach (XmlNode node in doc.ChildNodes)
                doIterateNode(node, elementVisitor);

    private static void doIterateNode(
        XmlNode node, 
        Action<XmlNode> elementVisitor)

        foreach (XmlNode childNode in node.ChildNodes)
            doIterateNode(childNode, elementVisitor);

To use it, I've used something like:

var doc = new XmlDocument();

    delegate(XmlNode node)
        // ...Do something with the node...

Maybe it helps someone out there.

Xcode swift am/pm time to 24 hour format

I am using a function here in my case by which I am updating a label with the normal time format and after that I am storing the selected time's 24hr format to do some another tasks..

Here is my code...

func timeUpdate(sender: NSDate)
    let timeSave = NSDateFormatter() //Creating first object to update time label as 12hr format with AM/PM
    timeSave.timeStyle = NSDateFormatterStyle.ShortStyle //Setting the style for the time selection.
    self.TimeShowOutlet.text = timeSave.stringFromDate(sender) // Getting the string from the selected time and updating the label as 1:40 PM
    let timeCheck = NSDateFormatter() //Creating another object to store time in 24hr format.
    timeCheck.dateFormat = "HH:mm:ss" //Setting the format for the time save.
    let time = timeCheck.stringFromDate(sender) //Getting the time string as 13:40:00
    self.timeSelectedForCheckAvailability = time //At last saving the 24hr format time for further task.

After writing this function you can call this where you are choosing the time from date/time picker.

Thanks, Hope this helped.

How to import large sql file in phpmyadmin

For that you will have to edit php.ini file, If you are using the ubuntu server this is link Upload large file in phpMyAdmin might help you.

Integer to hex string in C++

You can try the following. It's working...

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

template <class T>
string to_string(T t, ios_base & (*f)(ios_base&))
  ostringstream oss;
  oss << f << t;
  return oss.str();

int main ()
  cout<<to_string<long>(123456, hex)<<endl;
  return 0;

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

You can use git checkout <file> to check out the committed version of the file (thus discarding your changes), or git reset --hard HEAD to throw away any uncommitted changes for all files.

bash: shortest way to get n-th column of output

Try the zsh. It supports suffix alias, so you can define X in your .zshrc to be

alias -g X="| cut -d' ' -f2"

then you can do:

cat file X

You can take it one step further and define it for the nth column:

alias -g X2="| cut -d' ' -f2"
alias -g X1="| cut -d' ' -f1"
alias -g X3="| cut -d' ' -f3"

which will output the nth column of file "file". You can do this for grep output or less output, too. This is very handy and a killer feature of the zsh.

You can go one step further and define D to be:

alias -g D="|xargs rm"

Now you can type:

cat file X1 D

to delete all files mentioned in the first column of file "file".

If you know the bash, the zsh is not much of a change except for some new features.

HTH Chris

indexOf Case Sensitive?

indexOf is case sensitive. This is because it uses the equals method to compare the elements in the list. The same thing goes for contains and remove.

What is the purpose of Node.js module.exports and how do you use it?

module.exports is the object that's actually returned as the result of a require call.

The exports variable is initially set to that same object (i.e. it's a shorthand "alias"), so in the module code you would usually write something like this:

let myFunc1 = function() { ... };
let myFunc2 = function() { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;

to export (or "expose") the internally scoped functions myFunc1 and myFunc2.

And in the calling code you would use:

const m = require('./mymodule');

where the last line shows how the result of require is (usually) just a plain object whose properties may be accessed.

NB: if you overwrite exports then it will no longer refer to module.exports. So if you wish to assign a new object (or a function reference) to exports then you should also assign that new object to module.exports

It's worth noting that the name added to the exports object does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:

let myVeryLongInternalName = function() { ... };
exports.shortName = myVeryLongInternalName;
// add other objects, functions, as required

followed by:

const m = require('./mymodule');
m.shortName(); // invokes module.myVeryLongInternalName

How do I add images in laravel view?

If Image folder location is public/assets/img/default.jpg. You can try in view

   <img src="{{ URL::to('/assets/img/default.jpg') }}">

Counting number of occurrences in column?


You can replace the criteria with cell references from Column B

How to split one text file into multiple *.txt files?

Using bash:

readarray -t LINES < file.txt
for I in "${!LINES[@]}"; do
    INDEX=$(( (I * 12 - 1) / COUNT + 1 ))
    echo "${LINES[I]}" >> "file${INDEX}.txt"

Using awk:

awk '{
    a[NR] = $0
    for (i = 1; i in a; ++i) {
        x = (i * 12 - 1) / NR + 1
        sub(/\..*$/, "", x)
        print a[i] > "file" x ".txt"
}' file.txt

Unlike split this one makes sure that number of lines are most even.

Installing Apple's Network Link Conditioner Tool

Update on the answer December 2019 Xcode 11.1.2

Apple has moved Network Link Conditioner Tool to additional tools for Xcode

Go to the below link

enter image description here

Install the dmg file, select hardware from installer

enter image description here

select Network Link conditioner prefpane enter image description here

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

var f = document.createElement("form");

var i = document.createElement("input"); //input element, text

var s = document.createElement("input"); //input element, Submit button


//and some more input elements here
//and dont forget to add a submit button



How do I reverse an int array in Java?

Just for the sake of it. People often do only need a 'view' on an array or list in reversed order instead of a completely do not need a reversed array when working with streams and collections but a 'reversed' view on the original array/collection. , it is best to create a toolkit that has a reverse view on a list / array.

So create your Iterator implementation that takes an array or list and provide the input.

/// Reverse Iterator
public class ReverseIterator<T> implements Iterator<T> {
  private int index;
  private final List<T> list;
  public ReverseIterator(List<T> list) {
     this.list = list;
     this.index = list.size() - 1;
  public boolean hasNext() {
    return index >= 0 ? true : false;
  public T next() {
    if(index >= 0) 
      return list.get(index--);
      throw new NoSuchElementException();

An implementation for the array situation is quite similar. Of cause an iterator can be source for a stream or a collection as well.

So not always it is best to create a new array just to provide a reverse view when all you want to do is iterating over the array / list or feed it into a stream or a new collection / array.

How to use std::sort to sort an array in C++

C++ sorting using sort function

#include <bits/stdc++.h>
 using namespace std;

vector <int> v[100];

int main()
  sort(v.begin(), v.end());

why should I make a copy of a data frame in pandas

This expands on Paul's answer. In Pandas, indexing a DataFrame returns a reference to the initial DataFrame. Thus, changing the subset will change the initial DataFrame. Thus, you'd want to use the copy if you want to make sure the initial DataFrame shouldn't change. Consider the following code:

df = DataFrame({'x': [1,2]})
df_sub = df[0:1]
df_sub.x = -1

You'll get:

0 -1
1  2

In contrast, the following leaves df unchanged:

df_sub_copy = df[0:1].copy()
df_sub_copy.x = -1

BLOB to String, SQL Server

Can you try this:

select convert(nvarchar(max),convert(varbinary(max),blob_column)) from table_name

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine


How to copy to clipboard using Access/VBA?

I couldn't figure out how to use the API using the first Google results. Fortunately a thread somewhere pointed me to this link:

Which works nicely. :)

Run PowerShell command from command prompt (no ps1 script)

This works from my Windows 10's cmd.exe prompt

powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"

This example shows

  1. how to chain multiple commands
  2. how to import module with module path
  3. how to run a function defined in the module
  4. No need for those fancy "&".

Usage of __slots__?

You have — essentially — no use for __slots__.

For the time when you think you might need __slots__, you actually want to use Lightweight or Flyweight design patterns. These are cases when you no longer want to use purely Python objects. Instead, you want a Python object-like wrapper around an array, struct, or numpy array.

class Flyweight(object):

    def get(self, theData, index):
        return theData[index]

    def set(self, theData, index, value):
        theData[index]= value

The class-like wrapper has no attributes — it just provides methods that act on the underlying data. The methods can be reduced to class methods. Indeed, it could be reduced to just functions operating on the underlying array of data.

Git: add vs push vs commit

  1. git add adds your modified files to the queue to be committed later. Files are not committed

  2. git commit commits the files that have been added and creates a new revision with a log... If you do not add any files, git will not commit anything. You can combine both actions with git commit -a

  3. git push pushes your changes to the remote repository.

This figure from this git cheat sheet gives a good idea of the work flow

enter image description here

git add isn't on the figure because the suggested way to commit is the combined git commit -a, but you can mentally add a git add to the change block to understand the flow.

Lastly, the reason why push is a separate command is because of git's philosophy. git is a distributed versioning system, and your local working directory is your repository! All changes you commit are instantly reflected and recorded. push is only used to update the remote repo (which you might share with others) when you're done with whatever it is that you're working on. This is a neat way to work and save changes locally (without network overhead) and update it only when you want to, instead of at every commit. This indirectly results in easier commits/branching etc (why not, right? what does it cost you?) which leads to more save points, without messing with the repository.

How to change text color and console color in code::blocks?

textcolor function is no longer supported in the latest compilers.

This the simplest way to change text color in Code Blocks. You can use system function.

To change Text Color :

#include<stdlib.h> //as system function is in the standard library

int main()        
          system("color 1"); //here 1 represents the text color
          printf("This is dummy program for text color");
          return 0;

If you want to change both the text color & console color you just need to add another color code in system function

To change Text Color & Console Color :

system("color 41"); //here 4 represents the console color and 1 represents the text color

N.B: Don't use spaces between color code like these

system("color 4 1");

Though if you do it Code Block will show all the color codes. You can use this tricks to know all supported color codes.

How do I rotate a picture in WinForms

I found this article

  /// <summary>
    /// Creates a new Image containing the same image only rotated
    /// </summary>
    /// <param name=""image"">The <see cref=""System.Drawing.Image"/"> to rotate
    /// <param name=""offset"">The position to rotate from.
    /// <param name=""angle"">The amount to rotate the image, clockwise, in degrees
    /// <returns>A new <see cref=""System.Drawing.Bitmap"/"> of the same size rotated.</see>
    /// <exception cref=""System.ArgumentNullException"">Thrown if <see cref=""image"/"> 
    /// is null.</see>
    public static Bitmap RotateImage(Image image, PointF offset, float angle)
        if (image == null)
            throw new ArgumentNullException("image");

        //create a new empty bitmap to hold rotated image
        Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
        rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);

        //make a graphics object from the empty bitmap
        Graphics g = Graphics.FromImage(rotatedBmp);

        //Put the rotation point in the center of the image
        g.TranslateTransform(offset.X, offset.Y);

        //rotate the image

        //move the image back
        g.TranslateTransform(-offset.X, -offset.Y);

        //draw passed in image onto graphics object
        g.DrawImage(image, new PointF(0, 0));

        return rotatedBmp;

node.js require all files in a folder?

I have a folder /fields full of files with a single class each, ex:

fields/Text.js -> Test class
fields/Checkbox.js -> Checkbox class

Drop this in fields/index.js to export each class:

var collectExports, fs, path,
  __hasProp = {}.hasOwnProperty;

fs = require('fs');    
path = require('path');

collectExports = function(file) {
  var func, include, _results;

  if (path.extname(file) === '.js' && file !== 'index.js') {
    include = require('./' + file);
    _results = [];
    for (func in include) {
      if (!, func)) continue;
      _results.push(exports[func] = include[func]);
    return _results;


This makes the modules act more like they would in Python:

var text = new Fields.Text()
var checkbox = new Fields.Checkbox()

Can Android Studio be used to run standard Java projects?

on Android Studio 4.0 and above, you will get an option readily on the IDE,a green run icon to run the related main() class.

enter image description here

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

If the WAMP icon is Orange then one of the services has not started.

In your case it looks like MySQL has not started as you are getting the message that indicates there is no server running and therefore listening for requests.

Look at the mysql log and if that tells you nothing look at the Windows event log, in the Windows -> Applications section. Error messages in there are pretty good at identifying the cause of MySQL failing to start.

Sometimes this is caused by a my.ini file from another install being picked up by WAMPServers MySQL, normally in the \windows or \windows\system32 folders. Do a search for 'my.ini' and 'my.cnf' and if you find one of these anywhere outside of the \wamp.... folder structure then delete it, or at least rename it so it wont be found. Then restart the MySQL service.

Best way to create unique token in Rails?

This might be a late response but in order to avoid using a loop you can also call the method recursively. It looks and feels slightly cleaner to me.

class ModelName < ActiveRecord::Base

  before_create :generate_token


  def generate_token
    self.token = SecureRandom.urlsafe_base64
    generate_token if ModelName.exists?(token: self.token)


What is the Simplest Way to Reverse an ArrayList?

Solution without using extra ArrayList or combination of add() and remove() methods. Both can have negative impact if you have to reverse a huge list.

 public ArrayList<Object> reverse(ArrayList<Object> list) {

   for (int i = 0; i < list.size() / 2; i++) {
     Object temp = list.get(i);
     list.set(i, list.get(list.size() - i - 1));
     list.set(list.size() - i - 1, temp);

   return list;

In PHP, how do you change the key of an array element?

The way you would do this and preserve the ordering of the array is by putting the array keys into a separate array, find and replace the key in that array and then combine it back with the values.

Here is a function that does just that:

function change_key( $array, $old_key, $new_key ) {

    if( ! array_key_exists( $old_key, $array ) )
        return $array;

    $keys = array_keys( $array );
    $keys[ array_search( $old_key, $keys ) ] = $new_key;

    return array_combine( $keys, $array );

How can I get zoom functionality for images?

Try using ZoomView for zooming any other view. it's easy, free and fun to use!

Create an array of strings

You can create a character array that does this via a loop:

>> for i=1:10
Names(i,:)='Sample Text';
>> Names

Names =

Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text

However, this would be better implemented using REPMAT:

>> Names = repmat('Sample Text', 10, 1)

Names =

Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text

Text overflow ellipsis on two lines

This is a total hack, but it works:

div {
    width: 30%;
    float: left;
    margin-right: 2%;
    height: 94px;
    overflow: hidden;
    position: relative;

div:after {
     display: block;
      content: '...';
      width: 1em;
  height: 1.5em;
  background: #fff;
  position: absolute;
  bottom: -6px;
  right: 0;

It does have problems.... it might cut off a letter awkwardly, and it will probably have some weird results on a responsive site.

How do I convert a datetime to date?

import time
import datetime

# use mktime to step by one day
# end - the last day, numdays - count of days to step back
def gen_dates_list(end, numdays):
  start = end - datetime.timedelta(days=numdays+1)
  end   = int(time.mktime(end.timetuple()))
  start = int(time.mktime(start.timetuple()))
  # 86400 s = 1 day
  return xrange(start, end, 86400)

# if you need reverse the list of dates
for dt in reversed(gen_dates_list(, 100)):
    print datetime.datetime.fromtimestamp(dt).date()

Appending items to a list of lists in python

Python lists are mutable objects and here:

plot_data = [[]] * len(positions) 

you are repeating the same list len(positions) times.

>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]

Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.

If you want different lists, you can do this way:

plot_data = [[] for _ in positions]

for example:

>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]

Excel: Search for a list of strings within a particular string using array formulas?

Adding this answer for people like me for whom a TRUE/FALSE answer is perfectly acceptable


or case-sensitive


Where the range for the search terms is G1:G7

Remember to press CTRL+SHIFT+ENTER

Session 'app': Error Installing APK

Uninstall the app, and re-install and it should work!

Unsuccessful append to an empty NumPy array

I might understand the question incorrectly, but if you want to declare an array of a certain shape but with nothing inside, the following might be helpful:

Initialise empty array:

>>> a = np.zeros((0,3)) #or np.empty((0,3)) or np.array([]).reshape(0,3)
>>> a
array([], shape=(0, 3), dtype=float64)

Now you can use this array to append rows of similar shape to it. Remember that a numpy array is immutable, so a new array is created for each iteration:

>>> for i in range(3):
...     a = np.vstack([a, [i,i,i]])
>>> a
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.],
       [ 2.,  2.,  2.]])

np.vstack and np.hstack is the most common method for combining numpy arrays, but coming from Matlab I prefer np.r_ and np.c_:

Concatenate 1d:

>>> a = np.zeros(0)
>>> for i in range(3):
...     a = np.r_[a, [i, i, i]]
>>> a
array([ 0.,  0.,  0.,  1.,  1.,  1.,  2.,  2.,  2.])

Concatenate rows:

>>> a = np.zeros((0,3))
>>> for i in range(3):
...     a = np.r_[a, [[i,i,i]]]
>>> a
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.],
       [ 2.,  2.,  2.]])

Concatenate columns:

>>> a = np.zeros((3,0))
>>> for i in range(3):
...     a = np.c_[a, [[i],[i],[i]]]
>>> a
array([[ 0.,  1.,  2.],
       [ 0.,  1.,  2.],
       [ 0.,  1.,  2.]])

How to trigger the onclick event of a marker on a Google Maps V3?

I've found out the solution! Thanks to Firebug ;)

//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event

//V2 version is:
GEvent.trigger(markers[i], 'click');

//V3 version is:
google.maps.event.trigger(markers[i], 'click');

Has Facebook sharer.php changed to no longer accept detailed parameters?

If you encode the & in your URL to %26 it works correctly. Just tested and verified.

How to convert std::string to LPCSTR?

Converting is simple:

std::string myString;

LPCSTR lpMyString = myString.c_str();

One thing to be careful of here is that c_str does not return a copy of myString, but just a pointer to the character string that std::string wraps. If you want/need a copy you'll need to make one yourself using strcpy.

How do you check if a string is not equal to an object or other string value in java?

you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
    System.out.println("Sorry, incorrect input.");

to be clear you can also do

if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
    System.out.println("Sorry, incorrect input.");

to have the not (one or the other) phrase in the code (remember the (silent) brackets)

How to make ConstraintLayout work with percentage values?

you can use app:layout_constraintVertical_weight it same as layout_weight in linearlayout




NOTE: app:layout_constraintVertical_weight(app:layout_constraintHorizontal_weight) will work with android:layout_width="0dp" (android:layout_height="0dp"

Difference between StringBuilder and StringBuffer

StringBuffer is used to store character strings that will be changed (String objects cannot be changed). It automatically expands as needed. Related classes: String, CharSequence.

StringBuilder was added in Java 5. It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.

No module named 'openpyxl' - Python 3.4 - Ubuntu

In order to keep track of dependency issues, I like to use the conda installer, which simply boils down to:

conda install openpyxl

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

Use nginx to serve static files from subdirectories of a given directory

It should work, however says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;

  location = /404.html {
    root /home/www-data/mysite/static/html;

React : difference between <Route exact path="/" /> and <Route path="/" />

In this example, nothing really. The exact param comes into play when you have multiple paths that have similar names:

For example, imagine we had a Users component that displayed a list of users. We also have a CreateUser component that is used to create users. The url for CreateUsers should be nested under Users. So our setup could look something like this:

  <Route path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />

Now the problem here, when we go to the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users route first and then return it. All good.

But, if we went to, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users partially matches /users/create, so it would incorrectly return the Users route again!

The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

So in this case, we should add exact to our Users route so that it will only match on /users:

  <Route exact path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />

The docs explain exact in detail and give other examples.

Node / Express: EADDRINUSE, Address already in use - Kill server

delete undefined file in your project root directory (which created on app crash)

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

How to fix the session_register() deprecated issue?

Don't use it. The description says:

Register one or more global variables with the current session.

Two things that came to my mind:

  1. Using global variables is not good anyway, find a way to avoid them.
  2. You can still set variables with $_SESSION['var'] = "value".

See also the warnings from the manual:

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

This is pretty important, because the register_globals directive is set to False by default!


This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below.


If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered(), and session_unregister().

Bootstrap date time picker

In order to run the bootstrap date time picker you need to include Moment.js as well. Here is the working code sample in your case.

<!DOCTYPE html>_x000D_
    <html lang="en">_x000D_
      <meta charset="utf-8">_x000D_
      <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
      <link rel="stylesheet" href="">_x000D_
      <script src=""></script>_x000D_
      <script src=""></script>_x000D_
      <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
      <script type="text/javascript" src=""></script>_x000D_
      <link rel="stylesheet" type="text/css" href=""> _x000D_
      <link rel="stylesheet" type="text/css" href=""> _x000D_
      <script type="text/javascript" src=""></script>_x000D_
       <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_

How to reposition Chrome Developer Tools

If you use Windows, there some shortcuts, while devtools are opened:

Pressing Ctrl+Shift+D will dock all devtools to left, right, bottom in turn.

Press Ctrl+Shift+F if your JS console disappeared, and you want it docked back to bottom within dev tools.

twitter bootstrap typeahead ajax example

I am using this method

    hint: true,
    highlight: true,
    minLength: 1
    name: 'options',
    displayKey: 'value',
    source: function (query, process) {
        return $.get('/weather/searchCity/?q=%QUERY', { query: query }, function (data) {
            var matches = [];
            $.each(data, function(i, str) {
                matches.push({ value: str });
            return process(matches);


Changing the Git remote 'push to' default

Very simply, and cobbling together some of the great comments here along with my own research into this.

First, check out the local branch you want to tie to your remote branch:

git checkout mybranch


git branch -u origin/mybranch


git branch -u {remote name}/{branch name}

You should get a message:

"Branch mybranch set up to track remote branch mybranch from origin."

How to generate .env file for laravel?

In windows OS, you can open command prompt, change directory to your project directory.
My project directory


You can type into your Command prompt like this (hit enter each line):


cd xampp\htdocs\my_project

Then you can type,

copy .env.example .env

If you are using Linux, you can type cp, instead of copy

Why do I need to configure the SQL dialect of a data source?

Dialect property is used by hibernate in following ways

  1. To generate Optimized SQL queries.
  2. If you have more than one DB then to talk with particular DB you want.
  3. To set default values for hibernate configuration file properties based on the DB software we use even though they are not specifed in configuration file.

How to alert using jQuery

$(".overdue").each( function() {
    alert("Your book is overdue.");

Note that ".addClass()" works because addClass is a function defined on the jQuery object. You can't just plop any old function on the end of a selector and expect it to work.

Also, probably a bad idea to bombard the user with n popups (where n = the number of books overdue).

Perhaps use the size function:

alert( "You have " + $(".overdue").size() + " books overdue." );

Auto margins don't center image in page

You can center auto width div using display:table;

margin: 0px auto;
float: none;
display: table;

Get a particular cell value from HTML table using JavaScript

To get the text from this cell-

    <tr id="somerow">
        <td>some text</td>            

You can use this -

var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

Both solutions posted here (with slight modifications) work:

<!--[if !IE]><!--><script>if(/*@cc_on!@*/false){document.documentElement.className='ie10';}</script><!--<![endif]-->


<script>if(Function('/*@cc_on return 10===document.documentMode@*/')()){document.documentElement.className='ie10';}</script>

You include either of the above lines inside of head tag of your html page before your css link. And then in css file you specify your styles having "ie10" class as a parent:

.ie10 .myclass1 { }

And voilà! - other browsers stay intact. And you don't need jQuery. You can see the example how I implemented it here:

WRONGTYPE Operation against a key holding the wrong kind of value php

Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.

Here are the commands to retrieve key value:

  • if value is of type string -> GET <key>
  • if value is of type hash -> HGETALL <key>
  • if value is of type lists -> lrange <key> <start> <end>
  • if value is of type sets -> smembers <key>
  • if value is of type sorted sets -> ZRANGEBYSCORE <key> <min> <max>

Use the TYPE command to check the type of value a key is mapping to:

  • type <key>

Html- how to disable <a href>?

You can use CSS to accomplish this:

.disabled {
  pointer-events: none;
  cursor: default;
<a href="somelink.html" class="disabled">Some link</a>

Or you can use JavaScript to prevent the default action like this:


How to force open links in Chrome not download them?

To make certain file types OPEN on your computer, instead of Chrome Downloading...

You have to download the file type once, then right after that download, look at the status bar at the bottom of the browser. Click the arrow next to that file and choose "always open files of this type". DONE.

Now the file type will always OPEN using your default program.

To reset this feature, go to Settings / Advance Settings and under the "Download.." section, there's a button to reset 'all' Auto Downloads

Hope this helps.. :-)

Visual Instructions found here:

How to run binary file in Linux

This is an answer to @craq :

I just compiled the file from C source and set it to be executable with chmod. There were no warning or error messages from gcc.

I'm a bit surprised that you had to 'set it to executable' -- my gcc always sets the executable flag itself. This suggests to me that gcc didn't expect this to be the final executable file, or that it didn't expect it to be executable on this system.

Now I've tried to just create the object file, like so:

$ gcc -c -o hello hello.c
$ chmod +x hello

(hello.c is a typical "Hello World" program.) But my error message is a bit different:

$ ./hello
bash: ./hello: cannot execute binary file: Exec format error`

On the other hand, this way, the output of the file command is identical to yours:

$ file hello
hello: ELF 64-bit LSB  relocatable, x86-64, version 1 (SYSV), not stripped

Whereas if I compile correctly, its output is much longer.

$ gcc -o hello hello.c
$ file hello
hello: ELF 64-bit LSB  executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=131bb123a67dd3089d23d5aaaa65a79c4c6a0ef7, not stripped

What I am saying is: I suspect it has something to do with the way you compile and link your code. Maybe you can shed some light on how you do that?

Is recursion ever faster than looping?

Functional programming is more about "what" rather than "how".

The language implementors will find a way to optimize how the code works underneath, if we don't try to make it more optimized than it needs to be. Recursion can also be optimized within the languages that support tail call optimization.

What matters more from a programmer standpoint is readability and maintainability rather than optimization in the first place. Again, "premature optimization is root of all evil".

Example to use shared_ptr?

Learning to use smart pointers is in my opinion one of the most important steps to become a competent C++ programmer. As you know whenever you new an object at some point you want to delete it.

One issue that arise is that with exceptions it can be very hard to make sure a object is always released just once in all possible execution paths.

This is the reason for RAII:

Making a helper class with purpose of making sure that an object always deleted once in all execution paths.

Example of a class like this is: std::auto_ptr

But sometimes you like to share objects with other. It should only be deleted when none uses it anymore.

In order to help with that reference counting strategies have been developed but you still need to remember addref and release ref manually. In essence this is the same problem as new/delete.

That's why boost has developed boost::shared_ptr, it's reference counting smart pointer so you can share objects and not leak memory unintentionally.

With the addition of C++ tr1 this is now added to the c++ standard as well but its named std::tr1::shared_ptr<>.

I recommend using the standard shared pointer if possible. ptr_list, ptr_dequeue and so are IIRC specialized containers for pointer types. I ignore them for now.

So we can start from your example:

std::vector<gate*> G; 
G.push_back(new ANDgate);  
G.push_back(new ORgate); 
for(unsigned i=0;i<G.size();++i) 

The problem here is now that whenever G goes out scope we leak the 2 objects added to G. Let's rewrite it to use std::tr1::shared_ptr

// Remember to include <memory> for shared_ptr
// First do an alias for std::tr1::shared_ptr<gate> so we don't have to 
// type that in every place. Call it gate_ptr. This is what typedef does.
typedef std::tr1::shared_ptr<gate> gate_ptr;    
// gate_ptr is now our "smart" pointer. So let's make a vector out of it.
std::vector<gate_ptr> G; 
// these smart_ptrs can't be implicitly created from gate* we have to be explicit about it
// gate_ptr (new ANDgate), it's a good thing:
G.push_back(gate_ptr (new ANDgate));  
G.push_back(gate_ptr (new ORgate)); 
for(unsigned i=0;i<G.size();++i) 

When G goes out of scope the memory is automatically reclaimed.

As an exercise which I plagued newcomers in my team with is asking them to write their own smart pointer class. Then after you are done discard the class immedietly and never use it again. Hopefully you acquired crucial knowledge on how a smart pointer works under the hood. There's no magic really.

cannot connect to pc-name\SQLEXPRESS

Follow these steps then you solve your problem 100%.

  1. When you get this error then close everything(Microsoft SQL Server Managment):


  1. Then open command prompt by pressing (window + r) keys and type services.msc and click OK or press Enter key.

  2. And search **SQL Server (SQLEXPRESS) as I show in the image.

enter image description here

  1. Now see left upper side and click start.

  2. If you open Microsoft SQL Server Management then you not get any type error.


Laravel 5.2 redirect back with success message

you can use this :

return redirect()->back()->withSuccess('IT WORKS!');

and use this in your view :


Why is the jquery script not working?

Samuel Liew is right. sometimes jquery conflict with the other jqueries. to solve this problem you need to put them in such a order that they may not conflict with each other. do one thing: open your application in google chrome and inspect bottom right corner with red marked errors. which kind of error that is?

How to delete a file or folder?

Here is a robust function that uses both os.remove and shutil.rmtree:

def remove(path):
    """ param <path> could either be relative or absolute. """
    if os.path.isfile(path) or os.path.islink(path):
        os.remove(path)  # remove the file
    elif os.path.isdir(path):
        shutil.rmtree(path)  # remove dir and all contains
        raise ValueError("file {} is not a file or dir.".format(path))

How to resolve git's "not something we can merge" error

I had a work tree with master and an another branch checked out in two different work folders.

PS C:\rhipheusADO\Build> git worktree list
C:/rhipheusADO/Build         7d32e6e [vyas-cr-core]
C:/rhipheusADO/Build-master  91d418c [master]

PS C:\rhipheusADO\Build> cd ..\Build-master\

PS C:\rhipheusADO\Build-master> git merge 7d32e6e #Or any other intermediary commits
Updating 91d418c..7d32e6e
 Pipeline/CR-MultiPool/azure-pipelines-auc.yml | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

PS C:\rhipheusADO\Build-master> git ls-remote
53060bac18f9d4e7c619e5170c436e6049b63f25        HEAD
7d32e6ec76d5a5271caebc2555d5a3a84b703954        refs/heads/vyas-cr-core 

PS C:\rhipheusADO\Build-master> git merge 7d32e6ec76d5a5271caebc2555d5a3a84b703954
Already up-to-date

PS C:\rhipheusADO\Build>  git push
Total 0 (delta 0), reused 0 (delta 0)
   91d418c..7d32e6e  master -> master

If you need to just merge the latest commit:

git merge origin/vyas-cr-core 
git push

And is same as what I've always done:

git checkout master # This is needed if you're not using worktrees
git pull origin vyas-cr-core
git push

Jquery open popup on button click for bootstrap

The answer is on the example link you provided:


Call a modal with id myModal with a single line of JavaScript:


JavaFX Location is not set error message

That happened to me an i found the solution. If u build your project with your .fxml files in different packages from the class that has the launch line (Parent root = FXMLLoader.load(getClass().getResource("filenamehere.fxml"));) and use a relative path your windows except from the first one wont launch when your run the jar. To keep it short place the .fxml file in the same package with the class that launches it and set the path like this ("filenamehere.fxml") and it should work fine.

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

TL;DR: Install Chocolatey, Node (and NPM)

Install Chocolatey

NOTE: You might want to copy the exact command from their install page since it might change over time.

  1. Open your standard Windows command line
  2. @powershell -NoProfile -ExecutionPolicy unrestricted -Command "(iex ((new-object net.webclient).DownloadString(''))) >$null 2>&1" && SET PATH="%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
  3. Restart console
  4. Done!

Install Node (and NPM)

  1. Because Chocolatey installs a directory different from the MSI installation, go to your system configuration and delete your previous node installation (if you have one)
  2. Install Chocolatey as described above
  3. choco install nodejs

    NOTE I used nodejs. I am not even sure what node is, but having had my fair share of troubles with node already being taken by something else in other systems, I thought, nodejs would be the safer bet right away

  4. Restart your console
  5. Beware: node -v works!
    • And npm -v also works! Awesome.

After this, I was able to install firebase-tools without problems (which I was not able to do previously), so something must have gone terribly right! :)

My rather complete story the first time around

"Chocolatey installs in seconds"

If you don't care about sarcasm or lamenting engineers on a Sunday afternoon, skip ahead to the installation instructions in the TL;DR section below.

For everyone else: I want to amend this answer which recommends using (what seems to be the hottest package management solution for Windows right now): Chocolatey

It gets the job done nice and quick. However, when I gave it a first try, it took me a while to make sense of the install instructions which are kinda convoluted. The install instructions go a bit like this (complete with what went through my head while going through it):

  • NOTE:
  • NOTE:
  • NOTE:

    three big-ass NOTEs before even knowing the basics... this makes me anxious... how wrong could things go!?

  • Installing With Restricted TLS

    not even sure what TLS is... Oh it's a good friend of SSL - Shouldn't this just be the default and just work out of the box? My browser can do HTTPS, NO PROBLEM! (just kidding... I know that SSL and TSL frequently cause a lot of pain in environments that have high security needs)

  • Option 1
  • Option 2

    eeh... great... Can't I just install?

  • Installing Behind a Proxy?

    Just... no...

  • Requirements

    uh boi...

  • Why does Chocolatey install where it does by default?


  • Before You Install


  • Can I install with a proxy?

    again with the proxy...

  • Can I install a particular version of Chocolatey?

    just any version would be fine, thank you...

  • Can I use Windows built-in compression instead of downloading 7zip?

    7zip?! Why do you even mention this?!

  • Non-Administrative Install
  • Now that sounds great!

    • "NOTE: This option should be a last resort and is considered to be an advanced scenario."
      • Sh$%!@T.

  • Alternative Installation Options


  • Command Line
    • "This really is the easiest method because it requires no configuration of PowerShell prior to executing it."

      And there you go!

While I really appreciate the fact that pitfalls and their possible solutions are discussed so extensively, maybe re-organizing them as such, and putting the Chocolatey installs in seconds promise to work by putting the "easiest method" first would be just awesome!

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.


Java: Difference between the setPreferredSize() and setSize() methods in components

IIRC ...

setSize sets the size of the component.

setPreferredSize sets the preferred size. The Layoutmanager will try to arrange that much space for your component.

It depends on whether you're using a layout manager or not ...

Use component from another module

(Angular 2 - Angular 7)

Component can be declared in a single module only. In order to use a component from another module, you need to do two simple tasks:

  1. Export the component in the other module
  2. Import the other module, into the current module

1st Module:

Have a component (lets call it: "ImportantCopmonent"), we want to re-use in the 2nd Module's page.

declarations: [
    ImportantCopmonent // <-- Enable using the component html tag in current module
imports: [
exports: [
    ImportantCopmonent // <--- Enable using the component in other modules
export class FirstPageModule { }

2nd Module:

Reuses the "ImportantCopmonent", by importing the FirstPageModule

declarations: [
imports: [
  FirstPageModule // <--- this Imports the source module, with its exports
exports: [
export class SecondPageModule { }

How to append the output to a file?

Use >> to append:

command >> file

how to add the missing RANDR extension

I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.

It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR warning and problem at starting Firefox using Xfvb.

After adding +extension RANDR it worked again.

$ vim /etc/init/xvfb.conf

description "Xvfb Server as a daemon"

start on filesystem and started networking
stop on shutdown


env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/

exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1

Java logical operator short-circuiting

SET A uses short-circuiting boolean operators.

What 'short-circuiting' means in the context of boolean operators is that for a set of booleans b1, b2, ..., bn, the short circuit versions will cease evaluation as soon as the first of these booleans is true (||) or false (&&).

For example:

// 2 == 2 will never get evaluated because it is already clear from evaluating
// 1 != 1 that the result will be false.
(1 != 1) && (2 == 2)

// 2 != 2 will never get evaluated because it is already clear from evaluating
// 1 == 1 that the result will be true.
(1 == 1) || (2 != 2)

Only mkdir if it does not exist

Use mkdir's -p option, but note that it has another effect as well.

 -p      Create intermediate directories as required.  If this option is not specified, the full path prefix of each oper-
         and must already exist.  On the other hand, with this option specified, no error will be reported if a directory
         given as an operand already exists.  Intermediate directories are created with permission bits of rwxrwxrwx
         (0777) as modified by the current umask, plus write and search permission for the owner.

Difference between Inheritance and Composition

Inheritance brings out IS-A relation. Composition brings out HAS-A relation. Strategy pattern explain that Composition should be used in cases where there are families of algorithms defining a particular behaviour.
Classic example being of a duck class which implements a flying behaviour.

public interface Flyable{
 public void fly();

public class Duck {
 Flyable fly;

 public Duck(){
  fly = new BackwardFlying();

Thus we can have multiple classes which implement flying eg:

public class BackwardFlying implements Flyable{
  public void fly(){
    Systemout.println("Flies backward ");
public class FastFlying implements Flyable{
  public void fly(){
    Systemout.println("Flies 100 miles/sec");

Had it been for inheritance, we would have two different classes of birds which implement the fly function over and over again. So inheritance and composition are completely different.

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

Wordpress 4.2 introduced support for "utf8mb4" character encoding for security reasons, but only MySQL 5.5.3 and greater support it. The way the installer (and updater) handles this is that it checks your MySQL version and your database will be upgraded to utfmb4 only if it's supported.

This sounds great in theory but the problem (as you've discovered) is when you are migrating databases from a MySQL server that supports utf8mb4 to one that doesn't. While the other way around should work, it's basically a one-way operation.

As pointed out by Evster you might have success using PHPMYAdmin's "Export" feature. Use "Export Method: Custom" and for the "Database system or older MySQL server to maximize output compatibility with:" dropdown select "MYSQL 40".

For a command line export using mysqldump. Have a look at the flag:

$ mysqldump --compatible=mysql4

Note: If there are any 4-byte characters in the database they will be corrupted.

Lastly, for anyone using the popular WP Migrate DB PRO plugin, a user in this thread reports that the migration is always handled properly but I wasn't able to find anything official.

The WP Migrate DB plugin translates the database from one collation to the other when it moves 4.2 sites between hosts with pre- or post-5.5.3 MySQL

At this time, there doesn't appear to be a way to opt out of the database update. So if you are using a workflow where you are migrating a site from a server or localhost with MySQL > 5.5.3 to one that uses an older MySQL version you might be out of luck.

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);


JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

How can I send JSON response in symfony2 controller

Since Symfony 3.1 you can use JSON Helper

public function indexAction()
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header
return $this->json(array('username' => 'jane.doe'));

// the shortcut defines three optional arguments
// return $this->json($data, $status = 200, $headers = array(), $context = array());

Calling multiple JavaScript functions on a button click

And of course you can never call the two functions at the same time. Not any one in the world except you are working on two processors simultaneously.

The best way is to call a JavaScript parent function and in that, specify all the sequence of function you want to call. For example,

function ShowDiv1() {
    document.getElementById("ReportDiv").style.display = 'block';
    return false;

function validateView()
    if (document.getElementById("ctl00_ContentPlaceHolder1_DLCategory").selectedIndex == 0) {
        document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "Please Select Your Category";
        return false;
    if (document.getElementById("ctl00_ContentPlaceHolder1_DLEmpName").selectedIndex == 0) {
        document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "Please Select Your Employee Name";
        return false;
    return true;

When 1 px border is added to div, Div size increases, Don't want to do that

You can do some fancy things with inset shadows. Example to put a border on the bottom of an element without changing its size:

.bottom-border {
  box-shadow:inset 0px -3px 0px #000;

How to push local changes to a remote git repository on bitbucket

This is a safety measure to avoid pushing branches that are not ready to be published. Loosely speaking, by executing "git push", only local branches that already exist on the server with the same name will be pushed, or branches that have been pushed using the localbranch:remotebranch syntax.

To push all local branches to the remote repository, use --all:

git push REMOTENAME --all
git push --all

or specify all branches you want to push:

git push REMOTENAME master exp-branch-a anotherbranch bugfix

In addition, it's useful to add -u to the "git push" command, as this will tell you if your local branch is ahead or behind the remote branch. This is shown when you run "git status" after a git fetch.

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

The consequence of this is that you may need a rather insane-looking query, e. g.,

SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID]            AS lngRecordID
          ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]  AS vcrSourceWorkbookName
          ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]      AS vcrImportFileName
          ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]       AS dtmLastWriteTime
          ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]            AS lngNRecords
          ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]          AS lngSizeOnDisk
          ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]        AS lngLastIdentity
          ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
          ,MIN ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodFirstWorkDate
          ,MAX ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodLastWorkDate
          ,SUM ( [tblTimeRecords].[decMan_Hours_Actual] )           AS decHoursWorked
          ,SUM ( [tblTimeRecords].[decAdjusted_Hours] )             AS decHoursBilled
      FROM [dbo].[tblTimeSheetExportFiles]
      LEFT JOIN   [dbo].[tblTimeRecords]
              ON  [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
        GROUP BY  [dbo].[tblTimeSheetExportFiles].[lngRecordID]

Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.

Elegant way to report missing values in a data.frame

A dplyr solution to get the count could be:

summarise_all(df, ~sum(

Or to get a percentage:

summarise_all(df, ~(sum(is_missing(.) / nrow(df))))

Maybe also worth noting that missing data can be ugly, inconsistent, and not always coded as NA depending on the source or how it's handled when imported. The following function could be tweaked depending on your data and what you want to consider missing:

is_missing <- function(x){
  missing_strs <- c('', 'null', 'na', 'nan', 'inf', '-inf', '-9', 'unknown', 'missing')
  ifelse(( | is.nan(x) | is.infinite(x)), TRUE,
         ifelse(trimws(tolower(x)) %in% missing_strs, TRUE, FALSE))

# sample ugly data
df <- data.frame(a = c(NA, '1', '  ', 'missing'),
                 b = c(0, 2, NaN, 4),
                 c = c('NA', 'b', '-9', 'null'),
                 d = 1:4,
                 e = c(1, Inf, -Inf, 0))

# counts:
> summarise_all(df, ~sum(is_missing(.)))
  a b c d e
1 3 1 3 0 2

# percentage:
> summarise_all(df, ~(sum(is_missing(.) / nrow(df))))
     a    b    c d   e
1 0.75 0.25 0.75 0 0.5

Inversion of Control vs Dependency Injection

As for this question, I'd say the wiki has already provided detailed and easy-understanding explanations. I will just quote the most significant here.

Implementation of IoC

In object-oriented programming, there are several basic techniques to implement inversion of control. These are:

  1. Using a service locator pattern Using dependency injection, for example Constructor injection Parameter injection Setter injection Interface injection;
  2. Using a contextualized lookup;
  3. Using template method design pattern;
  4. Using strategy design pattern

As for Dependency Injection

dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.

jQuery textbox change event

The HTML4 spec for the <input> element specifies the following script events are available:

onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

here's an example that bind's to all these events and shows what's going on

I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change

How to use JavaScript to change div backgroundColor

Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and after tomorrow you decided that it would be also nice to change the border.

Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.

Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.

So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.

One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.

In conclusion, here is the code which I would use for such tasks:

//for adding a css class
function onOver(node){
   node.className = node.className + ' Hover';

//for removing a css class
function onOut(node){
    node.className = node.className.replace('Hover','');

function connect(node,event,fnc){
    }else if(node.attachEvent){

// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){

And you CSS whould be like this:

.content {
    background-color: blue;

    background-color: red;

.content.Hover h2{
    background-color : yellow;

What is the most elegant way to check if all values in a boolean array are true?

In Java 8+, you can create an IntStream in the range of 0 to myArray.length and check that all values are true in the corresponding (primitive) array with something like,

return IntStream.range(0, myArray.length).allMatch(i -> myArray[i]);

Adding Only Untracked Files

If you have thousands of untracked files (ugh, don't ask) then git add -i will not work when adding *. You will get an error stating Argument list too long.

If you then also are on Windows (don't ask #2 :-) and need to use PowerShell for adding all untracked files, you can use this command:

git ls-files -o --exclude-standard | select | foreach { git add $_ }

Bash ignoring error for a particular command

output=$(*command* 2>&1) && exit_status=$? || exit_status=$?
echo $output
echo $exit_status

Example of using this to create a log file

timestamp=$(date '+%D %T') #mm/dd/yy HH:MM:SS
echo -e "($timestamp) $event" >> "$log_file"

output=$(*command* 2>&1) && exit_status=$? || exit_status=$?

if [ "$exit_status" = 0 ]
        event="ERROR $output"

the getSource() and getActionCommand()

The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.

How to setup virtual environment for Python in VS Code?

I fixed the issue without changing the python path as that did not seem like the right solution for me. The following solution worked for me, hopefully it works for you as well :))

  1. Open cmd in windows / shell in Linux/Mac.
  2. Activate your virtualenv (using source activate / activate.bat / activate.ps1 if using power shell)

    C:\Users\<myUserName>\Videos\myFolder>django-project\Scripts\activate.bat (django-project) C:\Users\<myUserName>\Videos\myFolder>

  3. Navigate to your project directory and open vscode there.

    (django-project) C:\Users\prash\Videos\myFolder\projects>code .

  4. in VS Code, goto File --> Preferences --> Settings (dont worry you dont need to open the json file)

  5. In the setting search bar search for virtual / venv and hit enter. You should find the below in the search bar:

Python: Venv Folders Folders in your home directory to look into for virtual environments (supports pyenv, direnv and virtualenvwrapper by default).

  1. Add item, and then enter the path of the scripts of your virtuanenv which has the activate file in it. For example in my system, it is:


  2. Save it and restart VS Code.

  3. To restart, open cmd again, navigate to your project path and open vs code. (Note that your venv should be activated in cmd before you open vs code from cmd)

Command to open vs code from cmd:

code .

How to setup virtualenv in VS code

Today's Date in Perl in MM/DD/YYYY format

Perl Code for Unix systems:

# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;

# Remove newline character
$current_date = substr($current_date,0,-1);

print $current_date, "\n";

How to remove folders with a certain name

I had more than 100 files like


above answers did not work for me

but the following command helped me.

find . -name "log-*" -exec rm  -rf {} \;

i gave -type as . so it deletes both files and folders which starts with log-

and rm -rf deletes folders recursively even it has files.

if you want folders alone

find -type d -name "log-*" -exec rm  -rf {} \;

files alone

find -type f -name "log-*" -exec rm  -rf {} \;

Add querystring parameters to link_to

If you want the quick and dirty way and don't worry about XSS attack, use params.merge to keep previous parameters. e.g.

<%= link_to 'Link', params.merge({:per_page => 20}) %>


Otherwise , check this answer: params.merge and cross site scripting

CronJob not running

Sometimes the command that cron needs to run is in a directory where cron has no access, typically on systems where users' home directories' permissions are 700 and the command is in that directory.

Show loading screen when navigating between routes in Angular 2

If you have special logic required for the first route only you can do the following:


    loaded = false;

    constructor(private router: Router....) { => e instanceof NavigationEnd), take(1))
                    .subscribe((e) => {
                       this.loaded = true;
                       alert('loaded - this fires only once');

I had a need for this to hide my page footer, which was otherwise appearing at the top of the page. Also if you only want a loader for the first page you can use this.

Passing a method parameter using Task.Factory.StartNew

For passing a single integer I agree with Reed Copsey's answer. If in the future you are going to pass more complicated constucts I personally like to pass all my variables as an Anonymous Type. It will look something like this:

foreach(int id in myIdsToCheck)
    Task.Factory.StartNew( (Object obj) => 
           var data = (dynamic)obj;
           CheckFiles(, theBlockingCollection,
        }, new { id = id }); // Parameter value

You can learn more about it in my blog

How can I switch my git repository to a particular commit

Just checkout the commit you wants your new branch start from and create a new branch

git checkout -b newbranch 6e559cb95

How to amend a commit without changing commit message (reusing the previous one)?

git commit -C HEAD --amend will do what you want. The -C option takes the metadata from another commit.

How do I add an active class to a Link from React Router?

React-Router V4 comes with a NavLink component out of the box

To use, simply set the activeClassName attribute to the class you have appropriately styled, or directly set activeStyle to the styles you want. See the docs for more details.


What does $ mean before a string?

It signifies string interpolation.

It will protect you because it is adding compilation time protection on the string evaluation.

You will no longer get an exception with string.Format("{0}{1}",secondParamIsMissing)

element not interactable exception in selenium web automation

I got this error because I was using a wrong CSS selector with the Selenium WebDriver Node.js function By.css().

You can check if your selector is correct by using it in the web console of your web browser (Ctrl+Shift+K shortcut), with the JavaScript function document.querySelectorAll().

Finding Variable Type in JavaScript

In Javascript you can do that by using the typeof function

function foo(bar){

How to file split at a line number


# set first K lines:

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
SET level = users.level + 1;

How to find which version of TensorFlow is installed in my system?

On Latest TensorFlow release 1.14.0


is deprecated, instead of this use



WARNING: Logging before flag parsing goes to stderr.
The name tf.VERSION is deprecated. Please use tf.version.VERSION instead.

Standard deviation of a list

Here's some pure-Python code you can use to calculate the mean and standard deviation.

All code below is based on the statistics module in Python 3.4+.

def mean(data):
    """Return the sample arithmetic mean of data."""
    n = len(data)
    if n < 1:
        raise ValueError('mean requires at least one data point')
    return sum(data)/n # in Python 2 use sum(data)/float(n)

def _ss(data):
    """Return sum of square deviations of sequence data."""
    c = mean(data)
    ss = sum((x-c)**2 for x in data)
    return ss

def stddev(data, ddof=0):
    """Calculates the population standard deviation
    by default; specify ddof=1 to compute the sample
    standard deviation."""
    n = len(data)
    if n < 2:
        raise ValueError('variance requires at least two data points')
    ss = _ss(data)
    pvar = ss/(n-ddof)
    return pvar**0.5

Note: for improved accuracy when summing floats, the statistics module uses a custom function _sum rather than the built-in sum which I've used in its place.

Now we have for example:

>>> mean([1, 2, 3])
>>> stddev([1, 2, 3]) # population standard deviation
>>> stddev([1, 2, 3], ddof=1) # sample standard deviation

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

jquery - disable click

You can use unbind method to remove handler that has been attached...

if (current = 1){ 

You can check what can unbind do ? Unbind manual

How to define an optional field in protobuf 3

Another way is that you can use bitmask for each optional field. and set those bits if values are set and reset those bits which values are not set

enum bitsV {
    baz_present = 1; // 0x01
    baz1_present = 2; // 0x02

message Foo {
    uint32 bitMask;
    required int32 bar = 1;
    optional int32 baz = 2;
    optional int32 baz1 = 3;

On parsing check for value of bitMask.

if (bitMask & baz_present)
    baz is present

if (bitMask & baz1_present)
    baz1 is present

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Do something like this:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

another solution is to build a new list

List<Dog> dogs = new ArrayList<Dog>(); 
List<Animal> animals = new ArrayList<Animal>(dogs);
animals.add(new Cat());

What causes: "Notice: Uninitialized string offset" to appear?

Try to test and initialize your arrays before you use them :

if( !isset($catagory[$i]) ) $catagory[$i] = '' ;
if( !isset($task[$i]) ) $task[$i] = '' ;
if( !isset($fullText[$i]) ) $fullText[$i] = '' ;
if( !isset($dueDate[$i]) ) $dueDate[$i] = '' ;
if( !isset($empId[$i]) ) $empId[$i] = '' ;

If $catagory[$i] doesn't exist, you create (Uninitialized) one ... that's all ; => PHP try to read on your table in the address $i, but at this address, there's nothing, this address doesn't exist => PHP return you a notice, and it put nothing to you string. So you code is not very clean, it takes you some resources that down you server's performance (just a very little).

Take care about your MySQL tables default values

if( !isset($dueDate[$i]) ) $dueDate[$i] = '0000-00-00 00:00:00' ;


if( !isset($dueDate[$i]) ) $dueDate[$i] = 'NULL' ;

Labels for radio buttons in rails form

If you want the object_name prefixed to any ID you should call form helpers on the form object:

- form_for(@message) do |f|
  = f.label :email

This also makes sure any submitted data is stored in memory should there be any validation errors etc.

If you can't call the form helper method on the form object, for example if you're using a tag helper (radio_button_tag etc.) you can interpolate the name using:

= radio_button_tag "#{f.object_name}[email]",

In this case you'd need to specify the value manually to preserve any submissions.

c# open a new form then close the current form?

I usually do this to switch back and forth between forms.

Firstly, in Program file I keep ApplicationContext and add a helper SwitchMainForm method.

        static class Program
    public static ApplicationContext AppContext { get;  set; }

    static void Main(string[] args)

        //Save app context
        Program.AppContext = new ApplicationContext(new LoginForm());

    //helper method to switch forms
      public static void SwitchMainForm(Form newForm)
        var oldMainForm = AppContext.MainForm;
        AppContext.MainForm = newForm;


Then anywhere in the code now I call SwitchMainForm method to switch easily to the new form.

// switch to some other form
var otherForm = new MyForm();

How do I provide a username and password when running "git clone [email protected]"?

In the comments of @Bassetassen's answer, @plosco mentioned that you can use git clone https://<token> to clone from GitHub at the very least. I thought I would expand on how to do that, in case anyone comes across this answer like I did while trying to automate some cloning.

GitHub has a very handy guide on how to do this, but it doesn't cover what to do if you want to include it all in one line for automation purposes. It warns that adding the token to the clone URL will store it in plaintext in .git/config. This is obviously a security risk for almost every use case, but since I plan on deleting the repo and revoking the token when I'm done, I don't care.

1. Create a Token

GitHub has a whole guide here on how to get a token, but here's the TL;DR.

  1. Go to Settings > Developer Settings > Personal Access Tokens (here's a direct link)
  2. Click "Generate a New Token" and enter your password again. (here's another direct link)
  3. Set a description/name for it, check the "repo" permission and hit the "Generate token" button at the bottom of the page.
  4. Copy your new token before you leave the page

2. Clone the Repo

Same as the command @plosco gave, git clone https://<token><username>/<repository>.git, just replace <token>, <username> and <repository> with whatever your info is.

If you want to clone it to a specific folder, just insert the folder address at the end like so: git clone https://<token><username>/<repository.git> <folder>, where <folder> is, you guessed it, the folder to clone it to! You can of course use ., .., ~, etc. here like you can elsewhere.

3. Leave No Trace

Not all of this may be necessary, depending on how sensitive what you're doing is.

  • You probably don't want to leave that token hanging around if you have no intentions of using it for some time, so go back to the tokens page and hit the delete button next to it.
  • If you don't need the repo again, delete it rm -rf <folder>.
  • If do need the repo again, but don't need to automate it again, you can remove the remote by doing git remote remove origin or just remove the token by running git remote set-url origin<username>/<repository.git>.
  • Clear your bash history to make sure the token doesn't stay logged there. There are many ways to do this, see this question and this question. However, it may be easier to just prepend all the above commands with a space in order to prevent them being stored to begin with.

Note that I'm no pro, so the above may not be secure in the sense that no trace would be left for any sort of forensic work.

C - split string into an array of strings

Here is an example of how to use strtok borrowed from MSDN.

And the relevant bits, you need to call it multiple times. The token char* is the part you would stuff into an array (you can figure that part out).

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

int main( void )
    printf( "Tokens:\n" );
    /* Establish string and get the first token: */
    token = strtok( string, seps );
    while( token != NULL )
        /* While there are tokens in "string" */
        printf( " %s\n", token );
        /* Get next token: */
        token = strtok( NULL, seps );

Functional programming vs Object Oriented programming

When do you choose functional programming over object oriented?

When you anticipate a different kind of software evolution:

  • Object-oriented languages are good when you have a fixed set of operations on things, and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone.

  • Functional languages are good when you have a fixed set of things, and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone.

When evolution goes the wrong way, you have problems:

  • Adding a new operation to an object-oriented program may require editing many class definitions to add a new method.

  • Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.

This problem has been well known for many years; in 1998, Phil Wadler dubbed it the "expression problem". Although some researchers think that the expression problem can be addressed with such language features as mixins, a widely accepted solution has yet to hit the mainstream.

What are the typical problem definitions where functional programming is a better choice?

Functional languages excel at manipulating symbolic data in tree form. A favorite example is compilers, where source and intermediate languages change seldom (mostly the same things), but compiler writers are always adding new translations and code improvements or optimizations (new operations on things). Compilation and translation more generally are "killer apps" for functional languages.

How to add items to array in nodejs

Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.

You can download from (

$ npm install underscore

Here is small snippet to demonstrate how you can do it.

var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
    newArray = [];

_.each(calendars, function (item, index) {


How remove border around image in css?

Try this:


You can also limitate the scope and only remove border on some images by doing so:

.myClass img{border:0;}

More information about the border css property can by found here.

Edit: Changed border from 0px to 0. As explained in comments, px is redundant for a unit of 0.

Simulator or Emulator? What is the difference?

Simulator is something more broader than Emulator and it seems like the duality of this terms is overthought in the posts above.


People decided to use a new word emulation in the "computer world" when they started replacing some hardware parts of the existing system in straightforward manner - imitating their behaviour and relying on the computational nature to be sure to not break something and leave everything in the equivalent state. So we have emulated the piece of this! (and the whole still works as before)

Emulator usually used in narrow sense in digital area as replacement and virtualization - presenting in digital form as a piece of software - of something known and existed before (virtual chips, circuit boards, electronic devices). So when the world became more digital and brought the emulator word to the masses, the masses added uncertainty to it (or additional reasons).


First of all, I saw many comments about emulators do or replace something real but simulators not.

BUT flight simulator is used for a real thing - it trains pilots, gives them skill up and knowledge and it replaces expensive real planes and saves much of money. And we cannot just say a plane-emulator because we have inner feeling that this is much more than that, so we call it simulator :) Plane simulator could contain emulated radar or transponder that is true.

Contra-statements that simulators are used for analysis and study (and emulators for something real), but that analysis and study not less a real thing than emulated GSM boards (even more in the informational age we live in). Analysis adds a value to the business, cuts costs or points out to profits not less than the replaced (emulated) hardware.

Simulator is similar to modelling of something that we can't obtain for some reason (cost, technology, physical impossibility). It is usually simulated for something new or intangible or complex or not properly known to us like market, weather, combustion, user. So here comes the flight, black hole, stock exchange, simulations.

So finally:

  1. Simulator is broader than Emulator
  2. Simulator tends to imitate/model more global processes/things in general with ability to narrow the imitation down (e.g. capacitor simulator with presets representing some known models)
  3. Emulator tends to imitate certain hardware devices with certain specification, known characteristics and properties (e.g. SNES emulator, Intel 8087 or Roland TB-303)

As for words origin

All came from Latin and mean:

  • emulate is "to be equal" (looks like more aggressive and straightforward - rivalry)
  • simulate is "to be similar" (looks like more sly and tricky - imitation)

Write to text file without overwriting in Java

use a FileWriter instead.

FileWriter(File file, boolean append)

the second argument in the constructor tells the FileWriter to append any given input to the file rather than overwriting it.

here is some code for your example:

File log = new File("log.txt")

        System.out.println("We had to make a new file.");

    FileWriter fileWriter = new FileWriter(log, true);

    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write("******* " + timeStamp.toString() +"******* " + "\n");

} catch(IOException e) {
    System.out.println("COULD NOT LOG!!");

Draggable div without jQuery UI

What I saw above is complicate.....

Here is some code can refer to.

                  dragging = true;
                  dragX = e.clientX - $(this).position().left;
                  //To calculate the distance between the cursor pointer and box 
                  dragY = e.clientY - $(this).position().top;
                mouseup:function(){dragging = false;},
                  //If not set this on/off,the move will continue forever


dragging,dragX,dragY may place as the global variable.

It's a simple show about this issue,but there is some bug about this method.

If it's your need now,here's the Example here.

How to show live preview in a small popup of linked page on mouse over on link?

Another way is to use a website thumbnail/link preview service LinkPeek (even happens to show a screenshot of StackOverflow as a demo right now), URL2PNG, Browshot, Websnapr, or an alternative.

How can I generate a list or array of sequential integers in Java?

This is the shortest I could get using Core Java.

List<Integer> makeSequence(int begin, int end) {
  List<Integer> ret = new ArrayList(end - begin + 1);

  for(int i = begin; i <= end; i++, ret.add(i));

  return ret;  

permission denied - php unlink

in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink() , u will encounter with a wrong Warning message that says "permission denied"

however u can make folders & files by mkdir() but the way u delete folders (rmdir()) is different from the way you delete files(unlink())

eventually as a fact:

in many programming languages, any permission related error may not directly means an actual permission issue

for example, if you want to readSync a file that doesn't exist with node fs module you will encounter a wrong EPERM error

How do I change the JAVA_HOME for ant?

Set the env var: JAVACMD - full path of the Java executable. Use this to invoke a different JVM than JAVA_HOME/bin/java(.exe).


Extract substring from a string

substring(int startIndex, int endIndex)

If you don't specify endIndex, the method will return all the characters from startIndex.

startIndex : starting index is inclusive

endIndex : ending index is exclusive


String str = "abcdefgh"

str.substring(0, 4) => abcd

str.substring(4, 6) => ef

str.substring(6) => gh

How do I remove the passphrase for the SSH key without having to create a new key?

You might want to add the following to your .bash_profile (or equivalent), which starts ssh-agent on login.

if [ -f ~/.agent.env ] ; then
    . ~/.agent.env > /dev/null
    if ! kill -0 $SSH_AGENT_PID > /dev/null 2>&1; then
        echo "Stale agent file found. Spawning new agent… "
        eval `ssh-agent | tee ~/.agent.env`
    echo "Starting ssh-agent"
    eval `ssh-agent | tee ~/.agent.env`

On some Linux distros (Ubuntu, Debian) you can use:

ssh-copy-id -i ~/.ssh/ username@host

This will copy the generated id to a remote machine and add it to the remote keychain.

You can read more here and here.

error: Your local changes to the following files would be overwritten by checkout

You can force checkout your branch, if you do not want to commit your local changes.

git checkout -f branch_name

System.IO.IOException: file used by another process

I realize that I is kinda late, but still better late than never. I was having similar problem recently. I used XMLWriter to subsequently update XML file and was receiving the same errors. I found the clean solution for this:

The XMLWriter uses underlying FileStream to access the modified file. Problem is that when you call XMLWriter.Close() method, the underlying stream doesn't get closed and is locking the file. What you need to do is to instantiate your XMLWriter with settings and specify that you need that underlying stream closed.


XMLWriterSettings settings = new Settings();
settings.CloseOutput = true;
XMLWriter writer = new XMLWriter(filepath, settings);

Hope it helps.

Enable/Disable a dropdownbox in jquery

I am using JQuery > 1.8 and this works for me...

$('#dropDownId').attr('disabled', true);

How to search for an element in an stl list?

What you can do and what you should do are different matters.

If the list is very short, or you are only ever going to call find once then use the linear approach above.

However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.

GetElementByID - Multiple IDs

No, it won't work.

document.getElementById() method accepts only one argument.

However, you may always set classes to the elements and use getElementsByClassName() instead. Another option for modern browsers is to use querySelectorAll() method:

document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4");

How to fix the "508 Resource Limit is reached" error in WordPress?

I faced to this problem a lot when developing my company's website using WordPress. Finally I found that it happened because me and my colleague update the website at the same time as well as we installed and activated many plugins that we did not use them. The solution for me was we update the website in different time and deactivated and uninstalled those plugins.

Angular 2 'component' is not a known element

This question may seem old and odd, but when I was trying to load a module(lazy loading) and getting the same error, I realized I was missing an exports clause for the component that shipped as a part of a larger module.

This Link explains why: Components/Services inside a module, remains private(or protected) by default. To make them public, you have to export them.

Expanding on @Robin Djikof's answer with @live-love code sample, this is what was technically missing in my case(Angular 8):

  declarations: [
  imports: [
  exports: [ProductListComponent] 
  //<- This line makes ProductListComponent available outside the module, 
  //while keeping SomeOtherComponent private to the module
export class SomeLargeModule { }

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

Reason and solution-

Everything happens for a reason :)

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:3.1.0:clean (default-clean) on project

  • The reason of this problem is that the target folder is already in use. That means any jar or any war or any application is using that target folder

Solution- 1) Check the war and jar (also check jar if any running in background), terminate it.

2) if u have opened command prompt (cmd), and are using that path to execute the jar, close it or change the path in cmd. This was the reason in my case. Do check this.

Once u do this , u would be able to delete the contents of the target folder and and can also perform maven clean and maven install.

HttpClient - A task was cancelled?

Another reason can be that if you are running the service (API) and put a breakpoint in the service (and your code is stuck at some breakpoint (e.g Visual Studio solution is showing Debugging instead of Running)). and then hitting the API from the client code. So if the service code a paused on some breakpoint, you just hit F5 in VS.

Laravel 5 Class 'form' not found

This may not be the answer you're looking for, but I'd recommend using the now community maintained repository Laravel Collective Forms & HTML as the main repositories have been deprecated.

Laravel Collective is in the process of updating their website. You may view the documentation on GitHub if needed.

How do I set a fixed background image for a PHP file?

Your question doesn't have anything to do with PHP... just CSS.

Your CSS is correct, but your browser won't typically be able to open what you have put in for a URL. At a minimum, you'll need a file: path. It would be best to reference the file by its relative path.

Android Viewpager as Image Slide Gallery

you can use custom gallery control.. check this use galleryTouch class from this..

What are the differences between "git commit" and "git push"?

It is easier to understand the use of the git commands add and commit if you imagine a log file being maintained in your repository on Github. A typical project's log file for me may look like:

---------------- Day 1 --------------------
Message: Completed Task A
Index of files changed: File1, File2

Message: Completed Task B
Index of files changed: File2, File3

---------------- Day 2 --------------------
Message: Corrected typos
Index of files changed: File3, File1
...and so on

I usually start my day with a git pull request and end it with a git push request. So everything inside a day's record corresponds to what occurs between them. During each day, there are one or more logical tasks that I complete which require changing a few files. The files edited during that task are listed in an index.

Each of these sub tasks(Task A and Task B here) are individual commits. The git add command adds files to the 'Index of Files Changed' list. This process is also called staging and in reality records changed files and the changes performed. The git commit command records/finalizes the changes and the corresponding index list along with a custom message which may be used for later reference.

Remember that you're still only changing the local copy of your repository and not the one on Github. After this, only when you do a git push do all these recorded changes, along with your index files for each commit, get logged on the main repository(on Github).

As an example, to obtain the second entry in that imaginary log file, I would have done:

git pull
# Make changes to File3 and File4
git add File3 File4
# Verify changes, run tests etc..
git commit -m 'Corrected typos'
git push

In a nutshell, git add and git commit lets you break down a change to the main repository into systematic logical sub-changes. As other answers and comments have pointed out, there are ofcourse many more uses to them. However, this is one of the most common usages and a driving principle behind Git being a multi-stage revision control system unlike other popular ones like Svn.

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

Here is a jsfiddle HERE (not created by me) that does what you are looking for with pure css in a table. The thing to note here is the th header is set to a height of 0. Inside each th is and absolute positioned div that puts the header above the table and the scollable div that the table is in.

    <th>First Name<div>First Name</div></th>
    <th>Last Name<div>Last Name</div></th>

Adding items to a JComboBox

You can use any Object as an item. In that object you can have several fields you need. In your case the value field. You have to override the toString() method to represent the text. In your case "item text". See the example:

public class AnyObject {

    private String value;
    private String text;

    public AnyObject(String value, String text) {
        this.value = value;
        this.text = text;


    public String toString() {
        return text;

comboBox.addItem(new AnyObject("item_value", "item text"));

How do I create a message box with "Yes", "No" choices and a DialogResult?


MessageBoxResult m = MessageBox.Show("The file will be saved here.", "File Save", MessageBoxButton.OKCancel);
if(m == m.Yes)
    // Do something
else if (m == m.No)
    // Do something else

MessageBoxResult is used on Windows Phone instead of DialogResult...

find first sequence item that matches a criterion

def search(b):
  return a[k] 
 except ValueError:
    return 'not found'

it'll return the object if found else it'll return "not found"

Foreign Key to non-primary key

If you really want to create a foreign key to a non-primary key, it MUST be a column that has a unique constraint on it.

From Books Online:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

So in your case if you make AnotherID unique, it will be allowed. If you can't apply a unique constraint you're out of luck, but this really does make sense if you think about it.

Although, as has been mentioned, if you have a perfectly good primary key as a candidate key, why not use that?

How do I change the default port (9000) that Play uses when I execute the "run" command?

You can also set the HTTP port in .sbtopts in the project directory:


Then you do not have to remember to add it to the run task every time.

Tested with Play 2.1.1.

How to implement a ViewPager with different Fragments / Layouts

As this is a very frequently asked question, I wanted to take the time and effort to explain the ViewPager with multiple Fragments and Layouts in detail. Here you go.

ViewPager with multiple Fragments and Layout files - How To

The following is a complete example of how to implement a ViewPager with different fragment Types and different layout files.

In this case, I have 3 Fragment classes, and a different layout file for each class. In order to keep things simple, the fragment-layouts only differ in their background color. Of course, any layout-file can be used for the Fragments. has a orange background layout, has a green background layout and has a red background layout. Furthermore, each Fragment displays a different text, depending on which class it is from and which instance it is.

Also be aware that I am using the support-library's Fragment: (Initializes the Viewpager and has the adapter for it as an inner class). Again have a look at the imports. I am using the package.

import android.os.Bundle;

public class MainActivity extends FragmentActivity {

    protected void onCreate(Bundle savedInstanceState) {

        ViewPager pager = (ViewPager) findViewById(;
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

    private class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {

        public Fragment getItem(int pos) {
            switch(pos) {

            case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
            case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
            case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
            case 3: return ThirdFragment.newInstance("ThirdFragment, Instance 2");
            case 4: return ThirdFragment.newInstance("ThirdFragment, Instance 3");
            default: return ThirdFragment.newInstance("ThirdFragment, Default");

        public int getCount() {
            return 5;

activity_main.xml (The MainActivitys .xml file) - a simple layout file, only containing the ViewPager that fills the whole screen.


The Fragment classes, import;

public class FirstFragment extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.first_frag, container, false);

        TextView tv = (TextView) v.findViewById(;

        return v;

    public static FirstFragment newInstance(String text) {

        FirstFragment f = new FirstFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);


        return f;


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:background="@android:color/holo_orange_dark" >

        android:text="TextView" />

public class SecondFragment extends Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.second_frag, container, false);

    TextView tv = (TextView) v.findViewById(;

    return v;

public static SecondFragment newInstance(String text) {

    SecondFragment f = new SecondFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);


    return f;


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:background="@android:color/holo_green_dark" >

        android:text="TextView" />


public class ThirdFragment extends Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.third_frag, container, false);

    TextView tv = (TextView) v.findViewById(;      

    return v;

public static ThirdFragment newInstance(String text) {

    ThirdFragment f = new ThirdFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);


    return f;


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:background="@android:color/holo_red_light" >

        android:text="TextView" />


The end result is the following:

The Viewpager holds 5 Fragments, Fragments 1 is of type FirstFragment, and displays the first_frag.xml layout, Fragment 2 is of type SecondFragment and displays the second_frag.xml, and Fragment 3-5 are of type ThirdFragment and all display the third_frag.xml.

enter image description here

Above you can see the 5 Fragments between which can be switched via swipe to the left or right. Only one Fragment can be displayed at the same time of course.

Last but not least:

I would recommend that you use an empty constructor in each of your Fragment classes.

Instead of handing over potential parameters via constructor, use the newInstance(...) method and the Bundle for handing over parameters.

This way if detached and re-attached the object state can be stored through the arguments. Much like Bundles attached to Intents.


Here is a simple query containing coalesce -

select * from person where coalesce(addressId, ContactId) is null.

It will return the persons where both addressId and contactId are null.

coalesce function

  • takes least two arguments.
  • arguments must be of integer type.
  • return the first non-null argument.


  • coalesce(null, 1, 2, 3) will return 1.
  • coalesce(null, null) will return null.

Specified cast is not valid.. how to resolve this

If you are expecting double, decimal, float, integer why not use the one which accomodates all namely decimal (128 bits are enough for most numbers you are looking at).

instead of (double)value use decimal.Parse(value.ToString()) or Convert.ToDecimal(value)

Unix tail equivalent command in Windows Powershell

There have been many valid answers, however, none of them has the same syntax as tail in linux. The following function can be stored in your $Home\Documents\PowerShell\Microsoft.PowerShell_profile.ps1 for persistency (see powershell profiles documentation for more details).

This allows you to call...

tail server.log
tail -n 5 server.log
tail -f server.log
tail -Follow -Lines 5 -Path server.log

which comes quite close to the linux syntax.

function tail {
        Get the last n lines of a text file.
    .PARAMETER Follow
        output appended data as the file grows
    .PARAMETER Lines
        output the last N lines (default: 10)
        path to the text file
        PS> tail c:\server.log
        PS> tail -f -n 20 c:\server.log

        [Int]$Lines = 10,

        [parameter(Mandatory=$true, Position=5)]
    if ($Follow)
        Get-Content -Path $Path -Tail $Lines -Wait
        Get-Content -Path $Path -Tail $Lines

Removing character in list of strings

Here's a short one-liner using regular expressions:

print [re.compile(r"8").sub("", m) for m in mylist]

If we separate the regex operations and improve the namings:

pattern = re.compile(r"8") # Create the regular expression to match
res = [pattern.sub("", match) for match in mylist] # Remove match on each element
print res

TypeScript static classes

Abstract classes have been a first-class citizen of TypeScript since TypeScript 1.6. You cannot instantiate an abstract class.

Here is an example:

export abstract class MyClass {         
    public static myProp = "Hello";

    public static doSomething(): string {
      return "World";

const okay = MyClass.doSomething();

//const errors = new MyClass(); // Error

RecyclerView vs. ListView

For list views to have good performance you'll need to implement the holder pattern, and that's easy to mess up especially when you want to populate the list with several different kinds of views.

The RecyclerView bakes this pattern in, making it more difficult to mess up. It's also more flexible, making it easier to handle different layouts, that aren't straight linear, like a grid.

Eclipse error: indirectly referenced from required .class files?

It means: "A class that you use needs another class that is not on the classpath." You should make sure (as Harry Joy suggests) to add the required jar to the classpath.

Can I get Unix's pthread.h to compile in Windows?

There are, as i recall, two distributions of the gnu toolchain for windows: mingw and cygwin.

I'd expect cygwin work - a lot of effort has been made to make that a "stadard" posix environment.

The mingw toolchain uses msvcrt.dll for its runtime and thus will probably expose msvcrt's "thread" api: _beginthread which is defined in <process.h>

Order by multiple columns with Doctrine

The comment for orderBy source code notes: Keys are field and values are the order, being either ASC or DESC.. So you can do orderBy->(['field' => Criteria::ASC]).

Submitting a form by pressing enter without a submit button

This is my solution, tested in Chrome, Firefox 6 and IE7+:

    height: 1px;
    width: 1px;
    position: absolute;
    z-index: -100;

Alternative to file_get_contents?

Use cURL. This function is an alternative to file_get_contents.

function url_get_contents ($Url) {
    if (!function_exists('curl_init')){ 
        die('CURL is not installed!');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    return $output;

What is the standard exception to throw in Java for not supported/implemented operations?

If you want more granularity and better decription, you could use NotImplementedException from commons-lang

Warning: Available before versions 2.6 and after versions 3.2, only.

Extract first and last row of a dataframe in pandas

You can also use head and tail:

In [29]: pd.concat([df.head(1), df.tail(1)])
   a  b
0  1  a
3  4  d

Creating random numbers with no duplicates

Following code create a sequence random number between [1,m] that was not generated before.

public class NewClass {

    public List<Integer> keys = new ArrayList<Integer>();

    public int rand(int m) {
        int n = (int) (Math.random() * m + 1);
        if (!keys.contains(n)) {
            return n;
        } else {
            return rand(m);

    public static void main(String[] args) {
        int m = 4;
        NewClass ne = new NewClass();
        for (int i = 0; i < 4; i++) {
        System.out.println("list: " + ne.keys);

Android Studio Rendering Problems : The following classes could not be found

I had to change my values/styles.xml to

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

Before that change, it was without 'Base'.

(IntelliJ IDEA 2017.2.4)

Bind a function to Twitter Bootstrap Modal Close

Bootstrap 4:

$('#myModal').on('', function (e) {
   // call your method
}) This event is fired immediately when the hide instance method has been called. This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).

Using a dictionary to select function to execute

Simplify, simplify, simplify:

def p1(args):

def p2(more args):

myDict = {
    "P1": p1,
    "P2": p2,
    "Pn": pn

def myMain(name):

That's all you need.

You might consider the use of dict.get with a callable default if name refers to an invalid function—

def myMain(name):
    myDict.get(name, lambda: 'Invalid')()

(Picked this neat trick up from Martijn Pieters)

Why do I get a "permission denied" error while installing a gem?

Seems like a permissions issue. This is what worked for me

sudo chown -R $(whoami) /Library/Ruby/Gems/*

or in your case

sudo chown -R $(whoami) /usr/local/lib/ruby/gems/2.0.0/gems/

What does this do:

This is telling the system to change the files to change the ownership to the current user. Something must have gotten messed up when something got installed. Usually this is because there are multiple accounts or users are using sudo to install when they should not always have to.

is inaccessible due to its protection level

You need to use the public properties from Main, and not try to directly change the internal variables.

How do I check out a remote Git branch?

To get newly created branches

git fetch

To switch into another branch

git checkout BranchName

How can I add shadow to the widget in flutter?

Add box shadow to container in flutter

      margin: EdgeInsets.only(left: 30, top: 100, right: 30, bottom: 50),
      height: double.infinity,
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
            bottomLeft: Radius.circular(10),
            bottomRight: Radius.circular(10)
        boxShadow: [
            color: Colors.grey.withOpacity(0.5),
            spreadRadius: 5,
            blurRadius: 7,
            offset: Offset(0, 3), // changes position of shadow

Here is my output enter image description here

Get data from JSON file with PHP

Use json_decode to transform your JSON into a PHP array. Example:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

glm rotate usage in Opengl

You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).

All you need to do is (see here)

Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

Note that to convert from degrees to radians, use glm::radians(degrees)

That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.

note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6

Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

Disallow Twitter Bootstrap modal window from closing

Well, this is another solution that some of you guys might be looking for (as I was..)

My problem was similar, the modal box was closing while the iframe I had inside was loading, so I had to disable the modal dismiss until the Iframe finishes loading, then re-enable.

The solutions presented here were not working 100%.

My solution was this:

showLocationModal = function(loc){

    var is_loading = true;

    if(is_loading === true) {

        is_loading  = false;
        var $modal   = $('#locationModal');


        // prevent Modal to close before the iframe is loaded
        $modal.on("hide", function (e) {
            if(is_loading !== true) {
                return false

        // populate Modal
        $modal.find('.modal-body iframe').hide().attr('src',{

            is_loading = true;

So I temporarily prevent the Modal from closing with:

$modal.on("hide", function (e) {
    if(is_loading !== true) {
        return false

But ith the var is_loading that will re enable closing after the Iframe has loaded.

Array versus List<T>: When to use which?

Really just answering to add a link which I'm surprised hasn't been mentioned yet: Eric's Lippert's blog entry on "Arrays considered somewhat harmful."

You can judge from the title that it's suggesting using collections wherever practical - but as Marc rightly points out, there are plenty of places where an array really is the only practical solution.

Caching a jquery ajax response in javascript/browser

        function getDatas() {
            let cacheKey = 'memories';

            if (cacheKey in localStorage) {
                let datas = JSON.parse(localStorage.getItem(cacheKey));

                // if expired
                if (datas['expires'] < {

                } else {
            } else {
                    "dataType": "json",
                    "success": function(datas, textStatus, jqXHR) {
                        let today = new Date();

                        datas['expires'] = today.setDate(today.getDate() + 7) // expires in next 7 days


                        localStorage.setItem(cacheKey, JSON.stringify(datas));
                    "url": "http://localhost/phunsanit/snippets/PHP/json.json_encode.php",

        function setDatas(datas) {
            // display json as text

            // your code here


        // call

enter link description here

Check whether a value is a number in JavaScript or jQuery

there is a function called isNaN it return true if it's (Not-a-number) , so u can check for a number this way

   //do some thing if it's a number
   //do some thing if it's NOT a number

hope it works

Angular and debounce

I solved this by writing a debounce decorator. The problem described could be solved by applying the @debounceAccessor to the property's set accessor.

I've also supplied an additional debounce decorator for methods, which can be useful for other occasions.

This makes it very easy to debounce a property or a method. The parameter is the number of milliseconds the debounce should last, 100 ms in the example below.

set myProperty(value) {
  this._myProperty = value;

myMethod (a, b, c) {
  let d = a + b + c;
  return d;

And here's the code for the decorators:

function debounceMethod(ms: number, applyAfterDebounceDelay = false) {

  let timeoutId;

  return function (target: Object, propName: string, descriptor: TypedPropertyDescriptor<any>) {
    let originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
      if (timeoutId) return;
      timeoutId = window.setTimeout(() => {
        if (applyAfterDebounceDelay) {
          originalMethod.apply(this, args);
        timeoutId = null;
      }, ms);

      if (!applyAfterDebounceDelay) {
        return originalMethod.apply(this, args);

function debounceAccessor (ms: number) {

  let timeoutId;

  return function (target: Object, propName: string, descriptor: TypedPropertyDescriptor<any>) {
    let originalSetter = descriptor.set;
    descriptor.set = function (...args: any[]) {
      if (timeoutId) return;
      timeoutId = window.setTimeout(() => {
        timeoutId = null;
      }, ms);
      return originalSetter.apply(this, args);

I added an additional parameter for the method decorator which let's you trigger the method AFTER the debounce delay. I did that so I could for instance use it when coupled with mouseover or resize events, where I wanted the capturing to occur at the end of the event stream. In this case however, the method won't return a value.

bash shell nested for loop

The question does not contain a nested loop, just a single loop. But THIS nested version works, too:

# for i in c d; do for j in a b; do echo $i $j; done; done
c a
c b
d a
d b

Getting key with maximum value in dictionary?

key, value = max(stats.iteritems(), key=lambda x:x[1])

If you don't care about value (I'd be surprised, but) you can do:

key, _ = max(stats.iteritems(), key=lambda x:x[1])

I like the tuple unpacking better than a [0] subscript at the end of the expression. I never like the readability of lambda expressions very much, but find this one better than the operator.itemgetter(1) IMHO.

PSQLException: current transaction is aborted, commands ignored until end of transaction block

This is very weird behavior of PostgreSQL, it is even not " in-line with the PostgreSQL philosophy of forcing the user to make everything explicit" - as the exception was caught and ignored explicitly. So even this defense does not hold. Oracle in this case behaves much more user-friendly and (as for me) correctly - it leaves a choice to the developer.

RuntimeWarning: DateTimeField received a naive datetime

If you are trying to transform a naive datetime into a datetime with timezone in django, here is my solution:

>>> import datetime
>>> from django.utils import timezone
>>> t1 = datetime.datetime.strptime("2019-07-16 22:24:00", "%Y-%m-%d %H:%M:%S")
>>> t1
    datetime.datetime(2019, 7, 16, 22, 24)
>>> current_tz = timezone.get_current_timezone()
>>> t2 = current_tz.localize(t1)
>>> t2
    datetime.datetime(2019, 7, 16, 22, 24, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)

t1 is a naive datetime and t2 is a datetime with timezone in django's settings.