Programs & Examples On #Cglayer

How to initialize std::vector from C-style array?

Don't forget that you can treat pointers as iterators:

w_.assign(w, w + len);

How to zero pad a sequence of integers in bash so that all have the same width?

Easier still you can just do

for i in {00001..99999}; do
  echo $i

How do you change the server header returned by nginx?

Like Apache, this is a quick edit to the source and recompile. From

The Server: string is the header which is sent back to the client to tell them what type of http server you are running and possibly what version. This string is used by places like Alexia and Netcraft to collect statistics about how many and of what type of web server are live on the Internet. To support the author and statistics for Nginx we recommend keeping this string as is. But, for security you may not want people to know what you are running and you can change this in the source code. Edit the source file src/http/ngx_http_header_filter_module.c at look at lines 48 and 49. You can change the String to anything you want.

## vi src/http/ngx_http_header_filter_module.c (lines 48 and 49)
static char ngx_http_server_string[] = "Server:" CRLF;
static char ngx_http_server_full_string[] = "Server:" CRLF;

March 2011 edit: Props to Flavius below for pointing out a new option, replacing Nginx's standard HttpHeadersModule with the forked HttpHeadersMoreModule. Recompiling the standard module is still the quick fix, and makes sense if you want to use the standard module and won't be changing the server string often. But if you want more than that, the HttpHeadersMoreModule is a strong project and lets you do all sorts of runtime black magic with your HTTP headers.

Git with SSH on Windows

I've found my ssh.exe in "C:/Program Files/Git/usr/bin" directory

Attempt to write a readonly database - Django w/ SELinux error

I had this issue and I solved it by creating a directory in mysite folder to hold my db.sqlite3 file. so I did /home/user/src/mysite/database/db.sqlite3. In my django setting file I change my

'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': "/home/user/src/mysite/database/db.sqlite3" ,

I did this to make Django aware that I am storing my database in a sub directory of the base directory, which mysite in my case. Now you need to grant the permission to apache to be able read write the database.

chown user:www-data database/db.sqlite3
chown user:www-data database 
chmod 755 database
 chmod 755 database/db.sqlite3

This solved my problem. Here is a list of the different permissions. You can use choose the one that fits you but avoid 777 and 666

-rw------- (600) -- Only the user has read and write permissions.

-rw-r--r-- (644) -- Only user has read and write permissions; the group and others can read only.

-rwx------ (700) -- Only the user has read, write and execute permissions.

-rwxr-xr-x (755) -- The user has read, write and execute permissions; the group and others can only read and execute.

-rwx--x--x (711) -- The user has read, write and execute permissions; the group and others can only execute.

-rw-rw-rw- (666) -- Everyone can read and write to the file. Bad idea.

-rwxrwxrwx (777) -- Everyone can read, write and execute. Another bad idea.

Here are a couple common settings for directories:

drwx------ (700) -- Only the user can read, write in this directory.

drwxr-xr-x (755) -- Everyone can read the directory, but its contents can only be changed by the user.

here is a link to an article to [learn more][1]


Exit a while loop in VBS/VBA

Use Do...Loop with Until keyword

Do Until //certain_condition_to_break_loop

This loop will continue to execute, Until the condition becomes true

While...Wend is the old syntax and does not provide feature to break loop! Prefer do while loops

mssql '5 (Access is denied.)' error during restoring database

I found this, and it worked for me:

CREATE LOGIN BackupRestoreAdmin WITH PASSWORD='$tr0ngP@$$w0rd'
CREATE USER BackupRestoreAdmin FOR LOGIN BackupRestoreAdmin
EXEC sp_addsrvrolemember 'BackupRestoreAdmin', 'dbcreator'
EXEC sp_addrolemember 'db_owner','BackupRestoreAdmin'

How to parse JSON to receive a Date object in JavaScript?

function parseJsonDate(jsonDate) {

    var fullDate = new Date(parseInt(jsonDate.substr(6)));
    var twoDigitMonth = (fullDate.getMonth() + 1) + ""; if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;

    var twoDigitDate = fullDate.getDate() + ""; if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
    var currentDate = twoDigitMonth + "/" + twoDigitDate + "/" + fullDate.getFullYear();

    return currentDate;

a href link for entire div in HTML/CSS

A link with <div> tags:

<div style="cursor: pointer;" onclick="window.location='';">
     Something in the div 

A link with <a> tags:

<a href="">
        Something in the div 

Private class declaration

Private outer class would be useless as nothing can access it.

See more details:

Java: Why can we define a top level class as private?

Multiple argument IF statement - T-SQL

Seems to work fine.

If you have an empty BEGIN ... END block you might see

Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'END'.

How to add data via $.ajax ( serialize() + extra data ) like this

You can do it like this:

postData[postData.length] = { name: "variable_name", value: variable_value };

Add numpy array as column to Pandas data frame

You can add and retrieve a numpy array from dataframe using this:

import numpy as np
import pandas as pd

df = pd.DataFrame({'b':range(10)}) # target dataframe
a = np.random.normal(size=(10,2)) # numpy array
df['a']=a.tolist() # save array
np.array(df['a'].tolist()) # retrieve array

This builds on the previous answer that confused me because of the sparse part and this works well for a non-sparse numpy arrray.

Display a jpg image on a JPanel

I'd probably use an ImageIcon and set it on a JLabel which I'd add to the JPanel.

Here's Sun's docs on the subject matter.

Find PHP version on windows command line

This how I check php version

PS C:\Windows\system32> php -version


PHP 7.2.7 (cli) (built: Jun 19 2018 23:44:15) ( NTS MSVC15 (Visual C++ 2017) x86 )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

PS C:\Windows\system32>

@selector() in Swift?

If you want to pass a parameter to the function from the NSTimer then here is your solution:

var somethingToPass = "It worked"

let timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "tester:", userInfo: somethingToPass, repeats: false)

func tester(timer: NSTimer)
    let theStringToPrint = timer.userInfo as String

Include the colon in the selector text (tester:), and your parameter(s) go in userInfo.

Your function should take NSTimer as a parameter. Then just extract userInfo to get the parameter that passed.

is it possible to evenly distribute buttons across the width of an android linearlayout

You may use it with like the following.


Hiding user input on terminal in Linux script

A variation on both @SiegeX and @mklement0's excellent contributions: mask user input; handle backspacing; but only backspace for the length of what the user has input (so we're not wiping out other characters on the same line) and handle control characters, etc... This solution was found here after so much digging!

# Read and echo a password, echoing responsive 'stars' for input characters
# Also handles: backspaces, deleted and ^U (kill-line) control-chars
unset PWORD
echo -n 'password: ' 1>&2
while true; do
  IFS= read -r -N1 -s char
  # Note a NULL will return a empty string
  # Convert users key press to hexadecimal character code
  code=$(printf '%02x' "'$char") # EOL (empty char) -> 00
  case "$code" in
  ''|0a|0d) break ;;   # Exit EOF, Linefeed or Return
  08|7f)  # backspace or delete
      if [ -n "$PWORD" ]; then
        PWORD="$( echo "$PWORD" | sed 's/.$//' )"
        echo -n $'\b \b' 1>&2
  15) # ^U or kill line
      echo -n "$PWORD" | sed 's/./\cH \cH/g' >&2
  [01]?) ;;                        # Ignore ALL other control characters
  *)  PWORD="$PWORD$char"
      echo -n '*' 1>&2
echo $PWORD

dyld: Library not loaded ... Reason: Image not found

I fixed this by reinstalling Homebrew


ruby -e "$(curl -fsSL"


/usr/bin/ruby -e "$(curl -fsSL"

Why can templates only be implemented in the header file?

Just to add something noteworthy here. One can define methods of a templated class just fine in the implementation file when they are not function templates.


