Programs & Examples On #Tabbed interface


Best practice when adding whitespace in JSX

If the goal is to seperate two elements, you can use CSS like below:

A<span style={{paddingLeft: '20px'}}>B</span>

How can I view an old version of a file with Git?

If you like GUIs, you can use gitk:

  1. start gitk with:

    gitk /path/to/file
  2. Choose the revision in the top part of the screen, e.g. by description or date. By default, the lower part of the screen shows the diff for that revision, (corresponding to the "patch" radio button).

  3. To see the file for the selected revision:

    • Click on the "tree" radio button. This will show the root of the file tree at that revision.
    • Drill down to your file.

how do I join two lists using linq or lambda expressions

The way to do this using the Extention Methods, instead of the linq query syntax would be like this:

var results = workOrders.Join(plans,
  wo => wo.WorkOrderNumber,
  p => p.WorkOrderNumber,
  (order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}

How to get a table creation script in MySQL Workbench?

Right-click on the relevant table and choose either of:

  • Copy to Clipboard > Create Statement
  • Send to SQL Editor > Create Statement

That seems to work for me.

How to check if all inputs are not empty with jQuery

You can achive this with Regex and Replace or with just trimming.

Regex example:

if ($('input').val().replace(/[\s]/, '') == '') {
    alert('Input is not filled!');

With this replace() function you replace white spaces with nothing (removing white spaces).

Trimming Example:

if ($('input').val().trim() == '') {
    alert('Input is not filled!');

trim() function removes the leading and trailing white space and line terminator characters from a string.

foreach with index

I keep this extension method around for this:

public static void Each<T>(this IEnumerable<T> ie, Action<T, int> action)
    var i = 0;
    foreach (var e in ie) action(e, i++);

And use it like so:

var strings = new List<string>();
strings.Each((str, n) =>
    // hooray

Or to allow for break-like behaviour:

public static bool Each<T>(this IEnumerable<T> ie, Func<T, int, bool> action)
    int i = 0;
    foreach (T e in ie) if (!action(e, i++)) return false;
    return true;

var strings = new List<string>() { "a", "b", "c" };

bool iteratedAll = strings.Each ((str, n)) =>
    if (str == "b") return false;
    return true;

Docker compose, running containers in net:host

Those documents are outdated. I'm guessing the 1.6 in the URL is for Docker 1.6, not Compose 1.6. Check out the correct syntax here: You are looking for network_mode when using the v2 YAML format.

Abstract Class:-Real Time Example

You should be able to cite at least one from the JDK itself. Look in the java.util.collections package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map and why Joshua Bloch wrote it that way.


TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).

As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.

BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.

What is an NP-complete in computer science?

It's a class of problems where we must simulate every possibility to be sure we have the optimal solution.

There are a lot of good heuristics for some NP-Complete problems, but they are only an educated guess at best.

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

Check if any service is listening on port 5037, and kill it. You can use lsof for this:

$ lsof -i :5037
$ kill <PID Process>

Then try

$ adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *

This solved my problem.

CSS Selector for <input type="?"

You can do this with jQuery. Using their selectors, you can select by attributes, such as type. This does, however, require that your users have Javascript turned on, and an additional file to download, but if it works...

Kotlin - How to correctly concatenate a String

Try this, I think this is a natively way to concatenate strings in Kotlin:

val result = buildString{


// you will see "ab" in console.

Create a Cumulative Sum Column in MySQL

Using a correlated query:

         (SELECT SUM(x.count)
            FROM TABLE x
           WHERE <= AS cumulative_sum

Using MySQL variables:

         @running_total := @running_total + t.count AS cumulative_sum
    JOIN (SELECT @running_total := 0) r


  • The JOIN (SELECT @running_total := 0) r is a cross join, and allows for variable declaration without requiring a separate SET command.
  • The table alias, r, is required by MySQL for any subquery/derived table/inline view


  • MySQL specific; not portable to other databases
  • The ORDER BY is important; it ensures the order matches the OP and can have larger implications for more complicated variable usage (IE: psuedo ROW_NUMBER/RANK functionality, which MySQL lacks)

PHP Warning: Unknown: failed to open stream

In Fedora 25, it turned out to be an SE Linux issue, and the notification gave this solution which worked for me.

setsebool -P httpd_read_user_content 1

C#: what is the easiest way to subtract time?

Hi if you are going to subtract only Integer value from DateTime then you have to write code like this


Here I am subtracting 2 hours from the current date and time

Center-align a HTML table

For your design, it is common practice to use divs rather than a table. This way, your layout will be more maintainable and changeable through proper styling. It does take some getting used to, but it will help you a ton in the long run and you will learn a lot about how styling works. However, I will provide you with a solution to the problem at hand.

In your stylesheets you have margins and padding set to 0 pixels. This overrides your align="center" attribute. I would recommend taking these settings out of your CSS as you don't normally want all of your elements to be affected in this manner. If you already know what's going on in the CSS, and you want to keep it that way, then you have to apply a style to your table to override the previous sets. You could either give the table a class or you can put the style inline with the HTML. Here are the two options:

  1. With a class:

    <table class="centerTable"></table>

In your style.css file you would have something like this:

.centerTable { margin: 0px auto; }
  1. Inline with your HTML:

    <table style="margin: 0px auto;"></table>

If you decide to wipe out the margins and padding being set to 0px, then you can keep align="center" on your <td> tags for whatever column you wish to align.

How to calculate the sum of the datatable column in

 this.LabelControl.Text = datatable.AsEnumerable()
    .Sum(x => x.Field<int>("Amount"))

If you want to filter the results:

 this.LabelControl.Text = datatable.AsEnumerable()
    .Where(y => y.Field<string>("SomeCol") != "foo")
    .Sum(x => x.Field<int>("MyColumn") )

Basic example of using .ajax() with JSONP?

JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement("script");
script.type = "text/javascript";
script.src = "";

You will end up with a script segment that looks like this after it loads the data:

{['some string 1', 'some data', 'whatever data']}

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):

script = document.createElement("script");
script.type = "text/javascript";
script.src = "";

Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']});

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data. That's all there is to know about JSONP: it's a callback and script tags.

These are simple examples of JSONP usage, these are not production ready scripts.

RAW JavaScript demonstration (simple Twitter feed using JSONP):

        <div id = 'twitterFeed'></div>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            document.getElementById('twitterFeed').innerHTML = text;
        <script type="text/javascript" src=""></script>

Basic jQuery example (simple Twitter feed using JSONP):

        <script type="text/javascript" src=""></script>
                    url: '',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
        <div id = 'twitterFeed'></div>

JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)

How to specify credentials when connecting to boto3 S3?

You can create a session:

import boto3
session = boto3.Session(

Then use that session to get an S3 resource:

s3 = session.resource('s3')

the MySQL service on local computer started and then stopped

In my case, I tried to open a DOS prompt and go to the MySQL bin\ directory and issue the below command:

mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server 5.0\my.ini" --standalone --console

And it shows me I was missing the "C:\Program Files\MySQL\MySQL Server 5.0\Uploads" folder; I built one and problem solved.

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Faced the same issue and resolved by upgrading my Maven from 3.0.4 to 3.1.1. Please try with v3.1.1 or any higher version if available

How do I split a string into an array of characters?

You can use the regular expression /(?!$)/:


The negative look-ahead assertion (?!$) will match right in front of every character.


You need to use a group by clause.

SELECT  site_id, MAX(ts) as TIME, count(*) group by site_id

How do I setup the dotenv file in Node.js?

There's a lot of confusion about this topic and in these answers. I'm not surprised, that no single answer was accepted. Hopefully yet.

The answer by Basheer indeed solves most of the problems. However, there are few things you still need to know. Especially, if you're coming, like me, from frontend background and wants to add secrets to your frontend. Possibly, related to the introduction of some Server-Side Rendering (SSR) logic in the app.

Most probably you've seen this code in your webpack settings in a frontend app to solve the issue, as a frontend developer.

/* Custom webpack properties. */
const dotenv = require('dotenv-webpack');

module.exports = {
  plugins: [
    new dotenv(), // Handle environemntal variables on localhost, but on the Server-Side Rendering (SSR). There's no access to "process.env" on the browser.

Now, it'll work out fine, if you render on the server (SSR) across your app if the .env file is in the root of your project. However, it might not work if you have some custom server-related settings. An example of such situation is Angular Universal, Nuxt.js handles this much easier in which require('dotenv').config() in your next.config.js and makes you good to go. That's due to difference in philosophies between how Angular and Vue.js are handling SSR. To get Angular Universal app from Angular that's just 1 command, but the SSR app isn't as nicely organized as Nuxt.js. It comes with a price that to generate Nuxt.js app from Vue.js, you basically have to generate a new Nuxt.js project and copy files due to quite some differences between Nuxt.js and Vue.js setup. Don't know how React/Next.js and Svelte/Sapper solves this, but if similarly to Angular then you also might consider reading further.

Now, you've some server-related logic in a separated folder called server and let say the file is called main.ts. Maybe apart SSR in that file, you can also have sending mail (nodemailer?) logic. Then you'd like to use process.env, but apparently it doesn't work, even though you have the logic defined in webpack. That's where the require('dotenv').config(); is needed, even if you're using different syntax for import (such as import { Express } from 'express'; for example), require('dotenv').config(); will work like that. Don't feel confused. As long as .env is in the root of your app (don't confuse with server folder) and the variables have correct syntax inside that file, e.g.

[email protected]

It'll work.

Last scenario, in the SSR app you realised that to host this app you need something called Serverless/Cloud Functions/FaaS. Here, I know only Firebase scenario. In your project, to deploy such app you might have functions folder, from which you deploy the SSR app to the Cloud Functions for Firebase, in this example. What a surprise, on a deployment mail is not working and after hours of figuring out what's happening in the logs you can see process.env.VARIABLE_NAME returning undefined. The reason is that as of today the CLI cannot merge files from other locations and indeed the .env file has to be manually copied to the functions folder. Once copy/paste the .env file to functions and deploy, it'll work.

What you can use for debugging is one of those:

console.log(require('dotenv').config({debug: true})); 

However, be careful with your secrets, because these will be revealed when your .env setup will be done. Trying to access one of the secrets and trying to log its value in the logs might be more secure option. Especially, if you have many secrets and don't want to rewrite all.

Hope so this one post will cover most of the scenarios.

Can gcc output C code after preprocessing?


gcc -E <file>.c


g++ -E <file>.cpp

What is the difference between SQL and MySQL?

SQL - Structured Query Language. It is declarative computer language aimed at querying relational databases.

MySQL is a relational database - a piece of software optimized for data storage and retrieval. There are many such databases - Oracle, Microsoft SQL Server, SQLite and many others are examples of such.

Jersey Exception : SEVERE: A message body reader for Java class

Some may be confused why add jersey-json jar can't solve this problem. I found out that this jar has to newer than jersey-json-1.7.jar( 1.7.0 doesn't work, but 1.7.1 works fine.). hope this can help

How can I sanitize user input with PHP?

Do not try to prevent SQL injection by sanitizing input data.

Instead, do not allow data to be used in creating your SQL code. Use Prepared Statements (i.e. using parameters in a template query) that uses bound variables. It is the only way to be guaranteed against SQL injection.

Please see my website for more about preventing SQL injection.

How to put space character into a string name in XML?

As already mentioned the correct way to have a space in an XML file is by using \u0020 which is the unicode character for a space.


<string name="spelatonertext3">-4,\u00205,\u0020-5,\u00206,\u0020-6</string>

Other suggestions have said to use &#160; or &#032; but there is two downsides to this. The first downside is that these are ASCII characters so you are relying on something like a TextView to parse them. The second downside is that &#160; can sometimes cause strange wrapping in TextViews.

How to get a dependency tree for an artifact?

1) Use maven dependency plugin

Create a simple project with pom.xml only. Add your dependency and run:

mvn dependency:tree

Unfortunately dependency mojo must use pom.xml or you get following error:

Cannot execute mojo: tree. It requires a project with an existing pom.xml, but the build is not using one.

2) Find pom.xml of your artifact in maven central repository

Dependencies are described In pom.xml of your artifact. Find it using maven infrastructure.

Go to and enter your groupId and artifactId.

Or you can go to and navigate first using plugins groupId, later using artifactId and finally using its version.

For example see org.springframework:spring-core

3) Use maven dependency plugin against your artifact

Part of dependency artifact is a pom.xml. That specifies it's dependency. And you can execute mvn dependency:tree on this pom.

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

Whenever you start Visual Studio run it as administrator. It works for me.

SQL Server SELECT into existing table

There are two different ways to implement inserting data from one table to another table.

For Existing Table - INSERT INTO SELECT

This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.

----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database

For Non-Existing Table - SELECT INTO

This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.

----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database

Ref 1 2

How to set Angular 4 background image?

You can use ngStyle to set background for a div

<div [ngStyle]="{background-image: 'url(./images/' + trls.img + ')'}"></div>

or you can also use built in background style:

<div [style.background-image]="'url(/images/' + trls.img + ')'"></div>

Is it possible to deserialize XML into List<T>?

Not sure about List<T> but Arrays are certainly do-able. And a little bit of magic makes it really easy to get to a List again.

public class UserHolder {
   public User[] Users { get; set; }

   public List<User> UserList { get { return new List<User>(Users); } }

Bi-directional Map in Java?

You can use the Google Collections API for that, recently renamed to Guava, specifically a BiMap

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

Auto Increment after delete in MySQL

You may think about making a trigger after delete so you can update the value of autoincrement and the ID value of all rows that does not look like what you wanted to see.

So you can work with the same table and the auto increment will be fixed automaticaly whenever you delete a row the trigger will fix it.

base64 encode in MySQL

Functions from contain some error when in encoded string are 32-byte (space), ex BASE64_ENCODE(CONCAT(CHAR(15), CHAR(32))). Here is corrected function



DROP TABLE IF EXISTS core_base64_data$$
CREATE TABLE core_base64_data (c CHAR(1) BINARY, val TINYINT)$$
INSERT INTO core_base64_data VALUES 
('A',0), ('B',1), ('C',2), ('D',3), ('E',4), ('F',5), ('G',6), ('H',7), ('I',8), ('J',9),
('K',10), ('L',11), ('M',12), ('N',13), ('O',14), ('P',15), ('Q',16), ('R',17), ('S',18), ('T',19),
('U',20), ('V',21), ('W',22), ('X',23), ('Y',24), ('Z',25), ('a',26), ('b',27), ('c',28), ('d',29),
('e',30), ('f',31), ('g',32), ('h',33), ('i',34), ('j',35), ('k',36), ('l',37), ('m',38), ('n',39),
('o',40), ('p',41), ('q',42), ('r',43), ('s',44), ('t',45), ('u',46), ('v',47), ('w',48), ('x',49),
('y',50), ('z',51), ('0',52), ('1',53), ('2',54), ('3',55), ('4',56), ('5',57), ('6',58), ('7',59),
('8',60), ('9',61), ('+',62), ('/',63), ('=',0) $$


    IF input IS NULL THEN
        RETURN NULL;
    END IF;
        DECLARE in_count TINYINT DEFAULT 0;
        DECLARE out_count TINYINT;
        WHILE in_count < 3 DO BEGIN
            DECLARE first_char BLOB(1);

            IF LENGTH(input) = 0 THEN
                SET done = 1;
                SET accum_value = accum_value << (8 * (3 - in_count));
                LEAVE each_input_char;
            END IF;

            SET first_char = SUBSTRING(input,1,1);
            SET input = SUBSTRING(input,2);

            SET accum_value = (accum_value << 8) + ASCII(first_char);
            SET in_count = in_count + 1;
        END; END WHILE;

        -- We've now accumulated 24 bits; deaccumulate into base64 characters
        -- We have to work from the left, so use the third byte position and shift left
            WHEN in_count = 3 THEN SET out_count = 4;
            WHEN in_count = 2 THEN SET out_count = 3;
            WHEN in_count = 1 THEN SET out_count = 2;
            ELSE RETURN ret;
        END CASE;

        WHILE out_count > 0 DO BEGIN
                DECLARE out_char CHAR(1);
                DECLARE base64_getval CURSOR FOR SELECT c FROM core_base64_data WHERE val = (accum_value >> 18);
                OPEN base64_getval;
                FETCH base64_getval INTO out_char;
                CLOSE base64_getval;
                SET ret = CONCAT(ret,out_char);
                SET out_count = out_count - 1;
                SET accum_value = accum_value << 6 & 0xffffff;
        END; END WHILE;
            WHEN in_count = 2 THEN SET ret = CONCAT(ret,'=');
            WHEN in_count = 1 THEN SET ret = CONCAT(ret,'==');
            ELSE BEGIN END;
        END CASE;

    RETURN ret;


IIS7 URL Redirection from root to sub directory

I could not get this working with the accepted answer, mainly because I did not know where to enter that code. I looked everywhere for some explanation of the URL Rewrite tool that made sense, but could not find any. I ended up using the HTTP Redirect tool in IIS.

  1. Choose your site
  2. Click HTTP Redirect in the IIS section (Make sure the Role Service is installed)
  3. Check "Redirect requests to this destination"
  4. Enter where you want to redirect. In your case ""
  5. In Redirect Behavior, I found I had to check "Only redirect requests to content in this directory (not subdirectories), or it would go into a loop. See what works for you.

Hope this helps.

How to remove html special chars?

Use html_entity_decode to convert HTML entities.

You'll need to set charset to make it work correctly.

How to handle a single quote in Oracle SQL

Use two single-quotes



Alternatively, use the new (10g+) quoting method:



Can a foreign key refer to a primary key in the same table?

I think the question is a bit confusing.

If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied. For example, in an employee table, a row for an employee may have a column for storing manager's employee number where the manager is also an employee and hence will have a row in the table like a row of any other employee.

If you mean "can column(or set of columns) be a primary key as well as a foreign key in the same table?", the answer, in my view, is a no; it seems meaningless. However, the following definition succeeds in SQL Server!

create table t1(c1 int not null primary key foreign key references t1(c1))

But I think it is meaningless to have such a constraint unless somebody comes up with a practical example.

AmanS, in your example d_id in no circumstance can be a primary key in Employee table. A table can have only one primary key. I hope this clears your doubt. d_id is/can be a primary key only in department table.

Hyphen, underscore, or camelCase as word delimiter in URIs?

The standard best practice for REST APIs is to have a hyphen, not camelcase or underscores.

This comes from Mark Masse's "REST API Design Rulebook" from Oreilly.

In addition, note that Stack Overflow itself uses hyphens in the URL: .../hyphen-underscore-or-camelcase-as-word-delimiter-in-uris

As does WordPress:

How to find all trigger associated with a table with SQL Server?

use sp_helptrigger to find the triggerlist for the associated tables

How do I find the data directory for a SQL Server instance?

You can find default Data and Log locations for the current SQL Server instance by using the following T-SQL:

DECLARE @defaultDataLocation nvarchar(4000)
DECLARE @defaultLogLocation nvarchar(4000)

EXEC master.dbo.xp_instance_regread
    @defaultDataLocation OUTPUT

EXEC master.dbo.xp_instance_regread
    @defaultLogLocation OUTPUT

SELECT @defaultDataLocation AS 'Default Data Location',
       @defaultLogLocation AS 'Default Log Location'

Java; String replace (using regular expressions)?

What is your polynomial? If you're "processing" it, I'm envisioning some sort of tree of sub-expressions being generated at some point, and would think that it would be much simpler to use that to generate your string than to re-parse the raw expression with a regex.

Just throwing a different way of thinking out there. I'm not sure what else is going on in your app.

Android : Capturing HTTP Requests with non-rooted android device

There is many ways to do that but one of them is fiddler

Fiddler Configuration

  1. Go to options
  2. In HTTPS tab, enable Capture HTTPS Connects and Decrypt HTTPS traffic
  3. In Connections tab, enable Allow remote computers to connect
  4. Restart fiddler

Android Configuration

  1. Connect to same network
  2. Modify network settings
  3. Add proxy for connection with your PC's IP address ( or hostname ) and default fiddler's port ( 8888 / you can change that in settings )

Now you can see full log from your device in fiddler

Also you can find a full instruction here

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'


ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

How do I merge my local uncommitted changes into another Git branch?

The answers given so far are not ideal because they require a lot of needless work resolving merge conflicts, or they make too many assumptions which are frequently false. This is how to do it perfectly. The link is to my own site.

How to Commit to a Different Branch in git

You have uncommited changes on my_branch that you want to commit to master, without committing all the changes from my_branch.


git merge master
git stash -u
git checkout master
git stash apply
git reset
git add example.js
git commit
git checkout .
git clean -f -d
git checkout my_branch
git merge master
git stash pop


Start by merging master into your branch, since you'll have to do that eventually anyway, and now is the best time to resolve any conflicts.

The -u option (aka --include-untracked) in git stash -u prevents you from losing untracked files when you later do git clean -f -d within master.

After git checkout master it is important that you do NOT git stash pop, because you will need this stash later. If you pop the stash created in my_branch and then do git stash in master, you will cause needless merge conflicts when you later apply that stash in my_branch.

git reset unstages everything resulting from git stash apply. For example, files that have been modified in the stash but do not exist in master get staged as "deleted by us" conflicts.

git checkout . and git clean -f -d discard everything that isn't committed: all changes to tracked files, and all untracked files and directories. They are already saved in the stash and if left in master would cause needless merge conflicts when switching back to my_branch.

The last git stash pop will be based on the original my_branch, and so will not cause any merge conflicts. However, if your stash contains untracked files which you have committed to master, git will complain that it "Could not restore untracked files from stash". To resolve this conflict, delete those files from your working tree, then git stash pop, git add ., and git reset.

How to set a default value for an existing column

Like Yuck's answer with a check to allow the script to be ran more than once without error. (less code/custom strings than using information_schema.columns)

IF object_id('DF_SomeName', 'D') IS NULL BEGIN
    Print 'Creating Constraint DF_SomeName'

Javascript reduce on array of objects

I used to encounter this is my development, what I do is wrap my solution in a function to make it reusable in my environment, like this:

const sumArrayOfObject =(array, prop)=>array.reduce((sum, n)=>{return sum + n[prop]}, 0)

Get the time of a datetime using T-SQL?

You can try the following code to get time as HH:MM format:

 SELECT CONVERT(VARCHAR(5),getdate(),108)

Load a WPF BitmapImage from a System.Drawing.Bitmap

// at class level;
public static extern bool DeleteObject(IntPtr hObject);    //

/// <summary> 
/// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>. 
/// </summary> 
/// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject. 
/// </remarks> 
/// <param name="source">The source bitmap.</param> 
/// <returns>A BitmapSource</returns> 
public static System.Windows.Media.Imaging.BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
    var hBitmap = source.GetHbitmap();
    var result = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());


    return result;

Nodemailer with Gmail and NodeJS

exports.mailSend = (res, fileName, object1, object2, to, subject,   callback)=> {
var smtpTransport = nodemailer.createTransport('SMTP',{ //smtpTransport
host: 'hostname,
port: 1234,
secureConnection: false,
//   tls: {
//     ciphers:'SSLv3'
// },
auth: {
  user: 'username',
  pass: 'password'

res.render(fileName, {
info1: object1,
info2: object2
}, function (err, HTML) {

  from: "[email protected]",
  to: to,
  subject: subject,
  html: HTML
  , function (err, responseStatus) {
    console.log("checking dta", responseStatus.message);
    callback(err, responseStatus)

You must add secureConnection type in you code.

Cannot bulk load. Operating system error code 5 (Access is denied.)

Try giving the folder(s) containing the CSV and Format File read permissions for ‘MSSQLSERVER’ user (or whatever user the SQL Server service is set to Log On As in Windows Services)

not finding android sdk (Unity)

I have same problem.

I fixed by android sdk tool version downgrade.

The steps.

  1. Delete android sdk "tools" folder : [Your Android SDK root]/tools -> tools

  2. Download SDK Tools:

  3. Extract that to Android SDK root

  4. Build your project

eval command in Bash and its typical uses

The eval statement tells the shell to take eval’s arguments as command and run them through the command-line. It is useful in a situation like below:

In your script if you are defining a command into a variable and later on you want to use that command then you should use eval:

/home/user1 > a="ls | more"
/home/user1 > $a
bash: command not found: ls | more
/home/user1 > # Above command didn't work as ls tried to list file with name pipe (|) and more. But these files are not there
/home/user1 > eval $a
/home/user1 >

How can I get the behavior of GNU's readlink -f on a Mac?

  1. Install homebrew
  2. Run "brew install coreutils"
  3. Run "greadlink -f path"

greadlink is the gnu readlink that implements -f. You can use macports or others as well, I prefer homebrew.

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

Configure Log4net to write to multiple files

Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:

    <level value="ALL" />
    <appender-ref ref="File1Appender" />
<logger name="SomeName">
    <level value="ALL" />
    <appender-ref ref="File1Appender2" />

This is how I have done it in the past. Then something like this for the other log:

private static readonly ILog otherLog = LogManager.GetLogger("SomeName");

And you can get your normal logger as follows:

private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Read the loggers and appenders section of the documentation to understand how this works.

What is the difference between public, private, and protected?

Considering 'when':
I tend to declare everything as private initially, if I'm not exactly sure. Reason being, that it's usually much easier to turn a private method public than the other way round. That's because you can at least be sure that the private method hasn't been used anywhere but in the class itself. A public method may already be in use everywhere, possibly requiring an extensive re-write.

Update: i go for a default of protected nowadays, because I've come to find that it's good enough for encapsulation and doesn't get in the way when I'm extending classes (which i try to avoid anyway). Only if i have a good reason to use the other two, i will.

A good reason for a private method would be one that implements something inherent to that object that even an extending class should not change (factual reason, in addition to encapsulation, like internal state management). Eventually, it's still easy enough to track down where a protected method is being used usually, so i default to protected nowadays. Maybe not 100% objective "in the trenches" experience, I admit.

Post to another page within a PHP script

Solution is in target="_blank" like this:

edit form like this:

<form method="post" action="../booking/step1.php" onsubmit="doubleSubmit(this)">

And use this script:

    <script type="text/javascript">
function doubleSubmit(f)
  // submit to action in form
  // set second action and submit"_blank";
  return false;

updating nodejs on ubuntu 16.04

Try this:

Edit or create the file :nodesource.list

sudo gedit /etc/apt/sources.list.d/nodesource.list

Insert this text:

deb bionic main

deb-src bionic main

Run these commands:

curl -s | apt-key add -

sudo sh -c "echo deb cosmic main /etc/apt/sources.list.d/nodesource.list"

sudo apt-get update

sudo apt-get install nodejs

What's a good IDE for Python on Mac OS X?

Eclipse with Pydev works best for me on any platform.

Click through div to underlying elements

I couldn't always use pointer-events: none in my scenario, because I wanted both the overlay and the underlying element(s) to be clickable / selectable.

The DOM structure looked like this:

<div id="outerElement">
   <div id="canvas-wrapper">
      <canvas id="overlay"></canvas>
   <!-- Omitted: element(s) behind canvas that should still be selectable -->

(The outerElement, canvas-wrapper and canvas elements have the same size.)

To make the elements behind the canvas act normally (e.g. selectable, editable), I used the following code: = 'none';

outerElement.addEventListener('mousedown', event => {
    const clickedOnElementInCanvas = yourCheck // TODO: check if the event *would* click a canvas element.
    if (!clickedOnElementInCanvas) {

        // if necessary, add logic to deselect your canvas elements ... = 'none';
        return true;

    // Check if we emitted the event ourselves (avoid endless loop)
    if (event.isTrusted) {
        // Manually forward element to the canvas
        const mouseEvent = new MouseEvent(event.type, event);
    return true;

Some canvas objects also came with input fields, so I had to allow keyboard events, too. To do this, I had to update the pointerEvents property based on whether a canvas input field was currently focused or not:

onCanvasModified(canvas, () => {
    const inputFieldInCanvasActive = // TODO: Check if an input field of the canvas is active. = inputFieldInCanvasActive  ? 'auto' : 'none';

Removing all line breaks and adding them after certain text

You need to that in two steps, at least.

First, click on the ¶ symbol in the toolbar: you can see if you have CRLF line endings or just LF.

Click on the Replace button, and put \r\n or \n, depending on the kind of line ending. In the Search Mode section of the dialog, check Extended radio button (interpret \n and such). Then replace all occurrences with nothing (empty string).

You end with a big line...

Next, in the same Replace dialog, put your delimiter (</Row>) for example and in the Replace With field, put the same with a line ending (</Row>\r\n). Replace All, and you are done.

C# Parsing JSON array of objects

I have just got an solution a little bit easier do get an list out of an JSON object. Hope this can help.

I got an JSON like this:


And made some types like this

    public class FinancialData
    public string Accounts { get; set; } // this will store the JSON string
    public List<Accounts> AccountsList { get; set; } // this will be the actually list. 

    public class Accounts
    public string bank { get; set; }
    public string account { get; set; }
    public string agency { get; set; }
    public string digit { get; set; }


and the "magic" part

 Models.FinancialData financialData = (Models.FinancialData)JsonConvert.DeserializeObject(myJSON,typeof(Models.FinancialData));
        var accounts = JsonConvert.DeserializeObject(financialData.Accounts) as JArray;

        foreach (var account in  accounts)
            if (financialData.AccountsList == null)
                financialData.AccountsList = new List<Models.Accounts>();


How to clear a notification in Android

Since no one has posted a code answer to this:

notification.flags = Notification.FLAG_AUTO_CANCEL;

.. and if you already have flags, you can OR FLAG_AUTO_CANCEL like this:

notification.flags = Notification.FLAG_INSISTENT | Notification.FLAG_AUTO_CANCEL;

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

I wrote a deep object copy extension method, based on recursive "MemberwiseClone". It is fast (three times faster than BinaryFormatter), and it works with any object. You don't need a default constructor or serializable attributes.

Source code:

using System.Collections.Generic;
using System.Reflection;
using System.ArrayExtensions;

namespace System
    public static class ObjectExtensions
        private static readonly MethodInfo CloneMethod = typeof(Object).GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance);

        public static bool IsPrimitive(this Type type)
            if (type == typeof(String)) return true;
            return (type.IsValueType & type.IsPrimitive);

        public static Object Copy(this Object originalObject)
            return InternalCopy(originalObject, new Dictionary<Object, Object>(new ReferenceEqualityComparer()));
        private static Object InternalCopy(Object originalObject, IDictionary<Object, Object> visited)
            if (originalObject == null) return null;
            var typeToReflect = originalObject.GetType();
            if (IsPrimitive(typeToReflect)) return originalObject;
            if (visited.ContainsKey(originalObject)) return visited[originalObject];
            if (typeof(Delegate).IsAssignableFrom(typeToReflect)) return null;
            var cloneObject = CloneMethod.Invoke(originalObject, null);
            if (typeToReflect.IsArray)
                var arrayType = typeToReflect.GetElementType();
                if (IsPrimitive(arrayType) == false)
                    Array clonedArray = (Array)cloneObject;
                    clonedArray.ForEach((array, indices) => array.SetValue(InternalCopy(clonedArray.GetValue(indices), visited), indices));

            visited.Add(originalObject, cloneObject);
            CopyFields(originalObject, visited, cloneObject, typeToReflect);
            RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect);
            return cloneObject;

        private static void RecursiveCopyBaseTypePrivateFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect)
            if (typeToReflect.BaseType != null)
                RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect.BaseType);
                CopyFields(originalObject, visited, cloneObject, typeToReflect.BaseType, BindingFlags.Instance | BindingFlags.NonPublic, info => info.IsPrivate);

        private static void CopyFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy, Func<FieldInfo, bool> filter = null)
            foreach (FieldInfo fieldInfo in typeToReflect.GetFields(bindingFlags))
                if (filter != null && filter(fieldInfo) == false) continue;
                if (IsPrimitive(fieldInfo.FieldType)) continue;
                var originalFieldValue = fieldInfo.GetValue(originalObject);
                var clonedFieldValue = InternalCopy(originalFieldValue, visited);
                fieldInfo.SetValue(cloneObject, clonedFieldValue);
        public static T Copy<T>(this T original)
            return (T)Copy((Object)original);

    public class ReferenceEqualityComparer : EqualityComparer<Object>
        public override bool Equals(object x, object y)
            return ReferenceEquals(x, y);
        public override int GetHashCode(object obj)
            if (obj == null) return 0;
            return obj.GetHashCode();

    namespace ArrayExtensions
        public static class ArrayExtensions
            public static void ForEach(this Array array, Action<Array, int[]> action)
                if (array.LongLength == 0) return;
                ArrayTraverse walker = new ArrayTraverse(array);
                do action(array, walker.Position);
                while (walker.Step());

        internal class ArrayTraverse
            public int[] Position;
            private int[] maxLengths;

            public ArrayTraverse(Array array)
                maxLengths = new int[array.Rank];
                for (int i = 0; i < array.Rank; ++i)
                    maxLengths[i] = array.GetLength(i) - 1;
                Position = new int[array.Rank];

            public bool Step()
                for (int i = 0; i < Position.Length; ++i)
                    if (Position[i] < maxLengths[i])
                        for (int j = 0; j < i; j++)
                            Position[j] = 0;
                        return true;
                return false;


Scala best way of turning a Collection into a Map-by-key?

This is probably not the most efficient way to turn a list to map, but it makes the calling code more readable. I used implicit conversions to add a mapBy method to List:

implicit def list2ListWithMapBy[T](list: List[T]): ListWithMapBy[T] = {
  new ListWithMapBy(list)

class ListWithMapBy[V](list: List[V]){
  def mapBy[K](keyFunc: V => K) = { => keyFunc(a) -> a).toMap

Calling code example:

val list = List("A", "AA", "AAA")
list.mapBy(_.length)                  //Map(1 -> A, 2 -> AA, 3 -> AAA)

Note that because of the implicit conversion, the caller code needs to import scala's implicitConversions.

Setting action for back button in navigation controller

Found a solution which retains the back button style as well. Add the following method to your view controller.

-(void) overrideBack{

    UIButton *transparentButton = [[UIButton alloc] init];
    [transparentButton setFrame:CGRectMake(0,0, 50, 40)];
    [transparentButton setBackgroundColor:[UIColor clearColor]];
    [transparentButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:transparentButton];


Now provide a functionality as needed in the following method:

-(void)backAction:(UIBarButtonItem *)sender {
    //Your functionality

All it does is to cover the back button with a transparent button ;)

It is more efficient to use if-return-return or if-else-return?

Version A is simpler and that's why I would use it.

And if you turn on all compiler warnings in Java you will get a warning on the second Version because it is unnecesarry and turns up code complexity.

How would I find the second largest salary from the employee table?

Most of the other answers seem to be db specific.

General SQL query should be as follows:

   emp a 
   N = (
         count(distinct sal) 
         emp b 
         a.sal <= b.sal
   N = any value

and this query should be able to work on any database.

How to connect android emulator to the internet

I think some of the answers may have addressed this, however obliquely, but here's what worked for me.

Assuming your problem is occurring when you're on a wireless network and you have a LAN card installed, the issue is that the emulator tries to obtain its DNS settings from that LAN card. Not a problem when you're connected via that LAN, but utterly useless if you're on a wireless connection. I noticed this when I was on my laptop.

So, how to fix? Simple: Disable your LAN card. Really. Just go to your Network connections, find your LAN card, right click it and choose disable. Now try your emulator. If you're like me, it suddenly ... works!

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

I'd create a cte and do an inner join. It's not efficient but it's convenient

with table as (

select *

from table t
join select(
max(Row_Num) as Row_Num
from table 
group by date, status, title) t2  
on t2.Row_Num = t.Row_Num and t2
and =
and t2.title = t.title

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

get selected value in datePicker and format it

$('#scheduleDate').datepicker({ dateFormat : 'dd, MM, yy'});

var dateFormat = $('#scheduleDate').datepicker('option', 'dd, MM, yy');

$('#scheduleDate').datepicker('option', 'dateFormat', 'dd, MM, yy');

var result = $('#scheduleDate').val();

alert('result: ' + result);

result: 20, April, 2012

How to force a hover state with jQuery?

I think the best solution I have come across is on this stackoverflow. This short jQuery code allows all your hover effects to show on click or touch..
No need to add anything within the function.

$('body').on('touchstart', function() {});

Hope this helps.

ConnectivityManager getNetworkInfo(int) deprecated

Since answers posted only allow you to query the active network, here's how to get NetworkInfo for any network, not only the active one (for example Wifi network) (sorry, Kotlin code ahead)

(getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).run {
    allNetworks.find { getNetworkInfo(it).type == ConnectivityManager.TYPE_WIFI }?.let { network -> getNetworkInfo(network) }
//    getNetworkInfo(ConnectivityManager.TYPE_WIFI).isAvailable // This is the deprecated API pre-21

This requires API 21 or higher and the permission android.permission.ACCESS_NETWORK_STATE

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined


import { Router, Route, Link, browserHistory } from 'react-router';


import { BrowserRouter as Router, Route } from 'react-router-dom';

It will start working. It is because react-router-dom exports BrowserRouter

how to open *.sdf files?

If you simply need to view the table and run queries on it you can use this third party sdf viewer. It is a lightweight viewer that has all the basic functionalities and is ready to use after install.

and ofcourse, its Free.

What certificates are trusted in truststore?

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

keytool -list -v -keystore truststore.jks

How can you create pop up messages in a batch script?

msg * message goes here

That method is very simple and easy and should work in any batch file i believe. The only "downside" to this method is that it can only show 1 message at once, if there is more than one message it will show each one after the other depending on the order you put them inside the code. Also make sure there is a different looping or continuous operator in your batch file or it will close automatically and only this message will appear. If you need a "quiet" background looping opperator, heres one:

pause >nul

That should keep it running but then it will close after a button is pressed.

Also to keep all the commands "quiet" when running, so they just run and dont display that they were typed into the file, just put the following line at the beginning of the batch file:

@echo off

I hope all these tips helped!

Error Message : Cannot find or open the PDB file

  1. Please check if the setting Generate Debug Info is Yes which under Project Propeties > Configuration Properties > Linker > Debugging tab. If not, try to change it to Yes.

  2. Those perticular pdb's ( for ntdll.dll, mscoree.dll, kernel32.dll, etc ) are for the windows API and shouldn't be needed for simple apps. However, if you cannot find pdb's for your own compiled projects, I suggest making sure the Project Properties > Configuration Properties > Debugging > Working Directory uses the value from Project Properties > Configuration Properties > General > Output Directory .

  3. You need to run Visual c++ in "Run as Administrator" mode.Right click on the executable and click "Run as Administrator"

Copy or rsync command

For a local copy, the only advantage of rsync is that it will avoid copying if the file already exists in the destination directory. The definition of "already exists" is (a) same file name (b) same size (c) same timestamp. (Maybe same owner/group; I am not sure...)

The "rsync algorithm" is great for incremental updates of a file over a slow network link, but it will not buy you much for a local copy, as it needs to read the existing (partial) file to run it's "diff" computation.

So if you are running this sort of command frequently, and the set of changed files is small relative to the total number of files, you should find that rsync is faster than cp. (Also rsync has a --delete option that you might find useful.)

What exactly is the difference between Web API and REST API in MVC?

I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.


It is neither an API nor a framework. It is just an architectural concept. You can find more details here.


I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.

EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.


It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).

Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.

Ruby get object keys as array

An alternative way if you need something more (besides using the keys method):

hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.collect {|key,value| key }

obviously you would only do that if you want to manipulate the array while retrieving it..

White space at top of page

If nothing of the above helps, check if there is margin-top set on some of the (some levels below) nested DOM element(s).

It will be not recognizable when you inspect body element itself in the debugger. It will only be visible when you unfold several elements nested down in body element in Chrome Dev Tools elements debugger and check if there is one of them with margin-top set.

The below is the upper part of a site screen shot and the corresponding Chrome Dev Tools view when you inspect body tag.

No sign of top margin here and you have resetted all the browser-scpecific CSS properties as per answers above but that unwanted white space is still here.

The unwanted white space above the body element The corresponding debugger view

The following is a view when you inspect the right nested element. It is clearly seen the orange'ish top-margin is set on it. This is the one that causes the white space on top of body element.

Clearly visible top-margin enter image description here

On that found element replace margin-top with padding-top if you need space above it and yet not to leak it above the body tag.

Hope that helps :)

Vue Js - Loop via v-for X times (in a range)

The same goes for v-for in range:

<li v-for="n in 20 " :key="n">{{n}}</li>

Updating records codeigniter

In your_controller write this...

public function update_title() 
    $data = array
        'table_id' => $this->input->post('table_id'),
        'table_title' => $this->input->post('table_title')

    $this->load->model('your_model'); // First load the model
    if($this->your_model->update_title($data)) // call the method from the controller
        // update successful...
        // update not successful...


While in your_model...

public function update_title($data)

This will works fine...

For vs. while in C programming?

They are all the same in the work they do. You can do the same things using any of them. But for readability, usability, convenience etc., they differ.

How do you use colspan and rowspan in HTML tables?

I'd suggest:

table {_x000D_
    empty-cells: show;_x000D_
    border: 1px solid #000;_x000D_
table td,_x000D_
table th {_x000D_
    min-width: 2em;_x000D_
    min-height: 2em;_x000D_
    border: 1px solid #000;_x000D_
            <th rowspan="2"></th>_x000D_
            <th colspan="4">&nbsp;</th>_x000D_


How to install .MSI using PowerShell

You can use:

msiexec /i "c:\package.msi"

You can also add some more optional parameters. There are common msi parameters and parameters which are specific for your installer. For common parameters just call msiexec

How to add new item to hash, value) - Stores a key-value pair in hash.


hash   #=> {"a"=>9, "b"=>200, "c"=>4}"d", 42) #=> 42
hash   #=> {"a"=>9, "b"=>200, "c"=>4, "d"=>42}


Copy a table from one database to another in Postgres

Here is what worked for me. First dump to a file:

pg_dump -h localhost -U myuser -C -t my_table -d first_db>/tmp/table_dump

then load the dumped file:

psql -U myuser -d second_db</tmp/table_dump

CSS submit button weird rendering on iPad/iPhone

The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)

opacity: 1

After setting the opacity, the button looked the same on all the different devices/emulator/desktop.

How to change the Title of the window in Qt?

int main(int argc, char *argv[])
    QApplication a(argc, argv);
    MainWindow w;
    w.setWindowTitle("Main Page");;
    return a.exec();

enter image description here

Calculating powers of integers

import java.util.Scanner;

class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(;
        int t = sc.nextInt();

        for (int i = 0; i < t; i++) {

            try {
                long x = sc.nextLong();
                System.out.println(x + " can be fitted in:");
                if (x >= -128 && x <= 127) {
                    System.out.println("* byte");
                if (x >= -32768 && x <= 32767) {
                    //Complete the code
                    System.out.println("* short");
                    System.out.println("* int");
                    System.out.println("* long");
                } else if (x >= -Math.pow(2, 31) && x <= Math.pow(2, 31) - 1) {
                    System.out.println("* int");
                    System.out.println("* long");
                } else {
                    System.out.println("* long");
            } catch (Exception e) {
                System.out.println( + " can't be fitted anywhere.");


Is Unit Testing worth the effort?

I didn't see this in any of the other answers, but one thing I noticed is that I could debug so much faster. You don't need to drill down through your app with just the right sequence of steps to get to the code your fixing, only to find you've made a boolean error and need to do it all again. With a unit test, you can just step directly into the code you're debugging. is deprecated, what should I use instead?

You should use:

URLEncoder.encode("NAME", "UTF-8");

How does internationalization work in JavaScript?

You can also try another library - .

In addition to parameter replacement and multiple plural forms, it has support for gender a rather unique feature of custom grammar rules that some languages need.

How can I change the text color with jQuery?

Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.

Why use armeabi-v7a code over armeabi code?

Instead of having a fat APK file, I would like to use just the armeabi files and remove the armeabi-v7a folder.

The opposite is a much better strategy. If you have minSdkVersion to 14 and upload your apk to the play store, you'll notice you'll support the same number of devices whether you support armeabi or not. Therefore, there are no devices with Android 4 or higher which would benefit from armeabi at all.

This is probably why the Android NDK doesn't even support armeabi anymore as per revision r17b. [source]

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

Exception is never thrown in body of corresponding try statement

As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try block. Try changing your code to:

    Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
catch(NumberFormatException e){
    throw new MojException("Bledne dane");

Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.

MongoDB what are the default user and password?

In addition to previously provided answers, one option is to follow the 'localhost exception' approach to create the first user if your db is already started with access control (--auth switch). In order to do that, you need to have localhost access to the server and then run:

use admin
     user: "user_name",
     pwd: "user_pass",
     roles: [
           { role: "userAdminAnyDatabase", db: "admin" },
           { role: "readWriteAnyDatabase", db: "admin" },
           { role: "dbAdminAnyDatabase", db: "admin" }

As stated in MongoDB documentation:

The localhost exception allows you to enable access control and then create the first user in the system. With the localhost exception, after you enable access control, connect to the localhost interface and create the first user in the admin database. The first user must have privileges to create other users, such as a user with the userAdmin or userAdminAnyDatabase role. Connections using the localhost exception only have access to create the first user on the admin database.

Here is the link to that section of the docs.

extra qualification error in C++

A worthy note for readability/maintainability:

You can keep the JSONDeserializer:: qualifier with the definition in your implementation file (*.cpp).

As long as your in-class declaration (as mentioned by others) does not have the qualifier, g++/gcc will play nice.

For example:

In myFile.h:

class JSONDeserializer
    Value ParseValue(TDR type, const json_string& valueString);

And in myFile.cpp:

Value JSONDeserializer::ParseValue(TDR type, const json_string& valueString)
    do_something(type, valueString);

When myFile.cpp implements methods from many classes, it helps to know who belongs to who, just by looking at the definition.

How exactly does <script defer="defer"> work?

Should be also noted that there might be problems in IE<=9 when using script defer in certain situations. More on this:

Git update submodules recursively

git submodule update --recursive

You will also probably want to use the --init option which will make it initialize any uninitialized submodules:

git submodule update --init --recursive

Note: in some older versions of Git, if you use the --init option, already-initialized submodules may not be updated. In that case, you should also run the command without --init option.

Function for C++ struct

Yes, a struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

struct foo {
  int bar;
  foo() : bar(3) {}   //look, a constructor
  int getBar() 
    return bar; 

foo f;
int y = f.getBar(); // y is 3

HashMap to return default value for non-found keys?

    public final Map<String, List<String>> stringMap = new ConcurrentHashMap<String, List<String>>() {
        public List<String> get(@NonNull Object key) {
            return computeIfAbsent((String) key, s -> new ArrayList<String>());

HashMap cause dead loop, so use ConcurrentHashMap instead of HashMap,

Subtract two dates in SQL and get days of the result


Select I.Fee
From Item I
WHERE  DATEDIFF(day, GETDATE(), I.DateCreated) < 365

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

ALTER table table_name Drop column column1, Drop column column2,Drop column column3;

for MySQL DB.

Or you can add some column while altering in the same line:

ALTER table table_name Drop column column1, ADD column column2 AFTER column7;

Place cursor at the end of text in EditText

You should be able to achieve that with the help of EditText's method setSelection(), see here

How to check that Request.QueryString has a specific value or not in ASP.NET?

You can also try:

if (!Request.QueryString.AllKeys.Contains("aspxerrorpath"))

How do I find the current executable filename?

In addition to the answers above.

I wrote following test.exe as console application

static void Main(string[] args) {

Then I compiled the project and renamed its output to the test2.exe file. The output lines were correct and the same.

But, if I start it in the Visual Studio, the result is:





The ReSharper plug-in to the Visual Studio has underlined the


as possible System.NullReferenceException. If you look into documentation of the MainModule you will find that this property can throw also NotSupportedException, PlatformNotSupportedException and InvalidOperationException.

The GetEntryAssembly method is also not 100% "safe". MSDN:

The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.

For my solutions, I prefer the Assembly.GetEntryAssembly().Location.

More interest is if need to solve the problem for the virtualization. For example, we have a project, where we use a Xenocode Postbuild to link the .net code into one executable. This executable must be renamed. So all the methods above didn't work, because they only gets the information for the original assembly or inner process.

The only solution I found is

var location = System.Reflection.Assembly.GetEntryAssembly().Location;
var directory = System.IO.Path.GetDirectoryName(location);
var file = System.IO.Path.Combine(directory, 
  System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@Jk1's answer is fine, but Mockito also allows for more succinct injection using annotations:

@InjectMocks MyClass myClass; //@InjectMocks automatically instantiates too
@Mock MyInterface myInterface

But regardless of which method you use, the annotations are not being processed (not even your @Mock) unless you somehow call the static MockitoAnnotation.initMocks() or annotate the class with @RunWith(MockitoJUnitRunner.class).

How can I position my jQuery dialog to center?

Could not get IE9 to center the dialog.

Fixed it by adding this to the css:

.ui-dialog {

Percent doesn't matter. Any small number worked.

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

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

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

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

To get only the line numbers, you could use

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

Or you could simply use sed:

sed -n '/regex/=' file

Combining the two sed commands, you get:

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

Python threading. How do I lock a thread?

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  

def bye():
    while count < 5:

def hello_there():
    while count < 5:

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)

if __name__ == '__main__':

Sample output:

Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired

Difference between app.use and app.get in express.js

app.get is called when the HTTP method is set to GET, whereas app.use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.

How to cast Object to boolean?

Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())

Change default icon

Go to form's properties, ICON ... Choose an icon you want.

EDIT: try this

  1. Edit App.Ico to make it look like you want.
  2. In the property pane for your form, set the Icon property to your project's App.Ico file.
  3. Rebuild solution.

And read this one icons

C++ display stack trace on exception

A working example for OSX (tested right now on Catalina 10.15). Not portable to linux/windows obviously. Probably it will be usefull to somebody.

In the "Mew-exception" string you can use backtrace and/or backtrace_symbols functions

#include <stdexcept>
#include <typeinfo>
#include <dlfcn.h>

extern "C" void __cxa_throw(void *thrown_object, std::type_info *tinfo, void (*dest)(void *));
static void (*__cxa_throw_orig)(void *thrown_object, std::type_info *tinfo, void (*dest)(void *));
extern "C" void luna_cxa_throw(void *thrown_object, std::type_info *tinfo, void (*dest)(void *))
    printf("Mew-exception you can catch your backtrace here!");
    __cxa_throw_orig(thrown_object, tinfo, dest);

//__attribute__ ((used))
//__attribute__ ((section ("__DATA,__interpose")))
static struct replace_pair_t {
    void *replacement, *replacee;
} replace_pair = { (void*)luna_cxa_throw, (void*)__cxa_throw };

extern "C" const struct mach_header __dso_handle;
extern "C" void dyld_dynamic_interpose(const struct mach_header*,
                               const replace_pair_t replacements[],
                               size_t count);

int fn()
    int a = 10; ++a;
    throw std::runtime_error("Mew!");

int main(int argc, const char * argv[]) {
    __cxa_throw_orig = (void (*)(void *thrown_object, std::type_info *tinfo, void (*dest)(void *)))dlsym(RTLD_DEFAULT, "__cxa_throw");

    dyld_dynamic_interpose(&__dso_handle, &replace_pair, 1);

    return 0;

Update data on a page without refreshing

Suppose you want to display some live feed content (say livefeed.txt) on you web page without any page refresh then the following simplified example is for you.

In the below html file, the live data gets updated on the div element of id "liveData"


<!DOCTYPE html>
    <title>Live Update</title>
    <meta charset="UTF-8">
    <script type="text/javascript" src="autoUpdate.js"></script>
<div id="liveData">
    <p>Loading Data...</p>

Below autoUpdate.js reads the live data using XMLHttpRequest object and updates the html div element on every 1 second. I have given comments on most part of the code for better understanding.


window.addEventListener('load', function()
    var xhr = null;

    getXmlHttpRequestObject = function()
            // Create a new XMLHttpRequest object 
            xhr = new XMLHttpRequest();
        return xhr;

    updateLiveData = function()
        var now = new Date();
        // Date string is appended as a query with live data 
        // for not to use the cached version 
        var url = 'livefeed.txt?' + now.getTime();
        xhr = getXmlHttpRequestObject();
        xhr.onreadystatechange = evenHandler;
        // asynchronous requests"GET", url, true);
        // Send the request over the network


    function evenHandler()
        // Check response is ready or not
        if(xhr.readyState == 4 && xhr.status == 200)
            dataDiv = document.getElementById('liveData');
            // Set current data text
            dataDiv.innerHTML = xhr.responseText;
            // Update the live data every 1 sec
            setTimeout(updateLiveData(), 1000);

For testing purpose: Just write some thing in the livefeed.txt - You will get updated the same in index.html without any refresh.



Note: You need to run the above code on the web server (ex: http://localhost:1234/index.html) not as a client html file (ex: file:///C:/index.html).

Setting Android Theme background color


    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
        <item name="android:windowBackground">@android:color/black</item>


What is the '.well' equivalent class in Bootstrap 4

I'm mading my classes well for class alert, for me it looks like it's getting nice, but some tweaks are sometimes needed as to put the width 100%

<div class="alert alert-light" style="width:100%;">
  <strong>Heads up!</strong> This <a href="#" class="alert-link">alert needs your attention</a>, but it's not super important.

Loading PictureBox Image from resource file with path (Part 3)

Setting "Copy to Output Directory" to "Copy always" or "Copy if newer" may help for you.

Your PicPath is a relative path that is converted into an absolute path at some time while loading the image. Most probably you will see that there are no images on the specified location if you use Path.GetFullPath(PicPath) in Debug.

Procedure expects parameter which was not supplied

In addition to the other answers here, if you've forgotten to put:

cmd.CommandType = CommandType.StoredProcedure;

Then you will also get this error.

What are the various "Build action" settings in Visual Studio project properties and what do they do?

  • Fakes: Part of the Microsoft Fakes (Unit Test Isolation) Framework. Not available on all Visual Studio versions. Fakes are used to support unit testing in your project, helping you isolate the code you are testing by replacing other parts of the application with stubs or shims. More here:

How do I make a PHP form that submits to self?

  1. change
    <input type="submit" value="Submit" />
    <input type="submit" value="Submit" name='submit'/>

  2. change
    <form method="post" action="<?php echo $PHP_SELF;?>">
    <form method="post" action="">

  3. It will perform the code in if only when it is submitted.
  4. It will always show the form (html code).
  5. what exactly is your question?

How to terminate a Python script

Another way is:

raise SystemExit

Sending private messages to user

In order for a bot to send a message, you need <client>.send() , the client is where the bot will send a message to(A channel, everywhere in the server, or a PM). Since you want the bot to PM a certain user, you can use as your client. (you can replace author as mentioned user in a message or something, etc)

Hence, the answer is:"Your message here.")

I recommend looking up the Discord.js documentation about a certain object's properties whenever you get stuck, you might find a particular function that may serve as your solution.

How do I measure a time interval in C?

The following is a group of versatile C functions for timer management based on the gettimeofday() system call. All the timer properties are contained in a single ticktimer struct - the interval you want, the total running time since the timer initialization, a pointer to the desired callback you want to call, the number of times the callback was called. A callback function would look like this:

void your_timer_cb (struct ticktimer *t) {
  /* do your stuff here */

To initialize and start a timer, call ticktimer_init(your_timer, interval, TICKTIMER_RUN, your_timer_cb, 0).

In the main loop of your program call ticktimer_tick(your_timer) and it will decide whether the appropriate amount of time has passed to invoke the callback.

To stop a timer, just call ticktimer_ctl(your_timer, TICKTIMER_STOP).


#ifndef __TICKTIMER_H
#define __TICKTIMER_H

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>

#define TICKTIMER_STOP         0x00
#define TICKTIMER_RUN          0x01

struct ticktimer {
  u_int64_t tm_tick_interval;
  u_int64_t tm_last_ticked;
  u_int64_t tm_total;
  unsigned ticks_total;
  void (*tick)(struct ticktimer *);
  unsigned char flags;
  int id;

void ticktimer_init (struct ticktimer *, u_int64_t, unsigned char, void (*)(struct ticktimer *), int);
unsigned ticktimer_tick (struct ticktimer *);
void ticktimer_ctl (struct ticktimer *, unsigned char);
struct ticktimer *ticktimer_alloc (void);
void ticktimer_free (struct ticktimer *);
void ticktimer_tick_all (void);



#include "ticktimer.h"

#define TIMER_COUNT 100

static struct ticktimer timers[TIMER_COUNT];
static struct timeval tm;

    Initializes/sets the ticktimer struct.

  @param timer
    Pointer to ticktimer struct.
  @param interval
    Ticking interval in microseconds.
  @param flags
    to start a compensating timer; TICKTIMER_RUN to start
    a normal uncompensating timer.
  @param tick
    Ticking callback function.
  @param id
    Timer ID. Useful if you want to distinguish different
    timers within the same callback function.
void ticktimer_init (struct ticktimer *timer, u_int64_t interval, unsigned char flags, void (*tick)(struct ticktimer *), int id) {
  gettimeofday(&tm, NULL);
  timer->tm_tick_interval = interval;
  timer->tm_last_ticked = tm.tv_sec * 1000000 + tm.tv_usec;
  timer->tm_total = 0;
  timer->ticks_total = 0;
  timer->tick = tick;
  timer->flags = flags;
  timer->id = id;

    Checks the status of a ticktimer and performs a tick(s) if 

  @param timer
    Pointer to ticktimer struct.

    The number of times the timer was ticked.
unsigned ticktimer_tick (struct ticktimer *timer) {
  register typeof(timer->tm_tick_interval) now;
  register typeof(timer->ticks_total) nticks, i;

  if (timer->flags & TICKTIMER_RUN) {
    gettimeofday(&tm, NULL);
    now = tm.tv_sec * 1000000 + tm.tv_usec;

    if (now >= timer->tm_last_ticked + timer->tm_tick_interval) {
      timer->tm_total += now - timer->tm_last_ticked;

      if (timer->flags & TICKTIMER_COMPENSATE) {
        nticks = (now - timer->tm_last_ticked) / timer->tm_tick_interval;
        timer->tm_last_ticked = now - ((now - timer->tm_last_ticked) % timer->tm_tick_interval);

        for (i = 0; i < nticks; i++) {

          if (timer->tick == NULL) {

        return nticks;
      } else {
        timer->tm_last_ticked = now;
        return 1;

  return 0;

    Controls the behaviour of a ticktimer.

  @param timer
    Pointer to ticktimer struct.
  @param flags
    Flag bitmask.
inline void ticktimer_ctl (struct ticktimer *timer, unsigned char flags) {
  timer->flags = flags;

    Allocates a ticktimer struct from an internal
    statically allocated list.

    Pointer to the newly allocated ticktimer struct
    or NULL when no more space is available.
struct ticktimer *ticktimer_alloc (void) {
  register int i;

  for (i = 0; i < TIMER_COUNT; i++) {
    if (timers[i].tick == NULL) {
      return timers + i;

  return NULL;

    Marks a previously allocated ticktimer struct as free.

  @param timer
    Pointer to ticktimer struct, usually returned by 
inline void ticktimer_free (struct ticktimer *timer) {
  timer->tick = NULL;

    Checks the status of all allocated timers from the 
    internal list and performs ticks where necessary.

    Should be called in the main loop.
inline void ticktimer_tick_all (void) {
  register int i;

  for (i = 0; i < TIMER_COUNT; i++) {
    if (timers[i].tick != NULL) {
      ticktimer_tick(timers + i);

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Your json string is wrapped within square brackets ([]), hence it is interpreted as array instead of single RetrieveMultipleResponse object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse, for example :

var objResponse1 = 

ngOnInit not being called when Injectable class is Instantiated

I don't know about all the lifecycle hooks, but as for destruction, ngOnDestroy actually get called on Injectable when it's provider is destroyed (for example an Injectable supplied by a component).

From the docs :

Lifecycle hook that is called when a directive, pipe or service is destroyed.

Just in case anyone is interested in destruction check this question:

Angular JS - angular.forEach - How to get key of the object?

var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
    console.log(key + ': ' + value);

yields the attributes of obj with their respective values:

name: Krishna
gender: male

Throw HttpResponseException or return Request.CreateErrorResponse?

Do not throw an HttpResponseException or return an HttpResponesMessage for errors - except if the intent is to end the request with that exact result.

HttpResponseException's are not handled the same as other exceptions. They are not caught in Exception Filters. They are not caught in the Exception Handler. They are a sly way to slip in an HttpResponseMessage while terminating the current code's execution flow.

Unless the code is infrastructure code relying on this special un-handling, avoid using the HttpResponseException type!

HttpResponseMessage's are not exceptions. They do not terminate the current code's execution flow. They can not be filtered as exceptions. They can not be logged as exceptions. They represent a valid result - even a 500 response is "a valid non-exception response"!

Make life simpler:

When there is an exceptional/error case, go ahead and throw a normal .NET exception - or a customized application exception type (not deriving from HttpResponseException) with desired 'http error/response' properties such as a status code - as per normal exception handling.

Use Exception Filters / Exception Handlers / Exception Loggers to do something appropriate with these exceptional cases: change/add status codes? add tracking identifiers? include stack traces? log?

By avoiding HttpResponseException the 'exceptional case' handling is made uniform and can be handled as part of the exposed pipeline! For example one can turn a 'NotFound' into a 404 and an 'ArgumentException' into a 400 and a 'NullReference' into a 500 easily and uniformly with application-level exceptions - while allowing extensibility to provide "basics" such as error logging.

CSS horizontal scroll

Use this code to generate horizontal scrolling blocks contents. I got this from here

<title>HTMLExplorer Demo: Horizontal Scrolling Content</title>
<style type="text/css">
#outer_wrapper {  
    overflow: scroll;  
#outer_wrapper #inner_wrapper {
    width:6000px; /* If you have more elements, increase the width accordingly */
#outer_wrapper #inner_wrapper { /* Define the properties of inner block */
    width: 250px;
    float: left;
    margin: 0 4px 0 0;
    border:1px grey solid;

<div id="outer_wrapper">
    <div id="inner_wrapper">
        <div class="box">
            <!-- Add desired content here -->
   - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        <div class="box">
             <!-- Add desired content here -->
   - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        <div class="box">
            <!-- Add desired content here -->
   - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        <div class="box">
            <!-- Add desired content here -->
   - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        <div class="box">
             <!-- Add desired content here -->
   - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        <div class="box">
            <!-- Add desired content here -->
   - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        <!-- more boxes here -->

Windows path in Python

Use the os.path module.

os.path.join( "C:", "meshes", "as" )

Or use raw strings


I would also recommend no spaces in the path or file names. And you could use double backslashes in your strings.


How to launch an Activity from another Application in Android

I found the solution. In the manifest file of the application I found the package name: com.package.address and the name of the main activity which I want to launch: MainActivity The following code starts this application:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.package.address","com.package.address.MainActivity"));

How to detect when facebook's FB.init is complete

Here's a simpler method, that requires neither events or timeouts. It does require jQuery, however.

Use jQuery.holdReady() (docs)

So, immediately after your jQuery script, delay the ready event.

<!-- jQuery -->
<script src=""></script>
    $.holdReady( true ); // don't fire ready until told (ie when FB loaded)

Then, in your Facebook init function, release it:

window.fbAsyncInit = function() {
        appId: '11111111111111',
        cookie: true,
        xfbml: false,
        version: 'v2.4'

    // release the ready event to execute
    $.holdReady( false );

Then you can use the ready event as normal:

$(document).ready( myApp.init );

Split comma separated column data into additional columns

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').

How to show math equations in general github's markdown(not github's blog)

If just wanted to show math in the browser for yourself, you could try the Chrome extension GitHub with MathJax. It's quite convenient.

CSS word-wrapping in div

Setting just the width and float css properties would get a wrapping panel. The folowing example work just fine:

<div style="float:left; width: 250px">
Pellentesque feugiat tempor elit. Ut mollis lacinia quam. 
Sed pharetra, augue aliquam   ornare vestibulum, metus massa
laoreet tellus, eget iaculis lacus ipsum et diam. 

Maybe there are other styles in place that modify the appearance?

Writing a VLOOKUP function in vba

Please find the code below for Vlookup:

Function vlookupVBA(lookupValue, rangeString, colOffset)
vlookupVBA = "#N/A"
On Error Resume Next
Dim table_lookup As range
Set table_lookup = range(rangeString)
vlookupVBA = Application.WorksheetFunction.vlookup(lookupValue, table_lookup, colOffset, False)
End Function

What is token-based authentication?

A token is a piece of data created by server, and contains information to identify a particular user and token validity. The token will contain the user's information, as well as a special token code that user can pass to the server with every method that supports authentication, instead of passing a username and password directly.

Token-based authentication is a security technique that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server.

An authentication is successful if a user can prove to a server that he or she is a valid user by passing a security token. The service validates the security token and processes the user request.

After the token is validated by the service, it is used to establish security context for the client, so the service can make authorization decisions or audit activity for successive user requests.

Source (Web Archive)

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

On my execution of openssl pkcs12 -export -out cacert.pkcs12 -in testca/cacert.pem, I received the following message:

unable to load private key 140707250050712:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:701:Expecting: ANY PRIVATE KEY`

Got this solved by providing the key file along with the command. The switch is -inkey inkeyfile.pem

Embedding SVG into ReactJS

The best way I found was this site

You copy an svg and it give you a react functional component with the svg transformed to react code.

space between divs - display table-cell

Well, the above does work, here is my solution that requires a little less markup and is more flexible.

.cells {_x000D_
  display: inline-block;_x000D_
  float: left;_x000D_
  padding: 1px;_x000D_
.cells>.content {_x000D_
  background: #EEE;_x000D_
  display: table-cell;_x000D_
  float: left;_x000D_
  padding: 3px;_x000D_
  vertical-align: middle;_x000D_
<div id="div1" class="cells"><div class="content">My Cell 1</div></div>_x000D_
<div id="div2" class="cells"><div class="content">My Cell 2</div></div>

JavaScript window resize event

window.onresize = function() {
    // your code

How do I move a file (or folder) from one folder to another in TortoiseSVN?

To move a file or set of files using Tortoise SVN, right-click-and-drag the target files to their destination and release the right mouse button. The popup menu will have a SVN move versioned files here option.

Note that the destination folder must have already been added to the repository for the SVN move versioned files here option to appear.

How to print to console when using Qt

Add this to your project file:

CONFIG += console

Python convert object to float

I eventually used:

weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)

It worked just fine, except that I got the following message.

C:\ProgramData\Anaconda3\lib\site-packages\ FutureWarning:
convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

EntityType has no key defined error

In my case, I was getting the error when creating an "MVC 5 Controller with view, using Entity Framework".

I just needed to Build the project after creating the Model class and didn't need to use the [Key] annotation.

fatal error: iostream.h no such file or directory

Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)

#include <iostream>

int main()
    std::cout<<"Hello World!\n";
    return 0;

How to retrieve data from a SQL Server database in C#?

To retrieve data from database:

private SqlConnection Conn;
 private void CreateConnection()
    string ConnStr =
    Conn = new SqlConnection(ConnStr);
 public DataTable getData()
    string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
    SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
    DataTable dt = new DataTable();
    catch (SqlException se)
        DBErLog.DbServLog(se, se.ToString());
    return dt;

Javascript - validation, numbers only

Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.


RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.

Simply omit the negating ! and use if(/\D/.test(z)).

How do I kill a process using Vb.NET or C#?

You'll want to use the System.Diagnostics.Process.Kill method. You can obtain the process you want using System.Diagnostics.Proccess.GetProcessesByName.

Examples have already been posted here, but I found that the non-.exe version worked better, so something like:

foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") )
        p.WaitForExit(); // possibly with a timeout
    catch ( Win32Exception winException )
        // process was terminating or can't be terminated - deal with it
    catch ( InvalidOperationException invalidException )
        // process has already exited - might be able to let this one go

You probably don't have to deal with NotSupportedException, which suggests that the process is remote.

How to correctly get image from 'Resources' folder in NetBeans

I have a slightly different approach that might be useful/more beneficial to some.

Under your main project folder, create a resource folder. Your folder structure should look something like this.

  • Project Folder
    • build
    • dist
    • lib
    • nbproject
    • resources
    • src

Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.

Under categories on the left side, select Sources.

In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.

enter image description here

You should now be able to pull resources using this line or similar approach:


If you were to create a package called Images under the resources folder, you can retrieve the resource like this:


ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

I also face the similar Issue. Nothing programmer has to do to resolve this error. I informed to my oracle DBA team. They kill the session and worked like a charm.

PivotTable to show values, not sum of values

Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =

In my case the column header is URL

Creating PHP class instance with a string

have a look at example 3 from

$className = 'Foo';
$instance = new $className(); // Foo()

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

I resolved this issue by downloading current version of graddle from link given download latest version of graddle possibly graddle 3.3

Then in next step i accessed .graddle/wrapper/dists dirctory from home directory on my Mac after showing up hidden system files and deleted previuos version folder residing there.

Now i put that downloaded latest version folder after uncompressing there. Now restarted Android studio and problem was resolved.

Create Excel file in Java

I've created the API "generator-excel" to create an Excel file, below the dependecy:


This library can to configure the styles, the functions, the charts, the pivot table and etc. through a series of annotations.
You can write rows by getting data from a datasource trough a query with or without parameters.
Below an example to develop

  1. I created 2 classes that represents the row of the table.
  2. package;
        import java.util.Date;
        @ExcelRowHeight(height = 3)
        public class UtenteRow implements RowSheet {
            @ExcelColumn(columnName = "Id", indexColumn = 0)
            @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
            private Integer idUtente; 
            @ExcelColumn(columnName = "Nome", indexColumn = 2)
            private String nome; 
            @ExcelColumn(columnName = "Cognome", indexColumn = 1)
            private String cognome;
            @ExcelColumn(columnName = "Data di nascita", indexColumn = 3)
            @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.CENTER)
            private Date dataNascita;
            @ExcelColumn(columnName = "Immagine", indexColumn = 4)
            @ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
            private byte[] image;   
            @ExcelColumn(columnName = "Path", indexColumn = 5)
            @ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
            private String path;    
            public UtenteRow() {
            public UtenteRow(Integer idUtente, String nome, String cognome, Date dataNascita) {
                this.idUtente = idUtente;
                this.nome = nome;
                this.cognome = cognome;
                this.dataNascita = dataNascita;
            public Integer getIdUtente() {
                return idUtente;
            public void setIdUtente(Integer idUtente) {
                this.idUtente = idUtente;
            public String getNome() {
                return nome;
            public void setNome(String nome) {
                this.nome = nome;
            public String getCognome() {
                return cognome;
            public void setCognome(String cognome) {
                this.cognome = cognome;
            public Date getDataNascita() {
                return dataNascita;
            public void setDataNascita(Date dataNascita) {
                this.dataNascita = dataNascita;
            public byte[] getImage() {
                return image;
            public String getPath() {
                return path;
            public void setImage(byte[] image) {
                this.image = image;
            public void setPath(String path) {
                this.path = path;

    @ExcelSubtotals(labelTotalGroup = "Total",endLabel = "total")
    public class SalaryRow implements RowSheet {
        @ExcelColumn(columnName = "Name", indexColumn = 0)
        private String name;
        @ExcelColumn(columnName = "Amount", indexColumn = 1)
        @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
        @ExcelSubtotal(dataConsolidateFunction = DataConsolidateFunction.SUM,excelCellLayout = @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT,font=@ExcelFont(bold = true)))
        private Double amount;
        public SalaryRow() {
        public SalaryRow(String name, Double amount) {
   = name;
            this.amount = amount;
        public String getName() {
            return name;
        public void setName(String name) {
   = name;
        public Double getAmount() {
            return amount;
        public void setAmount(Double amount) {
            this.amount = amount;
  3. I created 2 class that represents the sheets.
  4. package;
    import javax.validation.constraints.Size;
    @ExcelMarginSheet(bottom = 1.5, left = 1.5, right = 1.5, top = 1.5)
    @ExcelQuery(select = "SELECT id_utente, nome, cognome, data_nascita,image,path "
            + "FROM utente "
            + "WHERE cognome=:cognome "
            + "order by cognome,nome")
    public class UtenteSheet extends QuerySheetData<UtenteRow> {
        public UtenteSheet(@Size(max = 31) String sheetName) {

    import javax.validation.constraints.Size;
    @ExcelMarginSheet(bottom = 1.5,left = 1.5,right = 1.5,top = 1.5)
    public class SalarySheet extends SheetData<SalaryRow> {
        public SalarySheet(@Size(max = 31) String sheetName) {
  5. Class test, in the test function there are antoher sheets
  6. package;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.util.List;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
     * The Class ReportTest.
    @ComponentScan(basePackages = {"bld.generator",""})
    public class ReportTestJpa {
        /** The Constant PATH_FILE. */
        private static final String PATH_FILE = "/mnt/report/";
        /** The generate excel. */
        private GenerateExcel generateExcel;
         * Sets the up.
         * @throws Exception the exception
        public void setUp() throws Exception {
         * Test.
         * @throws Exception the exception
        public void test() throws Exception {
            List<BaseSheet> listBaseSheet = new ArrayList<>();
            UtenteSheet utenteSheet=new UtenteSheet("Utente");
            utenteSheet.getMapParameters().put("cognome", "Rossi");
            CasaEditrice casaEditrice = new CasaEditrice("Casa Editrice","Mondadori", new GregorianCalendar(1955, Calendar.MAY, 10), "Roma", "/home/francesco/Documents/git-project/dev-excel/linux.jpg","Drammatico");
            AutoreLibriSheet autoreLibriSheet = new AutoreLibriSheet("Libri d'autore","Test label");
            TotaleAutoreLibriSheet totaleAutoreLibriSheet=new TotaleAutoreLibriSheet();
            totaleAutoreLibriSheet.getListRowSheet().add(new TotaleAutoreLibriRow("Totale"));
            GenereSheet genereSheet=new GenereSheet("Genere");
            SalarySheet salarySheet=new SalarySheet("salary");
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            ReportExcel excel = new ReportExcel("Mondadori JPA", listBaseSheet);
            byte[] byteReport = this.generateExcel.createFileXlsx(excel);
            ExcelUtils.writeToFile(PATH_FILE,excel.getTitle(), ".xlsx", byteReport);
  7. Application yaml
  8. logging:
        root: WARN
            web: DEBUG
          hibernate: ERROR
        url: jdbc:postgresql://localhost:5432/excel_db
        username: ${EXCEL_USER_DB}
        password: ${EXCEL_PASSWORD_DB}
        show-sql: true
            default_schema: public
                non_contextual_creation: true 
            format_sql: true    
            ddl-auto: auto
        database-platform: org.hibernate.dialect.PostgreSQLDialect
        generate-ddl: true

below the link of the project on github:

Invalid use side-effecting operator Insert within a function

There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.

The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.

I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.

Creating a new user and password with Ansible

If you'd like to accomplish this as a Ansible ad-hoc command you can do the following:

$ password='SomethingSecret!'
$ ansible -i some_inventory -b -m user -a "name=joe_user \
       update_password=always password=\"{{ \"$password\" | password_hash('sha512') }}\""

Output from above command: | SUCCESS => {
    "append": false,
    "changed": true,
    "comment": "Joe User",
    "group": 999,
    "home": "/home/joe_user",
    "move_home": false,
    "name": "joe_user",
    "password": "NOT_LOGGING_PASSWORD",
    "shell": "/bin/bash",
    "state": "present",
    "uid": 999

How to Deserialize JSON data?

You can deserialize this really easily. The data's structure in C# is just List<string[]> so you could just do;

  List<string[]> data = JsonConvert.DeserializeObject<List<string[]>>(jsonString);

The above code is assuming you're using json.NET.

EDIT: Note the json is technically an array of string arrays. I prefer to use List<string[]> for my own declaration because it's imo more intuitive. It won't cause any problems for json.NET, if you want it to be an array of string arrays then you need to change the type to (I think) string[][] but there are some funny little gotcha's with jagged and 2D arrays in C# that I don't really know about so I just don't bother dealing with it here.

Spring JUnit: How to Mock autowired component in autowired component

You could use Mockito. I am not sure with PostConstruct specifically, but this generally works:

// Create a mock of Resource to change its behaviour for testing
private Resource resource;

// Testing instance, mocked `resource` should be injected here 
private TestedClass testedClass;

public void setUp() throws Exception {
    // Initialize mocks created above
    // Change behaviour of `resource`

How to subtract/add days from/to a date?

Just subtract a number:

> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"

Since the Date class only has days, you can just do basic arithmetic on it.

If you want to use POSIXlt for some reason, then you can use it's slots:

> a <- as.POSIXlt("2009-10-04")
> names(unclass(as.POSIXlt("2009-10-04")))
[1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"
> a$mday <- a$mday - 6
> a
[1] "2009-09-28 EDT"

Clearing <input type='file' /> using jQuery

Quick answer: replace it.

In the code below I use the replaceWith jQuery method to replace the control with a clone of itself. In the event you have any handlers bound to events on this control, we'll want to preserve those as well. To do this we pass in true as the first parameter of the clone method.

<input type="file" id="control"/>
<button id="clear">Clear</button>
var control = $("#control");

$("#clear").on("click", function () {
    control.replaceWith( control = control.clone( true ) );


If cloning, while preserving event handlers, presents any issues you could consider using event delegation to handle clicks on this control from a parent element:

$("form").on("focus", "#control", doStuff);

This prevents the need for any handlers to be cloned along with the element when the control is being refreshed.

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

In my case, the error occurred when I made python makemigrations on Django 2.0.6.

The solution was to run python runserver and see the actual error (which was just a missing environment variable).

How to play ringtone/alarm sound in Android

It may be late but there is a new simple solution to this question for who ever wants it.
In kotlin

val player = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI)

Above code will play default ringtone but if you want default alarm, change




Disabling submit button until all fields have values

I refactored the chosen answer here and improved on it. The chosen answer only works assuming you have one form per page. I solved this for multiple forms on same page (in my case I have 2 modals on same page) and my solution only checks for values on required fields. My solution gracefully degrades if JavaScript is disabled and includes a slick CSS button fade transition.

See working JS fiddle example:


 function submitState(el) {

    var $form = $(el),
        $requiredInputs = $form.find('input:required'),
        $submit = $form.find('input[type="submit"]');

    $submit.attr('disabled', 'disabled');

    $requiredInputs.keyup(function () {

      $'empty', 'false');

      $requiredInputs.each(function() {
        if ($(this).val() === '') {
          $'empty', 'true');

      if ($'empty') === 'true') {
        $submit.attr('disabled', 'disabled').attr('title', 'fill in all required fields');
      } else {
        $submit.removeAttr('disabled').attr('title', 'click to submit');

  // apply to each form element individually


input[type="submit"] {
  background: #5cb85c;
  color: #fff;
  transition: background 600ms;
  cursor: pointer;

input[type="submit"]:disabled {
  background: #555;
  cursor: not-allowed;


<h4>Sign Up</h4>
<form id="sign_up_user" data-empty="" action="#" method="post">
 <input type="email" name="email" placeholder="Email" required>
 <input type="password" name="password" placeholder="Password" required>
 <input type="password" name="password_confirmation" placeholder="Password Confirmation" required>
 <input type="hidden" name="secret" value="secret">
 <input type="submit" value="signup">

<form id="login_user" data-empty="" action="#" method="post">
 <input type="email" name="email" placeholder="Email" required>
 <input type="password" name="password" placeholder="Password" required>
 <input type="checkbox" name="remember" value="1"> remember me
 <input type="submit" value="signup">

Change div height on button click

You have to set height as a string value when you use pixels.

document.getElementById('chartdiv').style.height = "200px"

Also try adding a DOCTYPE to your HTML for Internet Explorer.

<!DOCTYPE html>
<html> ...

Convert to date format dd/mm/yyyy

You can use a regular expression or some manual string fiddling, but I think I prefer:

date("d/m/Y", strtotime($str));

installing apache: no VCRUNTIME140.dll

I had same problem, my issue was that downloaded Apache 2.4 but 32 bits. Then re-download 64bits version and it's works.

I hope it helps you

add Shadow on UIView using swift 3

Shadow using UIView Extension Swift 4

I would like to add one more line with selected answer! When we rasterizing the layer, It needs to be set to 2.0 for retina displays. Otherwise label text or images on that view will be blurry. So we need to add rasterizationScale also.

  extension UIView {

    func dropShadow() {
        layer.masksToBounds = false
        layer.shadowColor =
        layer.shadowOpacity = 0.5
        layer.shadowOffset = CGSize(width: -1, height: 1)
        layer.shadowRadius = 1
        layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        layer.shouldRasterize = true
        layer.rasterizationScale = UIScreen.main.scale

printf with std::string?

use myString.c_str() if you want a c-like string (const char*) to use with printf


Check if value exists in the array (AngularJS)

U can use something like this....

  function (field,value) {

         var newItemOrder= value;
          // Make sure user hasnt already added this item
        angular.forEach(arr, function(item) {
            if (newItemOrder == item.value) {

            } });


How to create a MySQL hierarchical recursive query?

Its a little tricky one, check this whether it is working for you

select,if(a.parent = 0,@varw:=concat(,','),@varw:=concat(,',',@varw)) as list from (select * from recursivejoin order by if(parent=0,id,parent) asc) a left join recursivejoin b on ( = b.parent),(select @varw:='') as c  having list like '%19,%';

SQL fiddle link!2/e3cdf/2

Replace with your field and table name appropriately.

How can I get a list of all values in select box?





Link to fiddle

And I agree with Abraham - you might want to use text instead of value

The reason your fiddle didn't work was because you chose the option: "onLoad" instead of: "No wrap - in "

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

Also make sure the value is not too large or too small for int like in my case.

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

Gantt chart is wrong... First process P3 has arrived so it will execute first. Since the burst time of P3 is 3sec after the completion of P3, processes P2,P4, and P5 has been arrived. Among P2,P4, and P5 the shortest burst time is 1sec for P2, so P2 will execute next. Then P4 and P5. At last P1 will be executed.

Gantt chart for this ques will be:

| P3 | P2 | P4 | P5 | P1 |

1    4    5    7   11   14

Average waiting time=(0+2+2+3+3)/5=2

Average Turnaround time=(3+3+4+7+6)/5=4.6

Cloning an Object in Node.js

There is also a project on Github that aims to be a more direct port of the jQuery.extend():

An example, modified from the jQuery docs:

var extend = require('node.extend');

var object1 = {
    apple: 0,
    banana: {
        weight: 52,
        price: 100
    cherry: 97

var object2 = {
    banana: {
        price: 200
    durian: 100

var merged = extend(object1, object2);

Doctrine 2: Update query with query builder

Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.

An update could be executed this way …

class UserRepository extends \Doctrine\ORM\EntityRepository
    public function updateUserStatus($userId, $newStatus)
        return $this->createQueryBuilder('u')
            ->set('u.isActive', '?1')
            ->setParameter(1, $qb->expr()->literal($newStatus))
            ->where(' = ?2')
            ->setParameter(2, $qb->expr()->literal($userId))

AJAX action handling:

# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
        ->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
    # Row updated

Working example using Doctrine 2.5 (on top of Symfony3).

jQuery iframe load() event?

If you want it to be more generic and independent, you can use cookie. Iframe content can set a cookie. With jquery.cookie and a timer (or in this case javascript timer), you can check if the cookie is set each second or so.

//token should be a unique random value which is also sent to ifame to get set
iframeLoadCheckTimer = window.setInterval(function () {
        cookieValue = $.cookie('iframeToken');  
        if (cookieValue == token)
            window.clearInterval(iframeLoadCheckTimer );
            $.cookie('iframeToken', null, {
                expires: 1, 
                path: '/'
 }, 1000);

How to enable mbstring from php.ini?

All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.

If you have accidentally removed DLL file from php/ext folder, just add it back (get the copy from XAMPP zip archive - its downloadable).

If you have deleted the accompanying INI configuration line from php.ini file, add it back as well:


Also, ensure to restart your webserver (Apache) using XAMPP control panel.

Additional Info on Enabling PHP Extensions

  • install extension (e.g. put php_mbstring.dll into /XAMPP/php/ext directory)
  • in php.ini, ensure extension directory specified (e.g. extension_dir = "ext")
  • ensure correct build of DLL file (e.g. 32bit thread-safe VC9 only works with DLL files built using exact same tools and configuration: 32bit thread-safe VC9)
  • ensure PHP API versions match (If not, once you restart the webserver you will receive related error.)

how to get GET and POST variables with JQuery?

My approach:

var urlParams;
(window.onpopstate = function () {
var match,
      pl     = /\+/g,  Regex for replacing addition symbol with a space
       search = /([^&=]+)=?([^&]*)/g,
      decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
       query  =;
   urlParams = {};
   while (match = search.exec(query))
    urlParams[decode(match[1])] = decode(match[2]);

Node.js Write a line into a .txt file

Inserting data into the middle of a text file is not a simple task. If possible, you should append it to the end of your file.

The easiest way to append data some text file is to use build-in fs.appendFile(filename, data[, options], callback) function from fs module:

var fs = require('fs')
fs.appendFile('log.txt', 'new data', function (err) {
  if (err) {
    // append failed
  } else {
    // done

But if you want to write data to log file several times, then it'll be best to use fs.createWriteStream(path[, options]) function instead:

var fs = require('fs')
var logger = fs.createWriteStream('log.txt', {
  flags: 'a' // 'a' means appending (old data will be preserved)

logger.write('some data') // append string to your file
logger.write('more data') // again
logger.write('and more') // again

Node will keep appending new data to your file every time you'll call .write, until your application will be closed, or until you'll manually close the stream calling .end:

logger.end() // close string

Is there a C# case insensitive equals operator?

There are a number of properties on the StringComparer static class that return comparers for any type of case-sensitivity you might want:

StringComparer Properties

For instance, you can call

StringComparer.CurrentCultureIgnoreCase.Equals(string1, string2)


StringComparer.CurrentCultureIgnoreCase.Compare(string1, string2)

It's a bit cleaner than the string.Equals or string.Compare overloads that take a StringComparison argument.

Where in memory are my variables stored in C?

  • Variables/automatic variables ---> stack section
  • Dynamically allocated variables ---> heap section
  • Initialised global variables -> data section
  • Uninitialised global variables -> data section (bss)
  • Static variables -> data section
  • String constants -> text section/code section
  • Functions -> text section/code section
  • Text code -> text section/code section
  • Registers -> CPU registers
  • Command line inputs -> environmental/command line section
  • Environmental variables -> environmental/command line section

Getting attributes of Enum's value

    public enum DataFilters
        [Display(Name= "Equals")]
        Equals = 1,// Display Name and Enum Name are same 
        [Display(Name= "Does Not Equal")]
        DoesNotEqual = 2, // Display Name and Enum Name are different             

Now it will produce error in this case 1 "Equals"

public static string GetDisplayName(this Enum enumValue)
        var enumMember = enumValue.GetType().GetMember(enumValue.ToString()).First();
        return enumMember.GetCustomAttribute<DisplayAttribute>() != null ? enumMember.GetCustomAttribute<DisplayAttribute>().Name : enumMember.Name;

so if it is same return enum name rather than display name because enumMember.GetCustomAttribute() gets null if displayname and enum name are same.....

Return a `struct` from a function in C

The struct b line doesn't work because it's a syntax error. If you expand it out to include the type it will work just fine

struct MyObj b = a;  // Runs fine

What C is doing here is essentially a memcpy from the source struct to the destination. This is true for both assignment and return of struct values (and really every other value in C)

How to select the Date Picker In Selenium WebDriver

DatePicker are not Select element. What your doing in your code is wrong.

Datepicker are in fact table with set of rows and columns.To select a date you just have to navigate to the cell where our desired date is present.

So your code should be like this:

WebElement dateWidget = driver.findElement(your locator);
List<WebElement> columns=dateWidget.findElements(By.tagName("td"));

for (WebElement cell: columns){
   //Select 13th Date 
   if (cell.getText().equals("13")){

Check existence of input argument in a Bash shell script

one liner bash function validation

myFunction() {

    : ${1?"forgot to supply an argument"}
    if [ "$1" -gt "-1" ]; then
        echo hi


add function name and usage

myFunction() {

    : ${1?"forgot to supply an argument ${FUNCNAME[0]}() Usage:  ${FUNCNAME[0]} some_integer"}
    if [ "$1" -gt "-1" ]; then
        echo hi


add validation to check if integer

to add additional validation, for example to check to see if the argument passed is an integer, modify the validation one liner to call a validation function:

: ${1?"forgot to supply an argument ${FUNCNAME[0]}() Usage:  ${FUNCNAME[0]} some_integer"} && validateIntegers $1 || die "Must supply an integer!"

then, construct a validation function that validates the argument, returning 0 on success, 1 on failure and a die function that aborts script on failure

validateIntegers() {

    if ! [[ "$1" =~ ^[0-9]+$ ]]; then
        return 1 # failure
    return 0 #success


die() { echo "$*" 1>&2 ; exit 1; }

Even simpler - just use set -u

set -u makes sure that every referenced variable is set when its used, so just set it and forget it

myFunction() {
    set -u
    if [ "$1" -gt "-1" ]; then
        echo hi


Uninstall Django completely

The Issue is with pip --version or python --version.

try solving issue with pip2.7 uninstall Django command

If you are not able to uninstall using the above command then for sure your pip2.7 version is not installed so you can follow the below steps:

1)which pip2.7 it should give you an output like this :


2) If you have not got this output please install pip using following commands

$ wget
$ sudo python2.7

3) Now check your pip version : which pip2.7 Now you will get

/usr/local/bin/pip2.7 as output 

4) uninstall Django using pip2.7 uninstall Django command.

Problem can also be related to Python version. I had a similar problem, this is how I uninstalled Django.

Issue occurred because I had multiple python installed in my virtual environment.

$ ls

activate  easy_install-3.4  pip2.7  python     python3        wheel
activate.csh   easy_install      pip               pip3    python2    python3.4  easy_install-2.7  pip2              pip3.4  python2.7  python-config

Now when I tried to un-install using pip uninstall Django Django got uninstalled from python 2.7 but not from python 3.4 so I followed the following steps to resolve the issue :

1)alias python=/usr/bin/python3

2) Now check your python version using python -V command

3) If you have switched to your required python version now you can simply uninstall Django using pip3 uninstall Django command

Hope this answer helps.