template <class T> 
class QueueA {
    int size;
    template <class T> T dequeue() {
       // implementation here

    bool isEmpty();



// implementation of regular methods goes like this:
template <class T> bool QueueA<T>::isEmpty() {
    return this->size == 0;

    QueueA<char> Q;


Replace HTML page with contents retrieved via AJAX

I'm assuming you are using jQuery or something similar. If you are using jQuery, then the following should work:

   <script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

Chrome doesn't delete session cookies

I had to both, unchecked, under advanced settings of Chrome :

  • 'Continue running background apps when Google Chrome is closed'
  • "Continue where I left off", "On startup"

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

I have used <div class="container-fluid" style="padding: 0px !important"> and it seems to be working.

C# Passing Function as Argument

public static T Runner<T>(Func<T> funcToRun)
    //Do stuff before running function as normal
    return funcToRun();


var ReturnValue = Runner(() => GetUser(99));

Clear the entire history stack and start a new activity on Android

For me none of the above methods not work.

Just do this to clear all previous activity:

finishAffinity() // if you are in fragment use activity.finishAffinity()
Intent intent = new Intent(this, DestActivity.class); // with all flags you want

Getting the text from a drop-down box

Please try the below this is the easiest way and it works perfectly

var newSkill_Text = document.getElementById("newSkill")[document.getElementById("newSkill").selectedIndex];

How to correctly use the extern keyword in C

"extern" changes the linkage. With the keyword, the function / variable is assumed to be available somewhere else and the resolving is deferred to the linker.

There's a difference between "extern" on functions and on variables: on variables it doesn't instantiate the variable itself, i.e. doesn't allocate any memory. This needs to be done somewhere else. Thus it's important if you want to import the variable from somewhere else. For functions, this only tells the compiler that linkage is extern. As this is the default (you use the keyword "static" to indicate that a function is not bound using extern linkage) you don't need to use it explicitly.

Multiple input in JOptionPane.showInputDialog

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
} else {
    System.out.println("Login canceled");

Difference between checkout and export in SVN

if you are using tortoise svn client - while exporting - it displays ..export / checkout , it is confusing , it is just export only. only view/read use export , to commit use - "checkout"

Android, How to create option Menu

public class MenuTest extends Activity {

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(, menu);

        // return true so that the menu pop up is opened
        return true; 

and don't forget to press the menu button or icon on Emulator or device

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

public class User {

    private Long idUser;

    private String userName;

    private Area area;

    public Long getIdUser() {
        return idUser;

    public void setIdUser(Long idUser) {
        this.idUser = idUser;

    public String getUserName() {
        return userName;

    public void setUserName(String userName) {
        this.userName = userName;

    public Area getArea() {
        return area;

    public void setArea(Area area) {
        this.area = area;

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

@Table(name = "area")
public class Area {

    private Long idArea;

    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;

    public void setIdArea(Long idArea) {
        this.idArea = idArea;

    public String getAreaName() {
        return areaName;

    public void setAreaName(String areaName) {
        this.areaName = areaName;

    public User getUser() {
        return user;

    public void setUser(User user) {
        this.user = user;

Print commit message of a given commit in git

git show is more a plumbing command than git log, and has the same formatting options:

git show -s --format=%B SHA1

How to test if a file is a directory in a batch script?

You can do it like so:

IF EXIST %VAR%\NUL ECHO It's a directory

However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows:

FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory

The %%~si converts %%i to an 8.3 filename. To see all the other tricks you can perform with FOR variables enter HELP FOR at a command prompt.

(Note - the example given above is in the format to work in a batch file. To get it work on the command line, replace the %% with % in both places.)

How to trigger a phone call when clicking a link in a web page on mobile phone

The proper URL scheme is tel:[number] so you would do

<a href="tel:5551234567"><img src="callme.jpg" /></a>

Dynamic Web Module 3.0 -- 3.1

I opened the project org.eclipse.wst.common.project.facet.core.xml and first changed then removed line with web module tag. Cleaned project and launched on Tomcat each time but it still didn't run. Returned line (as was) and cleaned project. Opened Tomcat settings in Eclipse and manually added project to Tomcat startup (Right click + Add and Remove). Clicked on project and selected Run on server....and everything was fine.

How do I write a Python dictionary to a csv file?

You are using DictWriter.writerows() which expects a list of dicts, not a dict. You want DictWriter.writerow() to write a single row.

You will also want to use DictWriter.writeheader() if you want a header for you csv file.

You also might want to check out the with statement for opening files. It's not only more pythonic and readable but handles closing for you, even when exceptions occur.

Example with these changes made:

import csv

my_dict = {"test": 1, "testing": 2}

with open('mycsvfile.csv', 'w') as f:  # You will need 'wb' mode in Python 2.x
    w = csv.DictWriter(f, my_dict.keys())

Which produces:


Zoom to fit all markers in Mapbox or Leaflet

You have an array of L.Marker:

let markers = [marker1, marker2, marker3]

let latlngs = => marker.getLatLng())

let latlngBounds = L.latLngBounds(latlngs)

// OR with a smooth animation
// map.flyToBounds(latlngBounds)

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

@Martin Devillers solution works fine. For completeness, providing the steps below:

  1. Put your wsdl to resource directory like : src/main/resource
  2. In pom file, add both wsdlDirectory and wsdlLocation(don't miss / at the beginning of wsdlLocation), like below. While wsdlDirectory is used to generate code and wsdlLocation is used at runtime to create dynamic proxy.

  3. Then in your java code(with no-arg constructor):

    MyPort myPort = new MyPortService().getMyPort();
  4. Here is the full code generation part in pom file, with fluent api in generated code.


Jquery to get SelectedText from dropdown

If you're using a <select>, $(this).val() inside the change() event returns the value of the current selected option. Using text() is redundant most of the time, since it's usually identical to the value, and in case is different, you'll probably end up using the value in the back-end and not the text. So you can just do this:

var selectedText2 = $(this).val();

EDIT: Note that in case your value attribute is empty, most browsers use the contents as value, so it'll work either way.

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)

Changing the interval of SetInterval while it's running

I had the same question as the original poster, did this as a solution. Not sure how efficient this is ....

interval = 5000; // initial condition
var run = setInterval(request , interval); // start setInterval as "run"

    function request() { 

        console.log(interval); // firebug or chrome log
        clearInterval(run); // stop the setInterval()

         // dynamically change the run interval
        if(interval>200 ){
          interval = interval*.8;
          interval = interval*1.2;

        run = setInterval(request, interval); // start the setInterval()


How do I check for null values in JavaScript?

Actually I think you may need to use if (value !== null || value !== undefined) because if you use if (value) you may also filter 0 or false values.

Consider these two functions:

const firstTest = value => {
    if (value) {
    } else {
const secondTest = value => {
    if (value !== null && value !== undefined) {
    } else {

firstTest(0);            // result: failed
secondTest(0);           // result: passed

firstTest(false);        // result: failed
secondTest(false);       // result: passed

firstTest('');           // result: failed
secondTest('');          // result: passed

firstTest(null);         // result: failed
secondTest(null);        // result: failed

firstTest(undefined);    // result: failed
secondTest(undefined);   // result: failed

In my situation, I just needed to check if the value is null and undefined and I did not want to filter 0 or false or '' values. so I used the second test, but you may need to filter them too which may cause you to use first test.

TypeError: unhashable type: 'list' when using built-in set function

Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.

mylist = [[1,2,3,4],[4,5,6,7]]
mylist2 = []
for thing in mylist:
    thing = tuple(thing)

.htaccess rewrite to redirect root URL to subdirectory

This seemed the simplest solution:

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/$
RewriteRule (.*) [R=301,L]

I was getting redirect loops with some of the other solutions.

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Check your system clock,

$ date

If it's not correct the certificate check will fail. To correct the system clock,

$ apt-get install ntp

The clock should synchronise itself.

Finally enter the clone command again.

How should I have explained the difference between an Interface and an Abstract class?

I will try to answer using practical scenario to show the distinction between the two.

Interfaces come with zero payload i.e. no state has to be maintained and thus are better choice to just associate a contract (capability) with a class.

For example, say I have a Task class that performs some action, now to execute a task in separate thread I don't really need to extend Thread class rather better choice is to make Task implement Runnable interface (i.e. implement its run() method) and then pass object of this Task class to a Thread instance and call its start() method.

Now you can ask what if Runnable was a abstract class?

Well technically that was possible but design wise that would have been a poor choice reason being:

  • Runnable has no state associated with it and neither it 'offers' any default implementation for the run() method
  • Task would have to extend it thus it couldn't extend any other class
  • Task has nothing to offer as specialization to Runnable class, all it needs is to override run() method

In other words, Task class needed a capability to be run in a thread which it achieved by implementing Runnable interface verses extending the Thread class that would make it a thread.

Simply put us interface to define a capability (contract), while use a abstract class to define skeleton (common/partial) implementation of it.

Disclaimer: silly example follows, try not to judge :-P

interface Forgiver {
    void forgive();

abstract class GodLike implements Forgiver {
    abstract void forget();
    final void forgive() {

Now you have been given a choice to be GodLike but you may choose to be Forgiver only (i.e. not GodLike) and do:

class HumanLike implements Forgiver {
    void forgive() {
       // forgive but remember    

Or you may may choose to be GodLike and do:

class AngelLike extends GodLike {
    void forget() {
       // forget to forgive     

P.S. with java 8 interface can also have static as well default (overridable implementation) methods and thus difference b/w interface and abstract class is even more narrowed down.

'Source code does not match the bytecode' when debugging on a device

I tried all the solution given here and none of them worked for me. In version 2019.1.3 I just clean & rebuild artifact and it worked; first do Build -> Build Artifacts... -> <select your artifact> -> Clean then click Build or Rebuild from same place.

What is a Subclass

A sub class is a small file of a program that extends from some other class. For example you make a class about cars in general and have basic information that holds true for all cars with your constructors and stuff then you have a class that extends from that on a more specific car or line of cars that would have new variables/methods. I see you already have plenty of examples of code from above by the time I get to post this but I hope this description helps.

Use jQuery to navigate away from page

window.location.href = "/somewhere/else";

How can I read input from the console using the Scanner class in Java?

When the user enters his/her username, check for valid entry also.

java.util.Scanner input = new java.util.Scanner(;
String userName;
final int validLength = 6; // This is the valid length of an user name

System.out.print("Please enter the username: ");
userName = input.nextLine();

while(userName.length() < validLength) {

    // If the user enters less than validLength characters
    // ask for entering again
        "\nUsername needs to be " + validLength + " character long");

    System.out.print("\nPlease enter the username again: ");
    userName = input.nextLine();

System.out.println("Username is: " + userName);

Why would you use String.Equals over ==?

There is one subtle but very important difference between == and the String.Equals methods:

class Program
    static void Main(string[] args)
        CheckEquality("a", "a");
        CheckEquality("a", "ba".Substring(1));

    static void CheckEquality<T>(T value1, T value2) where T : class
        Console.WriteLine("value1: {0}", value1);
        Console.WriteLine("value2: {0}", value2);

        Console.WriteLine("value1 == value2:      {0}", value1 == value2);
        Console.WriteLine("value1.Equals(value2): {0}", value1.Equals(value2));

        if (typeof(T).IsEquivalentTo(typeof(string)))
            string string1 = (string)(object)value1;
            string string2 = (string)(object)value2;
            Console.WriteLine("string1 == string2:    {0}", string1 == string2);

Produces this output:

value1: a
value2: a
value1 == value2:      True
value1.Equals(value2): True
string1 == string2:    True
value1: a
value2: a
value1 == value2:      False
value1.Equals(value2): True
string1 == string2:    True

You can see that the == operator is returning false to two obviously equal strings. Why? Because the == operator in use in the generic method is resolved to be the op_equal method as defined by System.Object (the only guarantee of T the method has at compile time), which means that it's reference equality instead of value equality.

When you have two values typed as System.String explicitly, then == has a value-equality semantic because the compiler resolves the == to System.String.op_equal instead of System.Object.op_equal.

So to play it safe, I almost always use String.Equals instead to that I always get the value equality semantics I want.

And to avoid NullReferenceExceptions if one of the values is null, I always use the static String.Equals method:

bool true = String.Equals("a", "ba".Substring(1));

How can I open two pages from a single click without using JavaScript?

If you have the authority to edit the pages to be opened, you can href to 'A' page and in the A page you can put link to B page in onpageload attribute of body tag.

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The Accept Ranges header (the bit in writeHead()) is required for the HTML5 video controls to work.

I think instead of just blindly send the full file, you should first check the Accept Ranges header in the REQUEST, then read in and send just that bit. fs.createReadStream support start, and end option for that.

So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream to send the requested part to the client.

var fs = require("fs"),
    http = require("http"),
    url = require("url"),
    path = require("path");

http.createServer(function (req, res) {
  if (req.url != "/movie.mp4") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
  } else {
    var file = path.resolve(__dirname,"movie.mp4");
    fs.stat(file, function(err, stats) {
      if (err) {
        if (err.code === 'ENOENT') {
          // 404 Error if file not found
          return res.sendStatus(404);
      var range = req.headers.range;
      if (!range) {
       // 416 Wrong range
       return res.sendStatus(416);
      var positions = range.replace(/bytes=/, "").split("-");
      var start = parseInt(positions[0], 10);
      var total = stats.size;
      var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
      var chunksize = (end - start) + 1;

      res.writeHead(206, {
        "Content-Range": "bytes " + start + "-" + end + "/" + total,
        "Accept-Ranges": "bytes",
        "Content-Length": chunksize,
        "Content-Type": "video/mp4"

      var stream = fs.createReadStream(file, { start: start, end: end })
        .on("open", function() {
        }).on("error", function(err) {

What's the best way to iterate an Android Cursor?

The cursor is the Interface that represents a 2-dimensional table of any database.

When you try to retrieve some data using SELECT statement, then the database will 1st create a CURSOR object and return its reference to you.

The pointer of this returned reference is pointing to the 0th location which is otherwise called as before the first location of the Cursor, so when you want to retrieve data from the cursor, you have to 1st move to the 1st record so we have to use moveToFirst

When you invoke moveToFirst() method on the Cursor, it takes the cursor pointer to the 1st location. Now you can access the data present in the 1st record

The best way to look :

Cursor cursor

for (cursor.moveToFirst(); 
     cursor.moveToNext()) {

Server.Mappath in C# classlibrary

Use this System.Web.Hosting.HostingEnvironment.MapPath().


Wonder why nobody mentioned it here.

Best programming based games

I played RoboWar, but the programming game I remember on the Mac was Chipwits. It came out in 1984. Completely graphical, but entertaining. From what I've seen of Lego Mindstorms, the programming style is similar.

php is null or empty?

This is not a bug but PHP normal behavior. It happens because the == operator in PHP doesn't check for type.

'' == null == 0 == false

If you want also to check if the values have the same type, use === instead. To study in deep this difference, please read the official documentation.

What is the better API to Reading Excel sheets in java - JXL or Apache POI

I have used POI.

If you use that, keep on eye those cell formatters: create one and use it several times instead of creating each time for cell, it isa huge memory consumption difference or large data.

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {



class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;

  //getters setters

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

CMD: Export all the screen content to a text file

If you are looking for each command separately

To export all the output of the command prompt in text files. Simply follow the following syntax.

C:> [syntax] >file.txt

The above command will create result of syntax in file.txt. Where new file.txt will be created on the current folder that you are in.

For example,

C:Result> dir >file.txt

To copy the whole session, Try this:

Copy & Paste a command session as follows:

1.) At the end of your session, click the upper left corner to display the menu.
Then select.. Edit -> Select all

2.) Again, click the upper left corner to display the menu.
Then select.. Edit -> Copy

3.) Open your favorite text editor and use Ctrl+V or your normal
Paste operation to paste in the text.

SQL Server - Return value after INSERT

* Parameter order in the connection string is sometimes important. * The Provider parameter's location can break the recordset cursor after adding a row. We saw this behavior with the SQLOLEDB provider.

After a row is added, the row fields are not available, UNLESS the Provider is specified as the first parameter in the connection string. When the provider is anywhere in the connection string except as the first parameter, the newly inserted row fields are not available. When we moved the the Provider to the first parameter, the row fields magically appeared.

How many parameters are too many?

I generally agree with 5, however, if there is a situation where I need more and it's the clearest way to solve the problem, then I would use more.

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

To use arrow functions with, I made a helper function on the object prototype:

  // Using
  // @func = function() {use this here} or This => {use This here}
  using(func) {
    return, this);


  var obj = {f:3, a:2}
  .using(This => This.f + This.a) // 5


You don't NEED a helper. You could do:

var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5

How to have a drop down <select> field in a rails form?

Or for custom options

<%= :desired_attribute, ['option1', 'option2']%>

psql: FATAL: role "postgres" does not exist

This is the only one that fixed it for me :

createuser -s -U $USER

Phone number formatting an EditText in Android

You can accept only numbers and phone number type using java code

 EditText number1 = (EditText) layout.findViewById(; 
      number1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(14)}); // 14 is max digits

This code will avoid lot of validations after reading input

Trigger event on body load complete js/jquery

When the page loads totally (dom, images, ...)

    // full load

When DOM elements load (not necessary all images will be loaded)

    // DOM Ready

Then you can trigger any event


Can Twitter Bootstrap alerts fade in as well as out?

Of course, Yes. Use this simple file in your project:

First add you HTML like this:

<div id="messagebox" class="alert hide"></div>

and then use:

$("#messagebox").message({text: "Hello world!", type: "error"});

You can pass all bootstrap alert types such as error, success and warning to type property as options.

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 -

Microsoft Reference Guide (More Complicated, but resourceful none the less) -

The import org.apache.commons cannot be resolved in eclipse juno

If you got a Apache Maven project, it's easy to use this package in your project. Just specify it in your pom.xml:





Subscript out of range error in this Excel VBA script

This looks a little better than your previous version but get rid of that .Activate on that line and see if you still get that error.

Dim sh1 As Worksheet
set sh1 = Workbooks.Add(filenum(lngPosition) & ".csv")

Creates a worksheet object. Not until you create that object do you want to start working with it. Once you have that object you can do the following:


The sh1. explicitely tells Excel which object you are saying to work with... otherwise if you start selecting other worksheets while this code is running you could wind up pasting data to the wrong place.

Where will log4net create this log file?

Log4net is saving into your project folder. Something like: \SolutionFolder\ProjectFolder\bin\SolutionConfiguration\logs\log-file.txt.


  • SolutionFolder is where you save your solution
  • ProjectFolder is the folder where your project lives into the solution and
  • SolutionConfiguration is the folder that contais all the binaries of your project (the default is Debug or Release)

Hope this helps!

How do I remove the non-numeric character from a string in java?

Java 8 collection streams :

StringBuilder sb = new StringBuilder();
test.chars().mapToObj(i -> (char) i).filter(Character::isDigit).forEach(sb::append);

How to transform currentTimeMillis to a readable date format?

It will work.

long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");    
Date resultdate = new Date(yourmilliseconds);

var.replace is not a function

In case of a number you can try to convert to string:

var stringValue = str.toString();
return stringValue.replace(/^\s+|\s+$/g,'');

Why does ++[[]][+[]]+[+[]] return the string "10"?

+[] evaluates to 0 [...] then summing (+ operation) it with anything converts array content to its string representation consisting of elements joined with comma.

Anything other like taking index of array (have grater priority than + operation) is ordinal and is nothing interesting.

How to set text size in a button in html

Without using inline CSS you could set the text size of all your buttons using:

input[type="submit"], input[type="button"] {
  font-size: 14px;

Why calling react setState method doesn't mutate the state immediately?

As mentioned in the React documentation, there is no guarantee of setState being fired synchronously, so your console.log may return the state prior to it updating.

Michael Parker mentions passing a callback within the setState. Another way to handle the logic after state change is via the componentDidUpdate lifecycle method, which is the method recommended in React docs.

Generally we recommend using componentDidUpdate() for such logic instead.

This is particularly useful when there may be successive setStates fired, and you would like to fire the same function after every state change. Rather than adding a callback to each setState, you could place the function inside of the componentDidUpdate, with specific logic inside if necessary.

// example
componentDidUpdate(prevProps, prevState) {
  if (this.state.value > prevState.value) {;  

How to overcome the CORS issue in ReactJS

You can have your React development server proxy your requests to that server. Simply send your requests to your local server like this: url: "/" And add the following line to your package.json file

"proxy": ""

Though if you are sending CORS requests to multiple sources, you'll have to manually configure the proxy yourself This link will help you set that up Create React App Proxying API requests

What does value & 0xff do in Java?

In 32 bit format system the hexadecimal value 0xff represents 00000000000000000000000011111111 that is 255(15*16^1+15*16^0) in decimal. and the bitwise & operator masks the same 8 right most bits as in first operand.

C# create simple xml file

I'd recommend serialization,

public class Person
      public  string FirstName;
      public  string MI;
      public  string LastName;

static void Serialize()
      clsPerson p = new Person();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(System.Console.Out, p);
      System.Console.WriteLine(" --- Press any key to continue --- ");

You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:

using System;
using System.Xml;

public class GenerateXml {
    private static void Main() {
        XmlDocument doc = new XmlDocument();
        XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

        XmlNode productsNode = doc.CreateElement("products");

        XmlNode productNode = doc.CreateElement("product");
        XmlAttribute productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "01";

        XmlNode nameNode = doc.CreateElement("Name");
        XmlNode priceNode = doc.CreateElement("Price");

        // Create and add another product node.
        productNode = doc.CreateElement("product");
        productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "02";
        nameNode = doc.CreateElement("Name");
        priceNode = doc.CreateElement("Price");


And if it needs to be fast, use XmlWriter:

public static void WriteXML()
    // Create an XmlWriterSettings object with the correct options.
    System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "    "; //  "\t";
    settings.OmitXmlDeclaration = false;
    settings.Encoding = System.Text.Encoding.UTF8;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))


        for (int i = 0; i < 100; ++i)
            writer.WriteElementString("item", "Book "+ (i+1).ToString());


    } // End Using writer 


And btw, the fastest way to read XML is XmlReader:

public static void ReadXML()
    using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(""))
        while (xmlReader.Read())
            if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
                if (xmlReader.HasAttributes)
                    System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));

        } // Whend 

    } // End Using xmlReader


And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

How to get the current time in Google spreadsheet using script editor?

Use the Date object provided by javascript. It's not unique or special to Google's scripting environment.

Eclipse copy/paste entire line keyboard shortcut

The Ctrl+Alt+Down / Ctrl+Alt+Up flips my screen so I overrode that in the Eclipse shortcuts via Window => Preferences => General => Keys. Search for "dupl" to find the Duplicate Lines command. I overrode the default and chose Ctrl+Shift+D. For me, that's easy to remember just like Ctrl+D to delete lines

Read CSV file column by column

I sugges to use the Apache Commons CSV

Here is one example:

    Path currentRelativePath = Paths.get("");
    String currentPath = currentRelativePath.toAbsolutePath().toString();
    String csvFile = currentPath + "/pathInYourProject/test.csv";

    Reader in;
    Iterable<CSVRecord> records = null;
        in = new FileReader(csvFile);
        records = CSVFormat.EXCEL.withHeader().parse(in); // header will be ignored
    catch (IOException e)

    for (CSVRecord record : records) {
        String line = "";
        for ( int i=0; i < record.size(); i++)
            if ( line == "" )
                line = line.concat(record.get(i));
                line = line.concat("," + record.get(i));
        System.out.println("read line: " + line);

It automaticly recognize , and " but not ; (maybe it can be configured...).

My example file is:


And output is:

read line: val1,val2,val3
read line: val4,val5
read line: val6;val7;"val8"

Last line is considered like one value.

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

  1. Opened package.json
  2. Changed "@angular-devkit/build-angular": "^0.800.0" to "@angular-devkit/build-angular": "^0.10.0" or changed Changing from "@angular-devkit/build-angular": "^0.802.1" to "@angular-devkit/build-angular": "^0.13.9"
  3. Run npm install
  4. Run ng serve

The original version can be diferent, but is necessary change it at 0.10.0 or 0.13.9 version that fix the problem

How to edit a JavaScript alert box title?

When you start up or just join a project based on webapplications, the design of interface is maybe good. Otherwise this should be changed. In order to Web 2.0 applications you will work with dynamic contents, many effects and other stuff. All these things are fine, but no one thought about to style up the JavaScript alert and confirm boxes. Here is the they way,.. completely dynamic, JS and CSS driven Create simple html file

   <meta http-equiv="Content-Style-Type" content="text/css" />
   <meta http-equiv="Content-Script-Type" content="text/javascript" />
    <script type="text/javascript" src="jsConfirmStyle.js"></script>
    <script type="text/javascript">

      function confirmation() {
       var answer = confirm("Wanna visit google?")
       if (answer){
       window.location = "";

    <style type="text/css">
     body {
      background-color: white;
      font-family: sans-serif;
    #jsconfirm {
      border-color: #c0c0c0;
      border-width: 2px 4px 4px 2px;
      left: 0;
     margin: 0;
     padding: 0;
     position: absolute;
    top: -1000px;
    z-index: 100;

  #jsconfirm table {
   background-color: #fff;
   border: 2px groove #c0c0c0;
   height: 150px;
   width: 300px;

   #jsconfirmtitle {
  background-color: #B0B0B0;
  font-weight: bold;
  height: 20px;
  text-align: center;

 #jsconfirmbuttons {
height: 50px;
text-align: center;

#jsconfirmbuttons input {
background-color: #E9E9CF;
color: #000000;
font-weight: bold;
width: 125px;
height: 33px;
padding-left: 20px;

background-image: url(left.png);

background-image: url(right.png);
 < /style>
<p><br />
<a href="#"
onclick="javascript:showConfirm('Please confirm','Are you really really sure to visit    google?','Yes','','No','#')">JsConfirmStyled</a></p>
<p><a href="#" onclick="confirmation()">standard</a></p>


Then create simple js file name jsConfirmStyle.js. Here is simple js code



  if(ie5||nn6) {
  if(ie5) cs=2,th=30;
  else cs=0,th=20;
    "<div id='jsconfirm'>"+
            "<tr><td id='jsconfirmtitle'></td></tr>"+
            "<tr><td id='jsconfirmcontent'></td></tr>"+
            "<tr><td id='jsconfirmbuttons'>"+
                "<input id='jsconfirmleft' type='button' value='' onclick='leftJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
                "<input id='jsconfirmright' type='button' value='' onclick='rightJsConfirm()' onfocus='if(this.blur)this.blur()'>"+

 document.write("<div id='jsconfirmfade'></div>");

 function leftJsConfirm() {
function rightJsConfirm() {
function confirmAlternative() {
if(confirm("Scipt requieres a better browser!"))       document.location.href="";

leftJsConfirmUri = '';
rightJsConfirmUri = '';

   * Show the message/confirm box
    function       showConfirm(confirmtitle,confirmcontent,confirmlefttext,confirmlefturi,confirmrighttext,con      firmrighturi)  {
xConfirm=xConfirmStart, yConfirm=yConfirmStart;
if(ie5) {
else if(nn6) {
else confirmAlternative();


You can download full Source code from here

How to determine if a decimal/double is an integer?

You can use String formatting for the double type. Here is an example:

double val = 58.6547;
String.Format("{0:0.##}", val);      
//Output: "58.65"

double val = 58.6;
String.Format("{0:0.##}", val);      
//Output: "58.6"

double val = 58.0;
String.Format("{0:0.##}", val);      
//Output: "58"

Let me know if this doesn't help.

'this' vs $scope in AngularJS controllers

I recommend you to read the following post: AngularJS: "Controller as" or "$scope"?

It describes very well the advantages of using "Controller as" to expose variables over "$scope".

I know you asked specifically about methods and not variables, but I think that it's better to stick to one technique and be consistent with it.

So for my opinion, because of the variables issue discussed in the post, it's better to just use the "Controller as" technique and also apply it to the methods.

Does overflow:hidden applied to <body> work on iPhone Safari?

I've worked with <body>and <div class="wrapper">

When popup opens ...

<body> gets a height of 100% and an overflow:hidden

<div class="wrapper"> gets position:relative;overflow:hidden;height:100%;

I use JS/jQuery to get the actual scrollposition of the page and store the value as data-attribut to body

Then i scroll to the scrollposition in the .wrapper DIV (not in window)

Here is my solution:


// when popup opens

$('body').attr( 'data-pos', $(window).scrollTop()); // get actual scrollpos
$('body').addClass('locked'); // add class to body
$('.wrapper').scrollTop( $('body').attr( 'data-pos' ) ); // let wrapper scroll to scrollpos

// when popup close

$( window ).scrollTop( $('body').attr( 'data-pos' ));


body.locked {position:relative;overflow:hidden;height:100%;}
body.locked .wrapper {position:relative;overflow:hidden;height:100%;}

It works well on both sides ... desktop & mobile (iOS).

Tipps and improvements are welcome :)


What is SOA "in plain english"?

Have a listen to this week's edition of the Floss Weekly podcast, which covers SOA. The descriptions are pretty high level and don't delve into too many technical details (although more concrete and recognizable examples of SOA projects would have been helpful.

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Array vs. Object efficiency in JavaScript

I had a similar problem that I am facing where I need to store live candlesticks from an event source limited to x items. I could have them stored in an object where the timestamp of each candle would act as the key and the candle itself would act as the value. Another possibility was that I could store it in an array where each item was the candle itself. One problem about live candles is that they keep sending updates on the same timestamp where the latest update holds the most recent data therefore you either update an existing item or add a new one. So here is a nice benchmark that attempts to combine all 3 possibilities. Arrays in the solution below are atleast 4x faster on average. Feel free to play

"use strict";

const EventEmitter = require("events");
let candleEmitter = new EventEmitter();

//Change this to set how fast the setInterval should run
const frequency = 1;

setInterval(() => {
    // Take the current timestamp and round it down to the nearest second
    let time = Math.floor( / 1000) * 1000;
    let open = Math.random();
    let high = Math.random();
    let low = Math.random();
    let close = Math.random();
    let baseVolume = Math.random();
    let quoteVolume = Math.random();

    //Clear the console everytime before printing fresh values

    candleEmitter.emit("candle", {
        symbol: "ABC:DEF",
        time: time,
        open: open,
        high: high,
        low: low,
        close: close,
        baseVolume: baseVolume,
        quoteVolume: quoteVolume

}, frequency)

// Test 1 would involve storing the candle in an object
candleEmitter.on('candle', storeAsObject)

// Test 2 would involve storing the candle in an array
candleEmitter.on('candle', storeAsArray)

//Container for the object version of candles
let objectOhlc = {}

//Container for the array version of candles
let arrayOhlc = {}

//Store a max 30 candles and delete older ones
let limit = 30

function storeAsObject(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;

    // Create the object structure to store the current symbol
    if (typeof objectOhlc[symbol] === 'undefined') objectOhlc[symbol] = {}

    // The timestamp of the latest candle is used as key with the pair to store this symbol
    objectOhlc[symbol][time] = candle;

    // Remove entries if we exceed the limit
    const keys = Object.keys(objectOhlc[symbol]);
    if (keys.length > limit) {
        for (let i = 0; i < (keys.length - limit); i++) {
            delete objectOhlc[symbol][keys[i]];

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]

    console.log("Storing as objects", end - start, Object.keys(objectOhlc[symbol]).length)

function storeAsArray(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;
    if (typeof arrayOhlc[symbol] === 'undefined') arrayOhlc[symbol] = []

    //Get the bunch of candles currently stored
    const candles = arrayOhlc[symbol];

    //Get the last candle if available
    const lastCandle = candles[candles.length - 1] || {};

    // Add a new entry for the newly arrived candle if it has a different timestamp from the latest one we storeds
    if (time !== lastCandle.time) {

    //If our newly arrived candle has the same timestamp as the last stored candle, update the last stored candle
    else {
        candles[candles.length - 1] = candle

    if (candles.length > limit) {
        candles.splice(0, candles.length - limit);

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]

    console.log("Storing as array", end - start, arrayOhlc[symbol].length)

Conclusion 10 is the limit here

Storing as objects 4183 nanoseconds 10
Storing as array 373 nanoseconds 10

Create multiple threads and wait all of them to complete

In .NET 4.0, you can use the Task Parallel Library.

In earlier versions, you can create a list of Thread objects in a loop, calling Start on each one, and then make another loop and call Join on each one.

How to remove and clear all localStorage data

If you want to remove/clean all the values from local storage than use


And if you want to remove the specific item from local storage than use the following code


Get list of databases from SQL Server

You can find all database names with this:-

 select name from sys.sysdatabases

How to label each equation in align environment?

Usually my align environments are set up like

  \lambda_i + \mu_i = 0 \\
  \mu_i \xi_i = 0 \\
  \lambda_i [y_i( w^T x_i + b) - 1 + \xi_i] = 0

The \label command should be placed in the line you want to reference, the placement in the line does not matter. I prefer to place it at the beginning at the line (as a sort of description) while others place them at the end.

What is the default value for Guid?

You can use these methods to get an empty guid. The result will be a guid with all it's digits being 0's - "00000000-0000-0000-0000-000000000000".

new Guid()



How to install Visual Studio 2015 on a different drive

Run installer in command line (Admin) with argument:

vs_community_ENU.exe /uninstall /force


vs_community_ENU /CustomInstallPath E:\VisualStudio2015

Create timestamp variable in bash script

Use command substitution:

timestamp=$( date +%T )

How to reverse apply a stash?

How to reverse apply a stash?

Apart from what others have mentioned, easiest way is first do

git reset HEAD

and then checkout all local changes

git checkout . 

Squash the first two commits in Git?

I've reworked VonC's script to do everything automatically and not ask me for anything. You give it two commit SHA1s and it will squash everything between them into one commit named "squashed history":

# Go back to the last commit that we want
# to form the initial commit (detach HEAD)
git checkout $2

# reset the branch pointer to the initial commit (= $1),
# but leaving the index and working tree intact.
git reset --soft $1

# amend the initial tree using the tree from $2
git commit --amend -m "squashed history"

# remember the new commit sha1
TARGET=`git rev-list HEAD --max-count=1`

# go back to the original branch (assume master for this example)
git checkout master

# Replay all the commits after $2 onto the new initial commit
git rebase --onto $TARGET $2

How do you upload a file to a document library in sharepoint?

You can upload documents to SharePoint libraries using the Object Model or SharePoint Webservices.

Upload using Object Model:

String fileToUpload = @"C:\YourFile.txt";
String sharePointSite = "";
String documentLibraryName = "Shared Documents";

using (SPSite oSite = new SPSite(sharePointSite))
    using (SPWeb oWeb = oSite.OpenWeb())
        if (!System.IO.File.Exists(fileToUpload))
            throw new FileNotFoundException("File not found.", fileToUpload);                    

        SPFolder myLibrary = oWeb.Folders[documentLibraryName];

        // Prepare to upload
        Boolean replaceExistingFiles = true;
        String fileName = System.IO.Path.GetFileName(fileToUpload);
        FileStream fileStream = File.OpenRead(fileToUpload);

        // Upload document
        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);

        // Commit 

Anchor links in Angularjs?

There are a few ways to do this it seems.

Option 1: Native Angular

Angular provides an $anchorScroll service, but the documentation is severely lacking and I've not been able to get it to work.

Check out for some insight into $anchorScroll.

Option 2: Custom Directive / Native JavaScript

Another way I tested out was creating a custom directive and using el.scrollIntoView(). This works pretty decently by basically doing the following in your directive link function:

var el = document.getElementById(attrs.href);

However, it seems a bit overblown to do both of these when the browser natively supports this, right?

Option 3: Angular Override / Native Browser

If you take a look at$location and its HTML Link Rewriting section, you'll see that links are not rewritten in the following:

Links that contain target element

Example: <a href="/ext/link?a=b" target="_self">link</a>

So, all you have to do is add the target attribute to your links, like so:

<a href="#anchorLinkID" target="_self">Go to inpage section</a>

Angular defaults to the browser and since its an anchor link and not a different base url, the browser scrolls to the correct location, as desired.

I went with option 3 because its best to rely on native browser functionality here, and saves us time and effort.

Gotta note that after a successful scroll and hash change, Angular does follow up and rewrite the hash to its custom style. However, the browser has already completed its business and you are good to go.

How to upload a file to directory in S3 bucket using boto

For upload folder example as following code and S3 folder picture enter image description here

import boto
import boto.s3
import boto.s3.connection
import os.path
import sys    

# Fill in info on data to upload
# destination bucket name
bucket_name = 'willie20181121'
# source directory
sourceDir = '/home/willie/Desktop/x/'  #Linux Path
# destination directory name (on s3)
destDir = '/test1/'   #S3 Path

#max size in bytes before uploading in parts. between 1 and 5 GB recommended
MAX_SIZE = 20 * 1000 * 1000
#size of parts when uploading in parts
PART_SIZE = 6 * 1000 * 1000

access_key = 'MPBVAQ*******IT****'
secret_key = '11t63yDV***********HgUcgMOSN*****'

conn = boto.connect_s3(
        aws_access_key_id = access_key,
        aws_secret_access_key = secret_key,
        host = '******',
        is_secure=False,               # uncomment if you are not using ssl
        calling_format = boto.s3.connection.OrdinaryCallingFormat(),
bucket = conn.create_bucket(bucket_name,

uploadFileNames = []
for (sourceDir, dirname, filename) in os.walk(sourceDir):

def percent_cb(complete, total):

for filename in uploadFileNames:
    sourcepath = os.path.join(sourceDir + filename)
    destpath = os.path.join(destDir, filename)
    print ('Uploading %s to Amazon S3 bucket %s' % \
           (sourcepath, bucket_name))

    filesize = os.path.getsize(sourcepath)
    if filesize > MAX_SIZE:
        print ("multipart upload")
        mp = bucket.initiate_multipart_upload(destpath)
        fp = open(sourcepath,'rb')
        fp_num = 0
        while (fp.tell() < filesize):
            fp_num += 1
            print ("uploading part %i" %fp_num)
            mp.upload_part_from_file(fp, fp_num, cb=percent_cb, num_cb=10, size=PART_SIZE)


        print ("singlepart upload")
        k = boto.s3.key.Key(bucket)
        k.key = destpath
                cb=percent_cb, num_cb=10)

PS: For more reference URL

What's the "Content-Length" field in HTTP header?

One octet is 8 bits. Content-length is the number of octets that the message body represents.

keycode 13 is for which key

function myFunction(event) {
  var x = event.charCode;
  document.getElementById("demo").innerHTML = "The Unicode value is: " + x;
<p>Keycode 13 is: </p> 
<p>Press a key on the keyboard in the input field to get the Unicode character code of the pressed key.</p>
<b>You can test in below</b>

<input type="text" size="40" onkeypress="myFunction(event)">

<p id="demo"></p>

<p><strong>Note:</strong> The charCode property is not supported in IE8 and earlier versions.</p>

FIFO based Queue implementations?

Queue is an interface that extends Collection in Java. It has all the functions needed to support FIFO architecture.

For concrete implementation you may use LinkedList. LinkedList implements Deque which in turn implements Queue. All of these are a part of java.util package.

For details about method with sample example you can refer FIFO based Queue implementation in Java.

PS: Above link goes to my personal blog that has additional details on this.

What is the difference between angular-route and angular-ui-router?

1- ngRoute is developed by angular team whereas ui-router is a 3rd party module. 2- ngRoute implements routing based on the route URL whereas ui-router implements routing based on the state of the application. 3- ui-router provides everything that the ng-route provides plus some additional features like nested states and multiple named views.

How to add parameters to an external data query in Excel which can't be displayed graphically?

Easy Workaround (no VBA required)

  1. Right Click Table, expand "Table" context manu, select "External Data Properties"
  2. Click button "Connection Properties" (labelled in tooltip only)
  3. Go-to Tab "Definition"

From here, edit the SQL directly by adding '?' wherever you want a parameter. Works the same way as before except you don't get nagged.

How to Parse JSON Array with Gson

           id : '1',
           title: 'sample title',
           id : '2',
           title: 'sample title',

Check Easy code for this output

 Gson gson=new GsonBuilder().create();
                List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));

css 100% width div not taking up full width of parent

html, body{ 

This tells the html to be 100% wide. But 100% refers to the whole browser window width, so no more than that.

You may want to set a min width instead.

html, body{ 

So it will be 100% as a minimum, bot more if needed.

How to select data of a table from another database in SQL Server?

In SQL Server 2012 and above, you don't need to create a link. You can execute directly


I don't know whether previous versions of SQL Server work as well

Converting XML to JSON using Python?

You can use the xmljson library to convert using different XML JSON conventions.

For example, this XML:

<p id="1">text</p>

translates via the BadgerFish convention into this:

  'p': {
    '@id': 1,
    '$': 'text'

and via the GData convention into this (attributes are not supported):

  'p': {
    '$t': 'text'

... and via the Parker convention into this (attributes are not supported):

  'p': 'text'

It's possible to convert from XML to JSON and from JSON to XML using the same conventions:

>>> import json, xmljson
>>> from lxml.etree import fromstring, tostring
>>> xml = fromstring('<p id="1">text</p>')
>>> json.dumps(
'{"p": {"@id": 1, "$": "text"}}'
>>> xmljson.parker.etree({'ul': {'li': [1, 2]}})
# Creates [<ul><li>1</li><li>2</li></ul>]

Disclosure: I wrote this library. Hope it helps future searchers.

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

You just need to manually set the desired permissions with chmod():

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);

    // Set perms with chmod()
    chmod($file, 0777);
    return true;

JSON date to Java date?

That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.

Here's one

If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat to parse these kinds of strings.

How to create a jar with external libraries included in Eclipse?

If you want to export all JAR-files of a Java web-project, open the latest generated WAR-file with a ZIP-tool (e.g. 7-Zip), navigate to the /WEB-INF/lib/ folder. Here you will find all JAR-files you need for this project (as listed in "Referenced Libraries").

javascript check for not null

It's because val is not null, but contains 'null' as a string.

Try to check with 'null'

if ('null' != val)

For an explanation of when and why this works, see the details below.

Values of disabled inputs will not be submitted

You can use three things to mimic disabled:

  1. HTML: readonly attribute (so that the value present in input can be used on form submission. Also the user can't change the input value)

  2. CSS: 'pointer-events':'none' (blocking the user from clicking the input)

  3. HTML: tabindex="-1" (blocking the user to navigate to the input from the keyboard)

How to access a dictionary key value present inside a list?

You haven't provided enough context to provide an accurate answer (i.e. how do you want to handle identical keys in multiple dicts?)

One answer is to iterate the list, and attempt to get 'd'

mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
myvalues = [i['d'] for i in mylist if 'd' in i]

Another answer is to access the dict directly (by list index), though you have to know that the key is present


Windows Scheduled task succeeds but returns result 0x1

I found that the problem was to do with Powershell not being able to run scripts, if that's the case for you, here is the solution.

Create HTML table using Javascript

In the html file there are three input boxes with userid,username,department respectively.

These inputboxes are used to get the input from the user.

The user can add any number of inputs to the page.

When clicking the button the script will enable the debugger mode.

In javascript, to enable the debugger mode, we have to add the following tag in the javascript.


    Tools->Internet Options-->Advanced-->uncheck
    Disable script debugging(Internet Explorer)
    Disable script debugging(Other)

    <html xmlns="" >

    <head runat="server">

    <title>Dynamic Table</title>

    <script language="javascript" type="text/javascript">

    // <!CDATA[

    function CmdAdd_onclick() {

    var newTable,startTag,endTag;

    //Creating a new table

    startTag="<TABLE id='mainTable'><TBODY><TR><TD style=\"WIDTH: 120px\">User ID</TD>
    <TD style=\"WIDTH: 120px\">User Name</TD><TD style=\"WIDTH: 120px\">Department</TD></TR>"



    var trContents;

    //Get the row contents








    // Add previous rows







    //Add the Latest row

    newTable+="<TR><TD style=\"WIDTH: 120px\" >" +
        document.getElementById('userid').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('username').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('department').value +"</TD><TR>";


    //Update the Previous Table With New Table.



    // ]]>




    <form id="form1" runat="server">


    <br />


    <input id="userid" type="text" /><br />


    <input id="username" type="text" /><br />


    <input id="department" type="text" />


    <input id="CmdAdd" type="button" value="Add" onclick="return CmdAdd_onclick()" />


    <div id="tableDiv" style="text-align:center" >

    <table id="mainTable">

    <tr style="width:120px " >

    <td >User ID</td>

    <td>User Name</td>








How to change btn color in Bootstrap

Here's my flavor without the loss of hover. I personally like it better than the standard bootstrap transitioning.

.btn-primary:visited {_x000D_
  background-color: #8064A2 !important;_x000D_
.btn-primary:hover {_x000D_
  background-color: #594671 !important;_x000D_
  transition: all 1s ease;_x000D_
  -webkit-transition: all 1s ease;_x000D_
  -moz-transition: all 1s ease;_x000D_
  -o-transition: all 1s ease;_x000D_
  -ms-transition: all 1s ease;_x000D_
<link href="" rel="stylesheet" />_x000D_
<button class="btn btn-primary">Hover me!</button>

Remove empty strings from array while keeping record Without Loop?

arr = arr.filter(v => v);

as returned v is implicity converted to truthy

How do you add UI inside cells in a google spreadsheet using app script?

The apps UI only works for panels.

The best you can do is to draw a button yourself and put that into your spreadsheet. Than you can add a macro to it.

Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Than click it and click "assign Macro...", then insert the name of the function you wish to execute there. The function must be defined in a script in the spreadsheet.

Alternatively you can also draw the button somewhere else and insert it as an image.

More info:

enter image description here enter image description here enter image description here

Deploy a project using Git push

I use two solutions for post-receive hook:


#  /git-repo/hooks/post-receive - file content on server (chmod as 755 to be executed)

    export GIT_DIR=/git/repo-bare.git
    export GIT_BRANCH1=master
    export GIT_TARGET1=/var/www/html
    export GIT_BRANCH2=dev
    export GIT_TARGET2=/var/www/dev
    echo "GIT DIR:  $GIT_DIR/"
    echo "GIT TARGET1:  $GIT_TARGET1/"
    echo "GIT BRANCH1:  $GIT_BRANCH1/"
    echo "GIT TARGET2:  $GIT_TARGET2/"
    echo "GIT BRANCH2:  $GIT_BRANCH2/"
    echo ""

    cd $GIT_DIR/

while read oldrev newrev refname
    branch=$(git rev-parse --abbrev-ref $refname)
    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET1/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        git checkout -f $branch

    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET2/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        git checkout -f $branch


#  /git-repo/hooks/post-receive - file content on server (chmod as 755 to be executed)

    export GIT_DIR=/git/repo-bare.git
    export GIT_BRANCH1=master
    export GIT_TARGET1=/var/www/html
    export GIT_BRANCH2=dev
    export GIT_TARGET2=/var/www/dev
    export GIT_TEMP_DIR1=/tmp/deploy1
    export GIT_TEMP_DIR2=/tmp/deploy2
    echo "GIT DIR:  $GIT_DIR/"
    echo "GIT TARGET1:  $GIT_TARGET1/"
    echo "GIT BRANCH1:  $GIT_BRANCH1/"
    echo "GIT TARGET2:  $GIT_TARGET2/"
    echo "GIT BRANCH2:  $GIT_BRANCH2/"
    echo "GIT TEMP DIR1:  $GIT_TEMP_DIR1/"
    echo "GIT TEMP DIR2:  $GIT_TEMP_DIR2/"
    echo ""

    cd $GIT_DIR/

while read oldrev newrev refname
    branch=$(git rev-parse --abbrev-ref $refname)
    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET1/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        # DEPLOY SOLUTION 2: 
        cd $GIT_DIR/; mkdir -p $GIT_TEMP_DIR1; 
        export GIT_WORK_TREE=$GIT_TEMP_DIR1/.
        git checkout -f $branch
        export GIT_WORK_TREE=$GIT_TARGET1/.
        rsync $GIT_TEMP_DIR1/. -v -q --delete --delete-after -av $GIT_TARGET1/.
        rm -rf $GIT_TEMP_DIR1

    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET2/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        # DEPLOY SOLUTION 2: 
        cd $GIT_DIR/; mkdir -p $GIT_TEMP_DIR2; 
        export GIT_WORK_TREE=$GIT_TEMP_DIR2/.
        git checkout -f $branch
        export GIT_WORK_TREE=$GIT_TARGET2/.
        rsync $GIT_TEMP_DIR2/. -v -q --delete --delete-after -av $GIT_TARGET2/.
        rm -rf $GIT_TEMP_DIR2

Both solutions are based on earlier solutions available in this thread.

Note, the BRANCH_REGEX='^${GIT_BRANCH1}.$' filters for the branch names matching "master" or "dev*" string, and deploys the work tree, if the pushed branch matches. This makes possible to deploy a dev version and master version to different places.

DEPLOY SOLUTION 1 removes only files, which are part of the repo, and was removed by a commit. It is faster than Deployment Solution 2.

DEPLOY SOLUTION 2 has the advantage, that it will remove any new files from the production directory, which was added on server side, no matter if it was added to the repo or not. It will be always clean dupe of the repo. It is slower than Deployment Solution 1.

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

mysql update column with value from another table

    UPDATE    cities c,
          city_langs cl
    SET       c.fakename =
   WHERE = cl.city_id

Remove Trailing Spaces and Update in Columns in SQL Server

To just trim trailing spaces you should use

    ColumnName = RTRIM(ColumnName)

However, if you want to trim all leading and trailing spaces then use this

    ColumnName = LTRIM(RTRIM(ColumnName))

Animate background image change with jQuery

It can be done by jquery and css. i did it in a way that can be used in dynamic situations , you just have to change background-image in jquery and it will do every thing , also you can change the time in css.

The fiddle :


<div class="test">


.test {
  /* as default, we set a background-image , but it is not nessesary */
  background-image: url(;
  width: 200px;
  height: 200px;
  /* we set transition to 'all' properies - but you can use it just for background image either - by default the time is set to 1 second, you can change it yourself*/
  transition: linear all 1s;
  /* if you don't use delay , background will disapear and transition will start from a white background - you have to set the transition-delay the same as transition time OR more , so there won't be any problems */
  -webkit-transition-delay: 1s;/* Safari */
  transition-delay: 1s;


$('.test').click(function() {
  //you can use all properties : background-color  - background-image ...
    'background-image': 'url('

How to recover a dropped stash in Git?

If you didn't close the terminal, just look at the output from git stash pop and you'll have the object ID of the dropped stash. It normally looks like this:

$ git stash pop
Dropped refs/stash@{0} (2ca03e22256be97f9e40f08e6d6773c7d41dbfd1)

(Note that git stash drop also produces the same line.)

To get that stash back, just run git branch tmp 2cae03e, and you'll get it as a branch. To convert this to a stash, run:

git stash apply tmp
git stash

Having it as a branch also allows you to manipulate it freely; for example, to cherry-pick it or merge it.

What is the lifetime of a static variable in a C++ function?

FWIW, Codegear C++Builder doesn't destruct in the expected order according to the standard.

C:\> sample.exe 1 2
Created in foo
Created in if
Destroyed in foo
Destroyed in if

... which is another reason not to rely on the destruction order!

How to check if X server is running?

$DISPLAY is the standard way. That's how users communicate with programs about which X server to use, if any.

Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

If you have content with height unknown but you know the height the of container. The following solution works extremely well.


<div class="center-test">
    <span></span><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. 
    Nesciunt obcaecati maiores nulla praesentium amet explicabo ex iste asperiores 
    nisi porro sequi eaque rerum necessitatibus molestias architecto eum velit 
    recusandae ratione.</p>


.center-test { 
   width: 300px; 
   height: 300px; 
   background-color: #333; 
.center-test span { 
   height: 300px; 
   display: inline-block; 
   zoom: 1; 
   *display: inline; 
   vertical-align: middle; 
.center-test p { 
   display: inline-block; 
   zoom: 1; 
   *display: inline; 
   vertical-align: middle; 
   color: #fff; 


One gotcha for newby's to display: inline-block; [span] and [p] have no html white space so that the span then doesn't take up any space. Also I've added in the CSS hack for display inline-block for IE. Hope this helps someone!

Difference between style = "position:absolute" and style = "position:relative"

With CSS positioning, you can place an element exactly where you want it on your page.

When you are going to use CSS positioning, the first thing you need to do is use the CSS property position to tell the browser if you're going to use absolute or relative positioning.

Both Positions are having different features. In CSS Once you set Position then you can able to use top, right, bottom, left attributes.

Absolute Position

An absolute position element is positioned relative to the first parent element that has a position other than static.

Relative Position

A relative positioned element is positioned relative to its normal position.

To position an element relatively, the property position is set as relative. The difference between absolute and relative positioning is how the position is being calculated.

More :Postion Relative vs Absolute

Parse XLSX with Node and create json

You can also use

var XLSX = require('xlsx');
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;

How to Navigate from one View Controller to another using Swift

SWIFT 3.01

let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)

How to remove blank lines from a Unix file

To be thorough and remove lines even if they include spaces or tabs something like this in perl will do it:

cat file.txt | perl -lane "print if /\S/"

Of course there are the awk and sed equivalents. Best not to assume the lines are totally blank as ^$ would do.


Extract a page from a pdf as a jpeg

One problem,everyone will face that is to Install Poppler.My way is a tricky way,but will work efficiently.1st download Poppler here.Then Extract it add In the code section just add poppler_path=r'C:\Program Files\poppler-0.68.0\bin'(for eg.) like below

from pdf2image import convert_from_path
images = convert_from_path("mypdf.pdf", 500,poppler_path=r'C:\Program Files\poppler-0.68.0\bin')
for i, image in enumerate(images):
    fname = 'image'+str(i)+'.png', "PNG")

How to remove certain characters from a string in C++?

Yes, you can use the isdigit() function to check for a digits :)

Here you go:

#include <iostream>
#include <cctype>
#include <string.h>

using namespace std;

int main(){

  char *str = "(555) 555-5555";
  int len = strlen(str);

  for (int i=0; i<len; i++){
      if (isdigit(*(str+i))){
        cout << *(str+i);

  cout << endl;

return 0;   

Hope it helps :)

How do you switch pages in Xamarin.Forms?

By using the PushAsync() method you can push and PopModalAsync() you can pop pages to and from the navigation stack. In my code example below I have a Navigation page (Root Page) and from this page I push a content page that is a login page once I am complete with my login page I pop back to the root page

~~~ Navigation can be thought of as a last-in, first-out stack of Page objects.To move from one page to another an application will push a new page onto this stack. To return back to the previous page the application will pop the current page from the stack. This navigation in Xamarin.Forms is handled by the INavigation interface

Xamarin.Forms has a NavigationPage class that implements this interface and will manage the stack of Pages. The NavigationPage class will also add a navigation bar to the top of the screen that displays a title and will also have a platform appropriate Back button that will return to the previous page. The following code shows how to wrap a NavigationPage around the first page in an application:

Reference to content listed above and a link you should review for more information on Xamarin Forms, see the Navigation section:


public class MainActivity : AndroidActivity
    protected override void OnCreate(Bundle bundle)

        Xamarin.Forms.Forms.Init(this, bundle);
        // Set our view from the "main" layout resource

    static Page BuildView()
        var mainNav = new NavigationPage(new RootPage());
        return mainNav;

public class RootPage : ContentPage
    async void ShowLoginDialog()
        var page = new LoginPage();

        await Navigation.PushModalAsync(page);

//Removed code for simplicity only the pop is displayed

private async void AuthenticationResult(bool isValid)
    await navigation.PopModalAsync();

Displaying a vector of strings in C++

vector.size() returns the size of a vector. You didn't put any string in the vector before the loop , so the size of the vector is 0. It will never enter the loop. First put some data in the vector and then try to add them. You can take input from the user for the number of string user wants to enter.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;

int main(int a, char* b [])
    vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
        cin >> word;
        sentence += userString[i] + " ";
    cout << sentence;
    return 0;

another thing, actually you don't have to use a vector to do this.Two strings can do the job for you.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;

int main(int a, char* b [])
   // vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
        cin >> word;
        sentence += word+ " ";
    cout << sentence;
    return 0;

and if you want to enter string until the user wish , code will be like this:

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;

int main(int a, char* b [])
   // vector<string> userString;
    string word;
    string sentence = "";
    //int SIZE;
    //cin>>SIZE;    //what will be the size of the vector
        //cin >> word;
        sentence += word+ " ";
    cout << sentence;
  //  system("PAUSE");
    return 0;

Set Label Text with JQuery

The checkbox is in a td, so need to get the parent first:

$("input:checkbox").on("change", function() {

Alternatively, find a label which has a for with the same id (perhaps more performant than reverse traversal) :

$("input:checkbox").on("change", function() {
    $("label[for='" + $(this).attr('id') + "']").text("TESTTTT");

Or, to be more succinct just

$("input:checkbox").on("change", function() {
    $("label[for='" + + "']").text("TESTTTT");

php: catch exception and continue execution, is it possible?

An old question, but one I had in the past when coming away from VBA scipts to php, where you could us "GoTo" to re-enter a loop "On Error" with a "Resume" and away it went still processing the function.
In php, after a bit of trial and error, I now use nested try{} catch{} for critical versus non critical processes, or even for interdependent class calls so I can trace my way back to the start of the error. e.g. if function b is dependant on function a, but function c is a nice to have but should not stop the process, and I still want to know the outcomes of all 3 regardless, here's what I do:

//set up array to capture output of all 3 functions
$resultArr = array(array(), array(), array());

// Loop through the primary array and run the functions 
foreach($x as $key => $val)
        $resultArr[$key][0][] = a($key); 
        $resultArr[$key][1][] = b($val);
        { // If successful, output of c() is captured
            $resultArr[$key][2][] = c($key, $val);
        catch(Exception $ex)
        { // If an error, capture why c() failed
            $resultArr[$key][2][] = $ex->getMessage();
    catch(Exception $ex)
    { // If critical functions a() or b() fail, we catch the reason why
        $criticalError = $ex->getMessage();

Now I can loop through my result array for each key and assess the outcomes. If there is a critical failure for a() or b().
I still have a point of reference on how far it got before a critical failure occurred within the $resultArr and if the exception handler is set correctly, I know if it was a() or b() that failed.
If c() fails, loop keeps going. If c() failed at various points, with a bit of extra post loop logic I can even find out if c() worked or had an error on each iteration by interrogating $resultArr[$key][2].

How can I read the client's machine/computer name from the browser?

An updated version from Kelsey :

$(function GetInfo() {
    var network = new ActiveXObject('WScript.Network');
        alert('User ID : ' + network.UserName + '\nComputer Name : ' + network.ComputerName + '\nDomain Name : ' + network.UserDomain);
        document.getElementById('<%= currUserID.ClientID %>').value = network.UserName;
        document.getElementById('<%= currMachineName.ClientID %>').value = network.ComputerName;
        document.getElementById('<%= currMachineDOmain.ClientID %>').value = network.UserDomain;

To store the value, add these control :

<asp:HiddenField ID="currUserID" runat="server" /> <asp:HiddenField ID="currMachineName" runat="server" /> <asp:HiddenField ID="currMachineDOmain" runat="server" />

Where you also can calling it from behind like this :

Page.ClientScript.RegisterStartupScript(this.GetType(), "MachineInfo", "GetInfo();", true);

Function to get yesterday's date in Javascript in format DD/MM/YYYY

The problem here seems to be that you're reassigning $today by assigning a string to it:

$today = $dd+'/'+$mm+'/'+$yyyy;

Strings don't have getDate.

Also, $today.getDate()-1 just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:

$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.

Then just apply the formatting code you wrote:

var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!

var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;

Because of the last statement, $yesterday is now a String (not a Date) containing the formatted date.

MySQL root password change

On MySQL 8.0.4+

To update current root user:

select current_user();
set password = 'new_password';

To update other user:

set password for 'otherUser'@'localhost' = 'new_password';

To set password policy before updating password:

set global validate_password.policy = 0;
set password = 'new_password';
set password for 'otherUser'@'localhost' = 'new_password';

Other / better way to update root password:


Want to stick with 5.x authentication so you can still use legacy apps?

On my.cnf

default_authentication_plugin = mysql_native_password

To update root:

set global validate_password.policy = 0;
alter user 'root'@'localhost' identified with mysql_native_password by 'new_password';

Remove carriage return from string

I just had the same issue in my code today and tried which worked like a charm.


SQLite: How do I save the result of a query as a CSV file?

To include column names to your csv file you can do the following:

sqlite> .headers on
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

To verify the changes that you have made you can run this command:

sqlite> .show


echo: off   
explain: off   
headers: on   
mode: csv   
nullvalue: ""  
output: stdout  
separator: "|"   
stats: off   
width: 22 18 

How to generate the "create table" sql statement for an existing table in postgreSQL

This is the variation that works for me:

pg_dump -U user_viktor -h localhost unit_test_database -t floorplanpreferences_table --schema-only

In addition, if you're using schemas, you'll of course need to specify that as well:

pg_dump -U user_viktor -h localhost unit_test_database -t "949766e0-e81e-11e3-b325-1cc1de32fcb6".floorplanpreferences_table --schema-only

You will get an output that you can use to create the table again, just run that output in psql.

In C#, how to check whether a string contains an integer?

This work for me.

("your string goes here").All(char.IsDigit)

How do I split a string in Rust?

There are three simple ways:

  1. By separator:

     s.split("separator")  |  s.split('/')  |  s.split(char::is_numeric)
  2. By whitespace:

  3. By newlines:

  4. By regex: (using regex crate)

     Regex::new(r"\s").unwrap().split("one two three")

The result of each kind is an iterator:

let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();



stale element reference: element is not attached to the page document

Use this code:

public class LinkTest 
    public static void main(String[] args) 
        WebDriver driver = new FirefoxDriver();
        List<WebElement> alllinks =driver.findElements(By.xpath("//*[@id='sliding-navigation']//a"));
        String a[]=new String[alllinks.size()];
        for(int i=0;i<alllinks.size();i++)
                System.out.println("clicking on this link::"+driver.findElement(By.linkText(a[i])).getText());

                System.out.println("does not starts with B so not clicking");

How to make a window always stay on top in .Net?

Why not making your form a dialogue box:


Binding Button click to a method

Here is the VB.Net rendition of Rachel's answer above.

Obviously the XAML binding is the same...

<Button Command="{Binding Path=SaveCommand}" />

Your Custom Class would look like this...

''' <summary>
''' Retrieves an new or existing RelayCommand.
''' </summary>
''' <returns>[RelayCommand]</returns>
Public ReadOnly Property SaveCommand() As ICommand
        If _saveCommand Is Nothing Then
            _saveCommand = New RelayCommand(Function(param) SaveObject(), Function(param) CanSave())
        End If
        Return _saveCommand
    End Get
End Property
Private _saveCommand As ICommand

''' <summary>
''' Returns Boolean flag indicating if command can be executed.
''' </summary>
''' <returns>[Boolean]</returns>
Private Function CanSave() As Boolean
    ' Verify command can be executed here.
    Return True
End Function

''' <summary>
''' Code to be run when the command is executed.
''' </summary>
''' <remarks>Converted to a Function in to avoid the "Expression does not produce a value" error.</remarks>
''' <returns>[Nothing]</returns>
Private Function SaveObject()
    ' Save command execution logic.
   Return Nothing
End Function

And finally the RelayCommand class is as follows...

Public Class RelayCommand : Implements ICommand

ReadOnly _execute As Action(Of Object)
ReadOnly _canExecute As Predicate(Of Object)
Private Event ICommand_CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged

''' <summary>
''' Creates a new command that can always execute.
''' </summary>
''' <param name="execute">The execution logic.</param>
Public Sub New(execute As Action(Of Object))
    Me.New(execute, Nothing)
End Sub

''' <summary>
''' Creates a new command.
''' </summary>
''' <param name="execute">The execution logic.</param>
''' <param name="canExecute">The execution status logic.</param>
Public Sub New(execute As Action(Of Object), canExecute As Predicate(Of Object))
    If execute Is Nothing Then
        Throw New ArgumentNullException("execute")
    End If
    _execute = execute
    _canExecute = canExecute
End Sub

Public Function CanExecute(parameters As Object) As Boolean Implements ICommand.CanExecute
    Return If(_canExecute Is Nothing, True, _canExecute(parameters))
End Function

Public Custom Event CanExecuteChanged As EventHandler
    AddHandler(ByVal value As EventHandler)
        AddHandler CommandManager.RequerySuggested, value
    End AddHandler
    RemoveHandler(ByVal value As EventHandler)
        RemoveHandler CommandManager.RequerySuggested, value
    End RemoveHandler
    RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
        If (_canExecute IsNot Nothing) Then
        End If
    End RaiseEvent
End Event

Public Sub Execute(parameters As Object) Implements ICommand.Execute
End Sub

End Class

Hope that helps any VB.Net developers!

How to auto-format code in Eclipse?

CTRL + SHIFT + F will auto format your code(whether it is highlighted or non highlighted).

Telegram Bot - how to get a group chat id?

After mid-2018:
1:) Invite @getidsbot or @RawDataBot to your group and get your group id from the chat id field.

 + message_id: 338
 + from
 ?  + id: *****
 ?  + is_bot: false
 ?  + first_name: ???
 ?  + username: ******
 ?  + language_code: en
 + chat
 ?  + id: -1001118554477    // This is Your Group id
 ?  + title: Test Group
 ?  + type: supergroup
 + date: 1544948900
 + text: A

2:) use an unofficial Messenger like Plus Messenger and see your group id in group/channel info.

Before mid-2018: (don't Use)
1: Goto (
2: Goto your Gorup and Find your link of Gorup(
3: Copy That number after g and put a (-) Before That -154513121
4: Send Your Message to Gorup bot.sendMessage(-154513121, "Hi")
I Tested Now and Work like a Charm

How to upload file to server with HTTP POST multipart/form-data?

The below code reads a file, converts it to a byte array and then makes a request to the server.

    public void PostImage()
        HttpClient httpClient = new HttpClient();
        MultipartFormDataContent form = new MultipartFormDataContent();

        byte[] imagebytearraystring = ImageFileToByteArray(@"C:\Users\Downloads\icon.png");
        form.Add(new ByteArrayContent(imagebytearraystring, 0, imagebytearraystring.Count()), "profile_pic", "hello1.jpg");
        HttpResponseMessage response = httpClient.PostAsync("your url", form).Result;

        string sd = response.Content.ReadAsStringAsync().Result;

    private byte[] ImageFileToByteArray(string fullFilePath)
        FileStream fs = File.OpenRead(fullFilePath);
        byte[] bytes = new byte[fs.Length];
        fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
        return bytes;

convert strtotime to date time format in php

Use date() function to get the desired date

// set default timezone

//define date and time
$strtotime = 1307595105;

// output
echo date('d M Y H:i:s',$strtotime);

// more formats
echo date('c',$strtotime); // ISO 8601 format
echo date('r',$strtotime); // RFC 2822 format

Recommended online tool for strtotime to date conversion:

Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?

To sum up all of the options for VS 2017, WebHelpers was installed by installing MVC in previous versions of Visual Studio. If you're getting this error, you probably don't have the older versions of VS installed anymore.

So, installing the Microsoft.AspNet.MVC NuGet package will require Microsoft.AspNet.WebPages and Microsoft.AspNet.Razor, and the Microsoft.AspNet.WebPages includes System.Web.Helpers.dll.

If you've got direct references to System.Web.Mvc.dll and you don't want to use NuGet for MVC, you can get the Microsoft.AspNet.WebPages NuGet, or there are some other NuGet packages that only contain System.Web.Helpers.dll, like the microsoft-web-helpers or System-Web-Helpers.dllpackages.

There appear to be 2 versions of System.Web.Helpers.dll, one for .Net 4.0 and one for 4.5. Choosing the correct version of MVC or AspNet.WebPages will ensure you get the right one.

href="tel:" and mobile numbers

When dialing a number within the country you are in, you still need to dial the national trunk number before the rest of the number. For example, in Australia one would dial:

   0 - trunk prefix
   2 - Area code for New South Wales
6555 - STD code for a specific telephone exchange
1234 - Telephone Exchange specific extension.

For a mobile phone this becomes

   0 -      trunk prefix
   4 -      Area code for a mobile telephone
1234 5678 - Mobile telephone number

Now, when I want to dial via the international trunk, you need to drop the trunk prefix and replace it with the international dialing prefix

   + -      Short hand for the country trunk number
  61 -      Country code for Australia
   4 -      Area code for a mobile telephone
1234 5678 - Mobile telephone number

This is why you often find that the first digit of a telephone number is dropped when dialling internationally, even when using international prefixing to dial within the same country.

So as per the trunk prefix for Germany drop the 0 and add the +49 for Germany's international calling code (for example) giving:

<a href="tel:+496170961709" class="Blondie">_x000D_
    Call me, call me any, anytime_x000D_
      <b>Call me (call me) I'll arrive</b>_x000D_
        When you're ready we can share the wine!_x000D_

How do I compile and run a program in Java on my Mac?

You need to make sure that a mac compatible version of java exists on your computer. Do java -version from terminal to check that. If not, download the apple jdk from the apple website. (Sun doesn't make one for apple themselves, IIRC.)

From there, follow the same command line instructions from compiling your program that you would use for java on any other platform.

Why do we need middleware for async flow in Redux?

OK, let's start to see how middleware working first, that quite answer the question, this is the source code applyMiddleWare function in Redux:

function applyMiddleware() {
  for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
    middlewares[_key] = arguments[_key];

  return function (createStore) {
    return function (reducer, preloadedState, enhancer) {
      var store = createStore(reducer, preloadedState, enhancer);
      var _dispatch = store.dispatch;
      var chain = [];

      var middlewareAPI = {
        getState: store.getState,
        dispatch: function dispatch(action) {
          return _dispatch(action);
      chain = (middleware) {
        return middleware(middlewareAPI);
      _dispatch = compose.apply(undefined, chain)(store.dispatch);

      return _extends({}, store, {
        dispatch: _dispatch

Look at this part, see how our dispatch become a function.

  getState: store.getState,
  dispatch: function dispatch(action) {
  return _dispatch(action);
  • Note that each middleware will be given the dispatch and getState functions as named arguments.

OK, this is how Redux-thunk as one of the most used middlewares for Redux introduce itself:

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.

So as you see, it will return a function instead an action, means you can wait and call it anytime you want as it's a function...

So what the heck is thunk? That's how it's introduced in Wikipedia:

In computer programming, a thunk is a subroutine used to inject an additional calculation into another subroutine. Thunks are primarily used to delay a calculation until it is needed, or to insert operations at the beginning or end of the other subroutine. They have a variety of other applications to compiler code generation and in modular programming.

The term originated as a jocular derivative of "think".

A thunk is a function that wraps an expression to delay its evaluation.

//calculation of 1 + 2 is immediate 
//x === 3 
let x = 1 + 2;

//calculation of 1 + 2 is delayed 
//foo can be called later to perform the calculation 
//foo is a thunk! 
let foo = () => 1 + 2;

So see how easy the concept is and how it can help you manage your async actions...

That's something you can live without it, but remember in programming there are always better, neater and proper ways to do things...

Apply middleware Redux

No module named 'openpyxl' - Python 3.4 - Ubuntu

You have to install it explixitly using the python package manager as

  1. pip install openpyxl for Python 2
  2. pip3 install openpyxl for Python 3

Is it possible in Java to access private fields via reflection

Yes it is possible.

You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:

Field privateField = Test.class.getDeclaredField("str");

Additionally, you need to set this Field to be accessible, if you want to access a private field:


Once that's done, you can use the get method on the Field instance, to access the value of the str field.

Copy file or directories recursively in Python

The python shutil.copytree method its a mess. I've done one that works correctly:

def copydirectorykut(src, dst):
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            if not os.path.exists(dst+'/'+line[:-1]):

How do you add a timer to a C# console application

Lets Have A little Fun

using System;
using System.Timers;

namespace TimerExample
    class Program
        static Timer timer = new Timer(1000);
        static int i = 10;

        static void Main(string[] args)
            timer.Start(); Console.Read();

        private static void timer_Elapsed(object sender, ElapsedEventArgs e)

            Console.WriteLine("                  DEFUSE THE BOMB");
            Console.WriteLine("                Time Remaining:  " + i.ToString());

            if (i == 0) 
                Console.WriteLine("         B O O O O O M M M M M ! ! ! !");
                Console.WriteLine("               G A M E  O V E R");



Simple DatePicker-like Calendar

I'm particularly fond of this date picker built for Mootools:

It's lovely right out of the box.

In Swift how to call method with parameters on GCD main thread?

Don't forget to weakify self if you are using self inside of the closure.

dispatch_async(dispatch_get_main_queue(),{ [weak self] () -> () in
    if let strongSelf = self {

How to use GROUP BY to concatenate strings in MySQL?

The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024 characters, so we first do:

SET group_concat_max_len=100000000;

and then, for example:

SELECT pub_id,GROUP_CONCAT(cate_id SEPARATOR ' ') FROM book_mast GROUP BY pub_id

Cannot load properties file from resources directory

If it is simple application then getSystemResourceAsStream can also be used.

try (InputStream inputStream = ClassLoader.getSystemResourceAsStream(""))..

How to compare two vectors for equality element by element in C++?

According to the discussion here you can directly compare two vectors using


if (vector1 == vector2){

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I had the same issue. I resolved it doing the following:

  1. Add the this line to the dispatcher-servlet file:


    Check above <beans> section in the same file. These two lines must be present:

    xsi:schemaLocation= ""
  2. Also make sure you added @Repository and @Transactional where you are using sessionFactory.

    public class ItemDaoImpl implements ItemDao {
        private SessionFactory sessionFactory;

C#: Dynamic runtime cast

The opensource framework Dynamitey has a static method that does late binding using DLR including cast conversion among others.

dynamic Cast(object obj, Type castTo){
    return Dynamic.InvokeConvert(obj, castTo, explict:true);

The advantage of this over a Cast<T> called using reflection, is that this will also work for any IDynamicMetaObjectProvider that has dynamic conversion operators, ie. TryConvert on DynamicObject.

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;


  return Number ;


Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

HTML form action and onsubmit issues



There was no endpoint listening at (url) that could accept the message

This is ancient history but I just ran into this issue and the fix for me was recycling the application pool of the website in IIS. Easy fix, for once.

How to perform runtime type checking in Dart?

Simply call


on the data.

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

Just for completion, here is a code example indicating the differences:

success \ error:

.success(function(data, status, header, config) {
    // success handler
.error(function(data, status, header, config) {
    // error handler


.then(function(response) {
    // success handler
}, function(response) {
    // error handler
.then(function(response) {
    // success handler
}, function(response) {
    // error handler
.then(function(response) {
    // success handler
}, function(response) {
    // error handler

How to debug PDO database queries?

Here is a function I made to return a SQL query with "resolved" parameters.

function paramToString($query, $parameters) {
    if(!empty($parameters)) {
        foreach($parameters as $key => $value) {
            preg_match('/(\?(?!=))/i', $query, $match, PREG_OFFSET_CAPTURE);
            $query = substr_replace($query, $value, $match[0][1], 1);
    return $query;
    $query = "SELECT email FROM table WHERE id = ? AND username = ?";
    $values = [1, 'Super'];

    echo paramToString($query, $values);

Assuming you execute like this

$values = array(1, 'SomeUsername');

This function DOES NOT add quotes to queries but does the job for me.

How to detect internet speed in JavaScript?

I needed a quick way to determine if the user connection speed was fast enough to enable/disable some features in a site I’m working on, I made this little script that averages the time it takes to download a single (small) image a number of times, it's working pretty accurately in my tests, being able to clearly distinguish between 3G or Wi-Fi for example, maybe someone can make a more elegant version or even a jQuery plugin.

var arrTimes = [];_x000D_
var i = 0; // start_x000D_
var timesToTest = 5;_x000D_
var tThreshold = 150; //ms_x000D_
var testImage = ""; // small image in your server_x000D_
var dummyImage = new Image();_x000D_
var isConnectedFast = false;_x000D_
  isConnectedFast = (avg <= tThreshold);_x000D_
  /** output */_x000D_
    document.createTextNode("Time: " + (avg.toFixed(2)) + "ms - isConnectedFast? " + isConnectedFast)_x000D_
/** test and average time took to download image from server, called recursively timesToTest times */_x000D_
function testLatency(cb) {_x000D_
  var tStart = new Date().getTime();_x000D_
  if (i<timesToTest-1) {_x000D_
    dummyImage.src = testImage + '?t=' + tStart;_x000D_
    dummyImage.onload = function() {_x000D_
      var tEnd = new Date().getTime();_x000D_
      var tTimeTook = tEnd-tStart;_x000D_
      arrTimes[i] = tTimeTook;_x000D_
  } else {_x000D_
    /** calculate average of array items then callback */_x000D_
    var sum = arrTimes.reduce(function(a, b) { return a + b; });_x000D_
    var avg = sum / arrTimes.length;_x000D_

Escape double quote character in XML

If you just need to try something out quickly, here's a quick and dirty solution. Use single quotes for the attribute value:

<parameter name='Quote = " '>

DBCC CHECKIDENT Sets Identity to 0

As you pointed out in your question it is a documented behavior. I still find it strange though. I use to repopulate the test database and even though I do not rely on the values of identity fields it was a bit of annoying to have different values when populating the database for the first time from scratch and after removing all data and populating again.

A possible solution is to use truncate to clean the table instead of delete. But then you need to drop all the constraints and recreate them afterwards

In that way it always behaves as a newly created table and there is no need to call DBCC CHECKIDENT. The first identity value will be the one specified in the table definition and it will be the same no matter if you insert the data for the first time or for the N-th

git ahead/behind info between master and branch?

Here's a trick I found to compare two branches and show how many commits each branch is ahead of the other (a more general answer on your question 1):

For local branches: git rev-list --left-right --count master...test-branch

For remote branches: git rev-list --left-right --count origin/master...origin/test-branch

This gives output like the following:

1 7

This output means: "Compared to master, test-branch is 7 commits ahead and 1 commit behind."

You can also compare local branches with remote branches, e.g. origin/master...master to find out how many commits the local master branch is ahead/behind its remote counterpart.

How can JavaScript save to a local file?

If you are using FireFox you can use the File HandleAPI

I had just tested it out and it works!

Hashing a string with Sha256

This work for me in .NET Core 3.1.
But not in .NET 5 preview 7.

using System;
using System.Security.Cryptography;
using System.Text;

namespace PortalAplicaciones.Shared.Models
    public class Encriptar
        public static string EncriptaPassWord(string Password)
                SHA256Managed hasher = new SHA256Managed();

                byte[] pwdBytes = new UTF8Encoding().GetBytes(Password);
                byte[] keyBytes = hasher.ComputeHash(pwdBytes);

                return Convert.ToBase64String(keyBytes);
            catch (Exception ex)
                throw new Exception(ex.Message, ex);
} Certificates does not conform to algorithm constraints

We have this problem with one database we don't control and it requried another solution (The ones listed here didn't work). For mine I needed:


I think in my case it had to do with forcing a certain order.

How to hide close button in WPF window?

To disable close button you should add the following code to your Window class (the code was taken from here, edited and reformatted a bit):

protected override void OnSourceInitialized(EventArgs e)

    HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;

    if (hwndSource != null)


private bool allowClosing = false;

private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
private static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);

private const uint MF_BYCOMMAND = 0x00000000;
private const uint MF_GRAYED = 0x00000001;

private const uint SC_CLOSE = 0xF060;

private const int WM_SHOWWINDOW = 0x00000018;
private const int WM_CLOSE = 0x10;

private IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    switch (msg)
        case WM_SHOWWINDOW:
                IntPtr hMenu = GetSystemMenu(hwnd, false);
                if (hMenu != IntPtr.Zero)
                    EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
        case WM_CLOSE:
            if (!allowClosing)
                handled = true;
    return IntPtr.Zero;

This code also disables close item in System menu and disallows closing the dialog using Alt+F4.

You will probably want to close the window programmatically. Just calling Close() will not work. Do something like this:

allowClosing = true;

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

The icon will adopt the color from value of the color css property of it's parent.

You can either add this directly to the style:

<span class="glyphicon glyphicon-user" style="color:blue"></span>

Or you can add it as a class to your icon and then set the font color to it in CSS


<span class="glyphicon glyphicon-search"></span>
<span class="glyphicon glyphicon-user blue"></span>
<span class="glyphicon glyphicon-trash"></span>


.blue {
    color: blue;

This fiddle has an example.

How do I see what character set a MySQL database / table / column is?

For database : USE db_name; SELECT @@character_set_database;

SQL sum with condition

Try moving ValueDate:

select sum(CASE  
             WHEN ValueDate > @startMonthDate THEN cash 
              ELSE 0 
 from Table a
where a.branch = p.branch 
  and a.transID = p.transID

(reformatted for clarity)

You might also consider using '0' instead of NULL, as you are doing a sum. It works correctly both ways, but is maybe more indicitive of what your intentions are.

npm can't find package.json

just install any package you want with -g

npm install -g express

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

Your second example does not work if you send the argument by reference. Did you mean

void copyVecFast(vec<int> original) // no reference

  vector<int> new_;

That would work, but an easier way is

vector<int> new_(original);