Programs & Examples On #Admin interface

Should I use typescript? or I can just use ES6?

Decision tree between ES5, ES6 and TypeScript

Do you mind having a build step?

  • Yes - Use ES5
  • No - keep going

Do you want to use types?

  • Yes - Use TypeScript
  • No - Use ES6

More Details

ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers

ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.

TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.

Javascript Get Element by Id and set the value

function updateTextarea(element)
document.getElementById(element).innerText = document.getElementById("ment").value;

<input type="text" value="Enter your text here." id = "ment" style = " border: 1px solid grey; margin-bottom: 4px;"  

onKeyUp="updateTextarea('myDiv')" />


<textarea id="myDiv" ></textarea>


How to have multiple conditions for one if statement in python

I would use

def example(arg1, arg2, arg3):
     if arg1 == 1 and arg2 == 2 and arg3 == 3:
          print("Example Text")

The and operator is identical to the logic gate with the same name; it will return 1 if and only if all of the inputs are 1. You can also use or operator if you want that logic gate.

EDIT: Actually, the code provided in your post works fine with me. I don't see any problems with that. I think that this might be a problem with your Python, not the actual language.

Send Message in C#

public static extern int FindWindow(string lpClassName, String lpWindowName);

In order to find the window, you need the class name of the window. Here are some examples:


const string lpClassName = "Winamp v1.x";
IntPtr hwnd = FindWindow(lpClassName, null);

Example from a program that I made, written in VB:

hParent = FindWindow("TfrmMain", vbNullString)

In order to get the class name of a window, you'll need something called Win Spy

Once you have the handle of the window, you can send messages to it using the SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam) function.

hWnd, here, is the result of the FindWindow function. In the above examples, this will be hwnd and hParent. It tells the SendMessage function which window to send the message to.

The second parameter, wMsg, is a constant that signifies the TYPE of message that you are sending. The message might be a keystroke (e.g. send "the enter key" or "the space bar" to a window), but it might also be a command to close the window (WM_CLOSE), a command to alter the window (hide it, show it, minimize it, alter its title, etc.), a request for information within the window (getting the title, getting text within a text box, etc.), and so on. Some common examples include the following:

Public Const WM_CHAR = &H102
Public Const WM_SETTEXT = &HC
Public Const WM_KEYDOWN = &H100
Public Const WM_KEYUP = &H101
Public Const WM_LBUTTONDOWN = &H201
Public Const WM_LBUTTONUP = &H202
Public Const WM_CLOSE = &H10
Public Const WM_COMMAND = &H111
Public Const WM_CLEAR = &H303
Public Const WM_DESTROY = &H2
Public Const WM_GETTEXT = &HD
Public Const WM_LBUTTONDBLCLK = &H203

These can be found with an API viewer (or a simple text editor, such as notepad) by opening (Microsoft Visual Studio Directory)/Common/Tools/WINAPI/winapi32.txt.

The next two parameters are certain details, if they are necessary. In terms of pressing certain keys, they will specify exactly which specific key is to be pressed.

C# example, setting the text of windowHandle with WM_SETTEXT:

x = SendMessage(windowHandle, WM_SETTEXT, new IntPtr(0), m_strURL);

More examples from a program that I made, written in VB, setting a program's icon (ICON_BIG is a constant which can be found in winapi32.txt):

Call SendMessage(hParent, WM_SETICON, ICON_BIG, ByVal hIcon)

Another example from VB, pressing the space key (VK_SPACE is a constant which can be found in winapi32.txt):

Call SendMessage(button%, WM_KEYDOWN, VK_SPACE, 0)
Call SendMessage(button%, WM_KEYUP, VK_SPACE, 0)

VB sending a button click (a left button down, and then up):

Call SendMessage(button%, WM_LBUTTONDOWN, 0, 0&)
Call SendMessage(button%, WM_LBUTTONUP, 0, 0&)

No idea how to set up the listener within a .DLL, but these examples should help in understanding how to send the message.

Fragment pressing back button

if you are using webview inside a fragment than use this in your onCreateView method

webView.setOnKeyListener(new View.OnKeyListener(){

        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if((i==KeyEvent.KEYCODE_BACK)&& webView.canGoBack()){
                return true;
            return false;

and import this class

import android.view.KeyEvent;

Is it possible to run one logrotate check manually?

logrotate -d [your_config_file] invokes debug mode, giving you a verbose description of what would happen, but leaving the log files untouched.

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

How to write log to file

I prefer the simplicity and flexibility of the 12 factor app recommendation for logging. To append to a log file you can use shell redirection. The default logger in Go writes to stderr (2).

./app 2>> logfile

See also:

How do I concatenate two lists in Python?




 >>> [1, 2, 3, 4, 5, 6]

In the above code "+" operator is used to concatenate the 2 lists into a single list.


 c=[] #Empty list in which we are going to append the values of list (a) and (b)

 for i in a:
 for j in b:



>>> [1, 2, 3, 4, 5, 6]

Change the value in app.config file dynamically

 XmlReaderSettings _configsettings = new XmlReaderSettings();
 _configsettings.IgnoreComments = true;

 XmlReader _configreader = XmlReader.Create(ConfigFilePath, _configsettings);
 XmlDocument doc_config = new XmlDocument();

 foreach (XmlNode RootName in doc_config.DocumentElement.ChildNodes)
     if (RootName.LocalName == "appSettings")
         if (RootName.HasChildNodes)
             foreach (XmlNode _child in RootName.ChildNodes)
                 if (_child.Attributes["key"].Value == "HostName")
                     if (_child.Attributes["value"].Value == "false")
                         _child.Attributes["value"].Value = "true";

Getting current directory in VBScript

You can use CurrentDirectory property.

Dim WshShell, strCurDir
Set WshShell = CreateObject("WScript.Shell")
strCurDir    = WshShell.CurrentDirectory
WshShell.Run strCurDir & "\attribute.exe", 0
Set WshShell = Nothing

Java: How to stop thread?

One possible way is to do something like this:

public class MyThread extends Thread {
    public void run() {
        while (!this.isInterrupted()) {

And when you want to stop your thread, just call a method interrupt():


Of course, this won't stop thread immediately, but in the following iteration of the loop above. In the case of downloading, you need to write a non-blocking code. It means, that you will attempt to read new data from the socket only for a limited amount of time. If there are no data available, it will just continue. It may be done using this method from the class Socket:


In this case, timeout is set up to 50 ms. After this time has gone and no data was read, it throws an SocketTimeoutException. This way, you may write iterative and non-blocking thread, which may be killed using the construction above.

It's not possible to kill thread in any other way and you've to implement such a behavior yourself. In past, Thread had some method (not sure if kill() or stop()) for this, but it's deprecated now. My experience is, that some implementations of JVM doesn't even contain that method currently.

How to refer to relative paths of resources when working with a code repository

If you are using setup tools or distribute (a install) then the "right" way to access these packaged resources seem to be using package_resources.

In your case the example would be

import pkg_resources
my_data = pkg_resources.resource_string(__name__, "foo.dat")

Which of course reads the resource and the read binary data would be the value of my_data

If you just need the filename you could also use

resource_filename(package_or_requirement, resource_name)



The advantage is that its guaranteed to work even if it is an archive distribution like an egg.


Printing 1 to 1000 without loop or conditionals

Function pointer (ab)use. No preprocessor magic to increase output. ANSI C.

#include <stdio.h>

int i=1;

void x10( void (*f)() ){
    f(); f(); f(); f(); f();
    f(); f(); f(); f(); f();

void I(){printf("%i ", i++);}
void D(){ x10( I ); }
void C(){ x10( D ); }
void M(){ x10( C ); }

int main(){

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

How to SELECT by MAX(date)?

Did this on a blog engine to get the latest blog. I adapted it to your table structure.

SELECT * FROM reports WHERE date_entered = (SELECT max(date_entered) FROM REPORTS)

Best way to create enum of strings?

Either set the enum name to be the same as the string you want or, more generally,you can associate arbitrary attributes with your enum values:

enum Strings {
   private final String stringValue;
   Strings(final String s) { stringValue = s; }
   public String toString() { return stringValue; }
   // further methods, attributes, etc.

It's important to have the constants at the top, and the methods/attributes at the bottom.

PHP-FPM doesn't write to error log

Check the Owner directory of "PHP-FPM"

You can do:

ls -lah /var/log/php-fpm/
chown -R webusr:webusr /var/log/php-fpm/
chmod -R 777 /var/log/php-fpm/

SHA1 vs md5 vs SHA256: which to use for a PHP login?

Everyone is talking about this like they can be hacked over the internet. As already stated, limiting attempts makes it impossible to crack a password over the Internet and has nothing to do with the hash.

The salt is a must, but the complexity or multiple salts doesn't even matter. Any salt alone stops the attacker from using a premade rainbow table. A unique salt per user stops the attacker from creating a new rainbow table to use against your entire user base.

The security really comes into play when the entire database is compromised and a hacker can then perform 100 million password attempts per second against the md5 hash. SHA512 is about 10,000 times slower. A complex password with today's power could still take 100 years to bruteforce with md5 and would take 10,000 times as long with SHA512. The salts don't stop a bruteforce at all as they always have to be known, which if the attacker downloaded your database, he probably was in your system anyway.

How do I enable MSDTC on SQL Server?

MSDTC must be enabled on both systems, both server and client.
Also, make sure that there isn't a firewall between the systems that blocks RPC.
DTCTest is a nice litt app that helps you to troubleshoot any other problems.

How to remove Left property when position: absolute?

left: initial

This will also set left back to the browser default.

But important to know property: initial is not supported in IE.

What is the Linux equivalent to DOS pause?

This function works in both bash and zsh, and ensures I/O to the terminal:

# Prompt for a keypress to continue. Customise prompt with $*
function pause {
  >/dev/tty printf '%s' "${*:-Press any key to continue... }"
  [[ $ZSH_VERSION ]] && read -krs  # Use -u0 to read from STDIN
  [[ $BASH_VERSION ]] && </dev/tty read -rsn1
  printf '\n'
export_function pause

Put it in your .{ba,z}shrc for Great Justice!

How do you use MySQL's source command to import large files in windows

Option 1. you can do this using single cmd where D is my xampp or wampp install folder so i use this where mysql.exe install and second option database name and last is sql file so replace it as your then run this

D:\xampp\mysql\bin\mysql.exe -u root -p databse_name < D:\yoursqlfile.sql

Option 1 for wampp

D:\wamp64\bin\mysql\mysql5.7.14\bin\mysql.exe -u root -p databse_name< D:\yoursqlfile.sql

change your folder and mysql version

Option 2 Suppose your current path is which is showing command prompt


then change directory using cd.. then goto your mysql directory where your xampp installed. Then cd.. for change directory. then go to bin folder.


C:\xampp\mysql\bin\mysql -u {username} -p {database password}.then please enter when you see enter password in command prompt.

choose database using

mysql->use test (where database name test) 

then put in source sql in bin folder.

then last command will be

mysql-> source test.sql (where test.sql is file name which need to import)

then press enter

This is full command

C:\xampp\mysql\bin\mysql -u {username} -p {database password}
 mysql-> use test
 mysql->source test.sql

Checking out Git tag leads to "detached HEAD state"

Okay, first a few terms slightly oversimplified.

In git, a tag (like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.

Now a branch is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.

Your HEAD is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD will point to master which in turn will point to a commit. When you then do something like git checkout experimental, you switch the HEAD to point to the experimental branch which might point to a different commit.

Now the explanation.

When you do a git checkout v2.0, you are switching to a commit that is not pointed to by a branch. The HEAD is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.

Usually, what you can do is to say git checkout -b v2.0-fixes v2.0. This will create a new branch pointer at the commit pointed to by the treeish v2.0 (a tag in this case) and then shift your HEAD to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0 code. If however, you want to make any alterations there which you want to track, you'll need a branch.

You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.

What is the best way to dump entire objects to a log in C#?

What I like doing is overriding ToString() so that I get more useful output beyond the type name. This is handy in the debugger, you can see the information you want about an object without needing to expand it.

How to set space between listView Items in Android

Maybe you can try to add android:layout_marginTop = "15dp" and android:layout_marginBottom = "15dp" in the outermost Layout

No numeric types to aggregate - change in groupby() behaviour?

I got this error generating a data frame consisting of timestamps and data:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))

Adding the suggested solution works for me:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))

Thanks Chang She!


2005-01-01 00:10:00  7.53
2005-01-01 00:20:00  7.54
2005-01-01 00:30:00  7.62
2005-01-01 00:40:00  7.68
2005-01-01 00:50:00  7.81
2005-01-01 01:00:00  7.95
2005-01-01 01:10:00  7.96
2005-01-01 01:20:00  7.95
2005-01-01 01:30:00  7.98
2005-01-01 01:40:00  8.06
2005-01-01 01:50:00  8.04
2005-01-01 02:00:00  8.06
2005-01-01 02:10:00  8.12
2005-01-01 02:20:00  8.12
2005-01-01 02:30:00  8.25
2005-01-01 02:40:00  8.27
2005-01-01 02:50:00  8.17
2005-01-01 03:00:00  8.21
2005-01-01 03:10:00  8.29
2005-01-01 03:20:00  8.31
2005-01-01 03:30:00  8.25
2005-01-01 03:40:00  8.19
2005-01-01 03:50:00  8.17
2005-01-01 04:00:00  8.18
2005-01-01 00:00:00  7.636000
2005-01-01 01:00:00  7.990000
2005-01-01 02:00:00  8.165000
2005-01-01 03:00:00  8.236667
2005-01-01 04:00:00  8.180000

Getting a map() to return a list in Python 3.x

You can try getting a list from the map object by just iterating each item in the object and store it in a different variable.

a = map(chr, [66, 53, 0, 94])
b = [item for item in a]
>>>['B', '5', '\x00', '^']

How to set bot's status

    client.user.setStatus('dnd', 'Made by KwinkyWolf') 

And change 'dnd' to whatever status you want it to have. And then the next field 'Made by KwinkyWolf' is where you change the game. Hope this helped :)

List of status':

  • online
  • idle
  • dnd
  • invisible

Not sure if they're still the same, or if there's more but hope that helped too :)

Error: macro names must be identifiers using #ifdef 0

The #ifdef directive is used to check if a preprocessor symbol is defined. The standard (C11 6.4.2 Identifiers) mandates that identifiers must not start with a digit:

    identifier identifier-nondigit
    identifier digit
    other implementation-defined characters>
nondigit: one of
    _ a b c d e f g h i j k l m
    n o p q r s t u v w x y z
    A B C D E F G H I J K L M
    N O P Q R S T U V W X Y Z
digit: one of
    0 1 2 3 4 5 6 7 8 9

The correct form for using the pre-processor to block out code is:

#if 0
: : :

You can also use:

: : :

but you need to be confident that the symbols will not be inadvertently set by code other than your own. In other words, don't use something like NOTUSED or DONOTCOMPILE which others may also use. To be safe, the #if option should be preferred.

Adding quotes to a string in VBScript

The traditional way to specify quotes is to use Chr(34). This is error resistant and is not an abomination.

Chr(34) & "string" & Chr(34)

How do I update Node.js?

I used the following instructions to upgrade from Node.js version 0.10.6 to 0.10.21 on a Mac.

  1. Clear NPM's cache:

    sudo npm cache clean -f
  2. Install a little helper called 'n'

    sudo npm install -g n
  3. Install latest stable Node.js version

    sudo n stable

Alternatively pick a specific version and install like this:

sudo n 0.8.20

For production environments you might want to pay attention to version numbering and be picky about odd/even numbers.


Update (June 2017):

This four years old post still receives up-votes so I'm guessing it still works for many people. However, Mr. Walsh himself recommended to update Node.js just using nvm instead.

So here's what you might want to do today:

Find out which version of Node.js you are using:

node --version

Find out which versions of Node.js you may have installed and which one of those you're currently using:

nvm ls

List all versions of Node.js available for installation:

nvm ls-remote

Apparently for Windows the command would be rather like this:

nvm ls available

Assuming you would pick Node.js v8.1.0 for installation you'd type the following to install that version:

nvm install 8.1.0

You are then free to choose between installed versions of Node.js. So if you would need to use an older version like v4.2.0 you would set it as the active version like this:

nvm use 4.2

How do I get the Session Object in Spring?

ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();

Where do I configure log4j in a JUnit test class?

I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway)

Convert an array to string

You can join your array using the following:

string.Join(",", Client);

Then you can output anyway you want. You can change the comma to what ever you want, a space, a pipe, or whatever.

Declare a Range relative to the Active Cell with VBA

Like this:

Dim rng as Range
Set rng = ActiveCell.Resize(numRows, numCols)

then read the contents of that range to an array:

Dim arr As Variant
arr = rng.Value
'arr is now a two-dimensional array of size (numRows, numCols)

or, select the range (I don't think that's what you really want, but you ask for this in the question).


How to initialize const member variable in a class?

If a member is a Array it will be a little bit complex than the normal is:

class C
    static const int ARRAY[10];
    C() {}
const unsigned int C::ARRAY[10] = {0,1,2,3,4,5,6,7,8,9};


int* a = new int[N];
// fill a

class C {
  const std::vector<int> v;
  C():v(a, a+N) {}

convert UIImage to NSData

- (void) imageConvert
     UIImage *snapshot = self.myImageView.image;
     [self encodeImageToBase64String:snapshot];

call this method for image convert in base 64 
    -(NSString *)encodeImageToBase64String:(UIImage *)image
        return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

How to set delay in android?

If you use delay frequently in your app, use this utility class

import android.os.Handler;

public class Utils {

    // Delay mechanism

    public interface DelayCallback{
        void afterDelay();

    public static void delay(int secs, final DelayCallback delayCallback){
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
        }, secs * 1000); // afterDelay will be executed after (secs*1000) milliseconds.


// Call this method directly from java file

int secs = 2; // Delay in seconds

Utils.delay(secs, new Utils.DelayCallback() {
    public void afterDelay() {
        // Do something after delay


How to change the background color of Action Bar's Option Menu in Android 4.2?

I was able to change colour of action overflow by just putting hex value at:

    <!-- The beef: background color for Action Bar overflow menu -->
<style name="MyApp.PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
    <item name="android:popupBackground">HEX VALUE OF COLOR</item>

Objects inside objects in javascript

You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:

{el1, el2, {el31, el32, el33}, {el41, el42}}

var MainObj = {_x000D_
  prop1: "prop1MainObj",_x000D_
  Obj1: {_x000D_
    prop1: "prop1Obj1",_x000D_
    prop2: "prop2Obj1",    _x000D_
    Obj2: {_x000D_
      prop1: "hey you",_x000D_
      prop2: "prop2Obj2"_x000D_
  Obj3: {_x000D_
    prop1: "prop1Obj3",_x000D_
    prop2: "prop2Obj3"_x000D_
  Obj4: {_x000D_
    prop1: true,_x000D_
    prop2: 3_x000D_
  }  _x000D_

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

This isn't on the code parter it's on the server side Contact your Server Manager or fix it from server if you own it If you use CPANEL/WHM GO TO WHM/SMTP RESTRICTIONS AND DISABLE IT

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You need to open the file in binary mode i.e. wb instead of w. If you don't, the end of line characters are auto-converted to OS specific ones.

Here is an excerpt from Python reference about open().

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST.

That is: Modern browsers will only allow Ajax calls to services in the same domain as the HTML page.

Example: A page in can only directly request services that are in, like If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a CORS request, your browser:

  • Will first send an OPTION request to the target URL
  • And then only if the server response to that OPTION contains the adequate headers (Access-Control-Allow-Origin is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).

How to solve it? The simplest way is to enable CORS (enable the necessary headers) on the server.

If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.

How to get text in QlineEdit when QpushButton is pressed in a string?

The object name is not very important. what you should be focusing at is the variable that stores the lineedit object (le) and your pushbutton object(pb)

QObject(self.pb, SIGNAL("clicked()"), self.button_clicked)

def button_clicked(self):

I think this is what you want. I hope i got your question correctly :)

How to get host name with port from a http or https request

I'm late to the party, but I had this same issue working with Java 8.

This is what worked for me, on the HttpServletRequest request object.




How I came to that conclusion:

I have a java app running on http://localhost:3000 making a Http Post to another java app I have running on http://localhost:8080.

From the Java code running on http://localhost:8080 I couldn't get the http://localhost:3000 from the HttpServletRequest using the answers above. For me using the getHeader method with the correct string input worked.

request.getHeader("origin") gave me "http://localhost:3000" which is what I wanted.

request.getHeader("referer") gave me "http://localhost:3000/xxxx" where xxxx is full URL I have from the requesting app.

Cannot open local file - Chrome: Not allowed to load local resource

1) Open your terminal and type

npm install -g http-server

2) Go to the root folder that you want to serve you files and type:

http-server ./

3) Read the output of the terminal, something kinda http://localhost:8080 will appear.

Everything on there will be allowed to be got. Example:

background: url('http://localhost:8080/waw.png');

stdcall and cdecl

Those things are Compiler- and Platform-specific. Neither the C nor the C++ standard say anything about calling conventions except for extern "C" in C++.

how does a caller know if it should free up the stack ?

The caller knows the calling convention of the function and handles the call accordingly.

At the call site, does the caller know if the function being called is a cdecl or a stdcall function ?


How does it work ?

It is part of the function declaration.

How does the caller know if it should free up the stack or not ?

The caller knows the calling conventions and can act accordingly.

Or is it the linkers responsibility ?

No, the calling convention is part of a function's declaration so the compiler knows everything it needs to know.

If a function which is declared as stdcall calls a function(which has a calling convention as cdecl), or the other way round, would this be inappropriate ?

No. Why should it?

In general, can we say that which call will be faster - cdecl or stdcall ?

I don't know. Test it.

HttpClient does not exist in .net 4.0: what can I do?

Agreeing with TrueWill's comment on a separate answer, the best way I've seen to use system.web.http on a .NET 4 targeted project under current Visual Studio is Install-Package Microsoft.AspNet.WebApi.Client -Version 4.0.30506

Difference between res.send and res.json in Express.js

Looking in the headers sent...
res.send uses content-type:text/html
res.json uses content-type:application/json

edit: send actually changes what is sent based on what it's given, so strings are sent as text/html, but it you pass it an object it emits application/json.

Automatically enter SSH password with script

I managed to get it working with that:

SSH_ASKPASS="echo \"my-pass-here\""
ssh -tt remotehost -l myusername

Hook up Raspberry Pi via Ethernet to laptop without router?

I've just implemented and test this successfully. Same situation with my project, want to connect to a Raspberry Pi with no router or wifi. Just a simple ethernet cable.

Using ssh putty program put the address as


Log and in and you can access the terminal.

Alternatively if VNC server is setup, use VNC server and put


In the server address. input your VNC server password and you've now got GUI access to do what you want.

In may case it was run scripts in a remote location. In the posters situation, safely shutdown the Pi. Simples Pimples.

How to set a transparent background of JPanel?

In my particular case it was easier to do this:

 panel.setBackground(new Color(0,0,0,0,)): // any color with alpha 0 (in this case the color is black

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

¦   Property    ¦     HashMap       ¦    Hashtable      ¦  ConcurrentHashMap  ¦
¦      Null     ¦     allowed       ¦              not allowed                ¦
¦  values/keys  ¦                   ¦                                         ¦
¦ Thread-safety ¦                   ¦                                         ¦
¦   features    ¦       no          ¦                  yes                    ¦
¦     Lock      ¦       not         ¦ locks the whole   ¦ locks the portion   ¦        
¦  mechanism    ¦    applicable     ¦       map         ¦                     ¦ 
¦   Iterator    ¦               fail-fast               ¦ weakly consistent   ¦ 

Regarding locking mechanism: Hashtable locks the object, while ConcurrentHashMap locks only the bucket.

opening html from google drive

  1. Create a new folder in Drive and share it as "Public on the web."
  2. Upload your content files to this folder.
  3. Right click on your folder and click on Details.
  4. Copy Hosting URL and paste it on your browser.(e.g.
  5. It will launch index.html if it exist in your folder other wise list all files in your folder.

Jquery Date picker Default Date

$( ".selector" ).datepicker({ defaultDate: null });

and return empty string from backend

Convert objective-c typedef to its string equivalent

@pixel added the most brilliant answer here: Please, upvote him!

He uses the neat X macro from the 1960's. (I've changed his code a bit for the modern ObjC)

#define X(a, b, c) a b,
enum ZZObjectType {
typedef NSUInteger TPObjectType;
#undef X

X(ZZObjectTypeZero, = 0, @"ZZObjectTypeZero") \
X(ZZObjectTypeOne, , @"ZZObjectTypeOne") \
X(ZZObjectTypeTwo, , @"ZZObjectTypeTwo") \
X(ZZObjectTypeThree, , @"ZZObjectTypeThree")

+ (NSString*)nameForObjectType:(ZZObjectType)objectType {
#define X(a, b, c) @(a):c, 
    NSDictionary *dict = @{XXOBJECTTYPE_TABLE};
#undef X
    return dict[objectType];

That's it. Clean and neat. Thanks to @pixel!

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

Try this, It worked for me

                ROW_NUMBER() OVER(PARTITION BY [Code],[Name],[CategoryCode] ORDER BY ID DESC) rownumber
            FROM MasterTable
          ) a
        WHERE rownumber = 1 

Session 'app' error while installing APK

I was facing same problem.Tried every think mentioned here in blog.

But it was basic error to permit device "allow installing app from USB" which did it for me.

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

Or you could do this from NuGet Package Manager Console

 Install-Package Microsoft.AspNet.WebApi -Version 5.0.0

And then you will be able to add the reference to System.Web.Http.WebHost 5.0

select certain columns of a data table

First store the table in a view, then select columns from that view into a new table.

// Create a table with abitrary columns for use with the example
System.Data.DataTable table = new System.Data.DataTable();
for (int i = 1; i <= 11; i++)
    table.Columns.Add("col" + i.ToString());

// Load the table with contrived data
for (int i = 0; i < 100; i++)
    System.Data.DataRow row = table.NewRow();
    for (int j = 0; j < 11; j++)
        row[j] = i.ToString() + ", " + j.ToString();

// Create the DataView of the DataTable
System.Data.DataView view = new System.Data.DataView(table);
// Create a new DataTable from the DataView with just the columns desired - and in the order desired
System.Data.DataTable selected = view.ToTable("Selected", false, "col1", "col2", "col6", "col7", "col3");

Used the sample data to test this method I found: Create ADO.NET DataView showing only selected Columns

Child with max-height: 100% overflows parent

The closest I can get to this is this example:


.container {  
  background: blue; 
  border: 10px solid blue; 
  max-height: 200px; 
  max-width: 200px; 

img { 
  display: block;
  max-height: 100%; 
  max-width: 100%; 

The main problem is that the height takes the percentage of the containers height, so it is looking for an explicitly set height in the parent container, not it's max-height.

The only way round this to some extent I can see is the fiddle above where you can hide the overflow, but then the padding still acts as visible space for the image to flow into, and so replacing with a solid border works instead (and then adding border-box to make it 200px if that's the width you need)

Not sure if this would fit with what you need it for, but the best I can seem to get to.

Order a List (C#) by many fields?

Your object should implement the IComparable interface.

With it your class becomes a new function called CompareTo(T other). Within this function you can make any comparison between the current and the other object and return an integer value about if the first is greater, smaller or equal to the second one.

How do I include a file over 2 directories back?

.. selects the parent directory from the current. Of course, this can be chained:


This would be two directories up.

Switching from zsh to bash on OSX, and back again?

You can just use exec to replace your current shell with a new shell:

Switch to bash:

exec bash

Switch to zsh:

exec zsh

This won't affect new terminal windows or anything, but it's convenient.

How to clear jQuery validation error messages?

If you didn't previously save the validators apart when attaching them to the form you can also just simply invoke


as .validate() will return the same validators you attached previously (if you did so).

Serializing an object to JSON

Download, include it and do

var json_data = JSON.stringify(obj);

How to deal with missing src/test/java source folder in Android/Maven project?

I realise this annoying thing too since latest m2e-android plugin upgrade (version 0.4.2), it happens in both new project creation and existing project import (if you don't use src/test/java).

It looks like m2e-android (or perhaps m2e) now always trying to add src/test/java as a source folder, regardless of whether it is actually existed in your project directory, in the .classpath file:

<classpathentry kind="src" output="bin/classes" path="src/test/java">
    <attribute name="maven.pomderived" value="true"/>

As it is already added in the project metadata file, so if you trying to add the source folder via Eclipse, Eclipse will complain that the classpathentry is already exist:

enter image description here

There are several ways to fix it, the easiest is manually create src/test/java directory in the file system, then refresh your project by press F5 and run Maven -> Update Project (Right click project, choose Maven -> Update Project...), this should fix the missing required source folder: 'src/test/java' error.

How to make return key on iPhone make keyboard disappear?

After quite a bit of time hunting down something that makes sense, this is what I put together and it worked like a charm.


//  ViewController.h
//  demoKeyboardScrolling
//  Created by Chris Cantley on 11/14/13.
//  Copyright (c) 2013 Chris Cantley. All rights reserved.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>

// Connect your text field to this the below property.
@property (weak, nonatomic) IBOutlet UITextField *theTextField;



//  ViewController.m
//  demoKeyboardScrolling
//  Created by Chris Cantley on 11/14/13.
//  Copyright (c) 2013 Chris Cantley. All rights reserved.

#import "ViewController.h"

@interface ViewController ()


@implementation ViewController

- (void)viewDidLoad
    [super viewDidLoad];
    // _theTextField is the name of the parameter designated in the .h file. 
    _theTextField.returnKeyType = UIReturnKeyDone;
    [_theTextField setDelegate:self];


// This part is more dynamic as it closes the keyboard regardless of what text field 
// is being used when pressing return.  
// You might want to control every single text field separately but that isn't 
// what this code do.
-(void)textFieldShouldReturn:(UITextField *)textField
    [textField resignFirstResponder];


Hope this helps!

How to install mysql-connector via pip

pip install mysql-connector

Last but not least,You can also install mysql-connector via source code

Download source code from:

How do I give text or an image a transparent background using CSS?

A while back, I wrote about this in Cross Browser Background Transparency With CSS.

Bizarrely Internet Explorer 6 will allow you to make the background transparent and keep the text on top fully opaque. For the other browsers I then suggest using a transparent PNG file.

AngularJS - Create a directive that uses ng-model

I took a combo of all answers, and now have two ways of doing this with the ng-model attribute:

  • With a new scope which copies ngModel
  • With the same scope which does a compile on link

var app = angular.module('model', []);_x000D_
app.controller('MainCtrl', function($scope) {_x000D_
  $ = "Felipe";_x000D_
  $scope.label = "The Label";_x000D_
app.directive('myDirectiveWithScope', function() {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: {_x000D_
      ngModel: '=',_x000D_
    // Notice how label isn't copied_x000D_
    template: '<div class="some"><label>{{label}}: <input ng-model="ngModel"></label></div>',_x000D_
    replace: true_x000D_
app.directive('myDirectiveWithChildScope', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: true,_x000D_
    // Notice how label is visible in the scope_x000D_
    template: '<div class="some"><label>{{label}}: <input></label></div>',_x000D_
    replace: true,_x000D_
    link: function ($scope, element) {_x000D_
      // element will be the div which gets the ng-model on the original directive_x000D_
      var model = element.attr('ng-model');_x000D_
      $('input',element).attr('ng-model', model);_x000D_
      return $compile(element)($scope);_x000D_
app.directive('myDirectiveWithoutScope', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    template: '<div class="some"><label>{{$parent.label}}: <input></label></div>',_x000D_
    replace: true,_x000D_
    link: function ($scope, element) {_x000D_
      // element will be the div which gets the ng-model on the original directive_x000D_
      var model = element.attr('ng-model');_x000D_
      return $compile($('input',element).attr('ng-model', model))($scope);_x000D_
app.directive('myReplacedDirectiveIsolate', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: {},_x000D_
    template: '<input class="some">',_x000D_
    replace: true_x000D_
app.directive('myReplacedDirectiveChild', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: true,_x000D_
    template: '<input class="some">',_x000D_
    replace: true_x000D_
app.directive('myReplacedDirective', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    template: '<input class="some">',_x000D_
    replace: true_x000D_
.some {_x000D_
  border: 1px solid #cacaca;_x000D_
  padding: 10px;_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<div ng-app="model" ng-controller="MainCtrl">_x000D_
  This scope value <input ng-model="name">, label: "{{label}}"_x000D_
    <li>With new isolate scope (label from parent):_x000D_
      <my-directive-with-scope ng-model="name"></my-directive-with-scope>_x000D_
    <li>With new child scope:_x000D_
      <my-directive-with-child-scope ng-model="name"></my-directive-with-child-scope>_x000D_
    <li>Same scope:_x000D_
      <my-directive-without-scope ng-model="name"></my-directive-without-scope>_x000D_
    <li>Replaced element, isolate scope:_x000D_
      <my-replaced-directive-isolate ng-model="name"></my-replaced-directive-isolate>_x000D_
    <li>Replaced element, child scope:_x000D_
      <my-replaced-directive-child ng-model="name"></my-replaced-directive-child>_x000D_
    <li>Replaced element, same scope:_x000D_
      <my-replaced-directive ng-model="name"></my-replaced-directive>_x000D_
  <p>Try typing in the child scope ones, they copy the value into the child scope which breaks the link with the parent scope._x000D_
  <p>Also notice how removing jQuery makes it so only the new-isolate-scope version works._x000D_
  <p>Finally, note that the replace+isolate scope only works in AngularJS >=1.2.0_x000D_

I'm not sure I like the compiling at link time. However, if you're just replacing the element with another you don't need to do that.

All in all I prefer the first one. Simply set scope to {ngModel:"="} and set ng-model="ngModel" where you want it in your template.

Update: I inlined the code snippet and updated it for Angular v1.2. Turns out that isolate scope is still best, especially when not using jQuery. So it boils down to:

  • Are you replacing a single element: Just replace it, leave the scope alone, but note that replace is deprecated for v2.0:

    app.directive('myReplacedDirective', function($compile) {
      return {
        restrict: 'E',
        template: '<input class="some">',
        replace: true
  • Otherwise use this:

    app.directive('myDirectiveWithScope', function() {
      return {
        restrict: 'E',
        scope: {
          ngModel: '=',
        template: '<div class="some"><input ng-model="ngModel"></div>'

The program can't start because libgcc_s_dw2-1.dll is missing

Code::Blocks: add '-static' in settings->compiler->Linker settings->Other linker options.

PHP: How do I display the contents of a textfile on my page?

If you aren't looking to do anything to the stuff in the file, just display it, you can actually just include() it. include works for any file type, but of course it runs any php code it finds inside.

Unable to create Android Virtual Device

Simply because CPU/ABI says "No system images installed for this target". You need to install system images.

In the Android SDK Manager check that you have installed "ARM EABI v7a System Image" (for each Android version from 4.0 and on you have to install a system image to be able to run a virtual device)

In your case only ARM system image exsits (Android 4.2). If you were running an older version, Intel has provided System Images (Intel x86 ATOM). You can check on the internet to see the comparison in performance between both.

In my case (see image below) I haven't installed a System Image for Android 4.2, whereas I have installed ARM and Intel System Images for 4.1.2

As long as I don't install the 4.2 System Image I would have the same problem as you.

UPDATE : This recent article Speeding Up the Android Emaulator on Intel Architectures explains how to use/install correctly the intel system images to speed up the emulator.


What I show in the picture is for Android 4.2, as it was the original question, but is true for every versions of Android.

Of course (as @RedPlanet said), if you are developing for MIPS CPU devices you have to install the "MIPS System Image".

Finally, as @SeanJA said, you have to restart eclipse to see the new installed images. But for me, I always restart a software which I updated to be sure it takes into account all the modifications, and I assume it is a good practice to do so.

enter image description here

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

I found that, if you are using a storyboard, you will want to put the code that is presenting the new view controller in viewDidAppear. It will also get rid of the "Presenting view controllers on detached view controllers is discouraged" warning.

Get second child using jQuery

I didn't see it mentioned here, but you can also use CSS spec selectors. See the docs

$('#parentContainer td:nth-child(2)')


You can define a variable @Result to fill your data in it


IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
SET @Result = 1 
SET @Result = 2

How do I set an absolute include path in PHP?

hey all...i had a similar problem with my cms system. i needed a hard path for some security aspects. think the best way is like rob wrote. for quick an dirty coding think this works also..:-)

$path   = getcwd(); 
$myfile = "/";


getcwd () points to: /usr/srv/apache/htdocs/myworkingdir (as example)

echo ($path.$myfile);
would return...


access outside your working directory is not allowed.

includ_once ($path.$myfile);

//some code


nice day strtok

Split a string into an array of strings based on a delimiter

you can use the TStrings.DelimitedText property for split an string

check this sample

program Project28;



procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
   ListOfStrings.Delimiter       := Delimiter;
   ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer.
   ListOfStrings.DelimitedText   := Str;

   OutPutList: TStringList;
   OutPutList := TStringList.Create;
     Split(':', 'word:doc,txt,docx', OutPutList) ;


See this link for an explanation of StrictDelimiter.

DateTime.MinValue and SqlDateTime overflow

Very simple avoid using DateTime.MinValue use System.Data.SqlTypes.SqlDateTime.MinValue instead.

inline if statement java, why is not working

Syntax is Shown below:

"your condition"? "step if true":"step if condition fails"

converting Java bitmap to byte array

In order to avoid OutOfMemory error for bigger files, I would solve the task by splitting a bitmap into several parts and merging their parts' bytes.

private byte[] getBitmapBytes(Bitmap bitmap)
    int chunkNumbers = 10;
    int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
    byte[] imageBytes = new byte[bitmapSize];
    int rows, cols;
    int chunkHeight, chunkWidth;
    rows = cols = (int) Math.sqrt(chunkNumbers);
    chunkHeight = bitmap.getHeight() / rows;
    chunkWidth = bitmap.getWidth() / cols;

    int yCoord = 0;
    int bitmapsSizes = 0;

    for (int x = 0; x < rows; x++)
        int xCoord = 0;
        for (int y = 0; y < cols; y++)
            Bitmap bitmapChunk = Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkWidth, chunkHeight);
            byte[] bitmapArray = getBytesFromBitmapChunk(bitmapChunk);
            System.arraycopy(bitmapArray, 0, imageBytes, bitmapsSizes, bitmapArray.length);
            bitmapsSizes = bitmapsSizes + bitmapArray.length;
            xCoord += chunkWidth;

            bitmapChunk = null;
        yCoord += chunkHeight;

    return imageBytes;

private byte[] getBytesFromBitmapChunk(Bitmap bitmap)
    int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
    ByteBuffer byteBuffer = ByteBuffer.allocate(bitmapSize);
    return byteBuffer.array();

How to set IE11 Document mode to edge as default?

I ran into this problem with a particular webpage I was maintaining. No matter what settings I changed, it kept going back to IE8 compatibility mode.

It turned out X-UA-Compatible was set in the metadata in the head:

<meta http-equiv="X-UA-Compatible" content="IE=8" >

As I later discovered, and at least in Internet Explorer 11, you can see where it gets its "document mode" from, by going into developer tools (F12), then selecting the tab "Emulation", and checking the text below the drop down "Document mode".

Since we only support IE11 and higher, and Microsoft says document modes are deprecated, I just threw the whole thing out. That solved it.

Text editor to open big (giant, huge, large) text files

Tips and tricks


Why are you using editors to just look at a (large) file?

Under *nix or Cygwin, just use less. (There is a famous saying – "less is more, more or less" – because "less" replaced the earlier Unix command "more", with the addition that you could scroll back up.) Searching and navigating under less is very similar to Vim, but there is no swap file and little RAM used.

There is a Win32 port of GNU less. See the "less" section of the answer above.


Perl is good for quick scripts, and its .. (range flip-flop) operator makes for a nice selection mechanism to limit the crud you have to wade through.

For example:

$ perl -n -e 'print if ( 1000000 .. 2000000)' humongo.txt | less

This will extract everything from line 1 million to line 2 million, and allow you to sift the output manually in less.

Another example:

$ perl -n -e 'print if ( /regex one/ .. /regex two/)' humongo.txt | less

This starts printing when the "regular expression one" finds something, and stops when the "regular expression two" find the end of an interesting block. It may find multiple blocks. Sift the output...


This is another useful tool you can use. To quote the Wikipedia article:

logparser is a flexible command line utility that was initially written by Gabriele Giuseppini, a Microsoft employee, to automate tests for IIS logging. It was intended for use with the Windows operating system, and was included with the IIS 6.0 Resource Kit Tools. The default behavior of logparser works like a "data processing pipeline", by taking an SQL expression on the command line, and outputting the lines containing matches for the SQL expression.

Microsoft describes Logparser as a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. The results of the input query can be custom-formatted in text based output, or they can be persisted to more specialty targets like SQL, SYSLOG, or a chart.

Example usage:

C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line > 1000 and line < 2000"
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line like '%pattern%'"

The relativity of sizes

100 MB isn't too big. 3 GB is getting kind of big. I used to work at a print & mail facility that created about 2% of U.S. first class mail. One of the systems for which I was the tech lead accounted for about 15+% of the pieces of mail. We had some big files to debug here and there.

And more...

Feel free to add more tools and information here. This answer is community wiki for a reason! We all need more advice on dealing with large amounts of data...

Split text file into smaller multiple text file using command line

This "File Splitter" Windows command line program works nicely:

It's open source, simple, documented, proven, and worked for me.


fsplit -split 50 mb mylargefile.txt

Rename Files and Directories (Add Prefix)

On my system, I don't have the rename command. Here is a simple one liner. It finds all the HTML files recursively and adds prefix_ in front of their names:

for f in $(find . -name '*.html'); do mv "$f" "$(dirname "$f")/prefix_$(basename "$f")"; done

How to view the roles and permissions granted to any database user in Azure SQL server instance?

if you want to find about object name e.g. table name and stored procedure on which particular user has permission, use the following query:

SELECT pr.principal_id,, pr.type_desc, 
    pr.authentication_type_desc, pe.state_desc, pe.permission_name, OBJECT_NAME(major_id) objectName
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id
--INNER JOIN sys.schemas AS s ON s.principal_id =  sys.database_role_members.role_principal_id 
     where in ('youruser1','youruser2') 

How can I set the focus (and display the keyboard) on my EditText programmatically

showSoftInput was not working for me at all.

I figured I needed to set the input mode : android:windowSoftInputMode="stateVisible" (here in the Activity component in the manifest)

Hope this help!

Python: SyntaxError: non-keyword after keyword arg

To really get this clear, here's my for-beginners answer: You inputed the arguments in the wrong order.
A keyword argument has this style:

nullable=True, unique=False

A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:

name="Ricardo", fruit="chontaduro" 

This syntax error asks you to first put name="Ricardo" and all of its kind (non-keyword) before those like nullable=True.

Change directory command in Docker?

To change into another directory use WORKDIR. All the RUN, CMD and ENTRYPOINT commands after WORKDIR will be executed from that directory.

RUN git clone XYZ 
RUN make

How to bind bootstrap popover on dynamic elements


If your popover is going to have a selector that is consistent then you can make use of selector property of popover constructor.

var popOverSettings = {
    placement: 'bottom',
    container: 'body',
    html: true,
    selector: '[rel="popover"]', //Sepcify the selector here
    content: function () {
        return $('#popover-content').html();



Other ways:

  1. (Standard Way) Bind the popover again to the new items being inserted. Save the popoversettings in an external variable.
  2. Use Mutation Event/Mutation Observer to identify if a particular element has been inserted on to the ul or an element.


var popOverSettings = { //Save the setting for later use as well
    placement: 'bottom',
    container: 'body',
    html: true,
    //content:" <div style='color:red'>This is your div content</div>"
    content: function () {
        return $('#popover-content').html();


$('ul').on('DOMNodeInserted', function () { //listed for new items inserted onto ul

$('.pop-Add').click(function () {
    $('ul').append("<li class='project-name'>     <a>project name 2        <button class='pop-function' rel='popover'></button>     </a>   </li>");

But it is not recommended to use DOMNodeInserted Mutation Event for performance issues as well as support. This has been deprecated as well. So your best bet would be to save the setting and bind after you update with new element.


Another recommended way is to use MutationObserver instead of MutationEvent according to MDN, but again support in some browsers are unknown and performance a concern.

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {

// configuration of the observer:
var config = {
     attributes: true, 
     childList: true, 
     characterData: true

// pass in the target node, as well as the observer options
observer.observe($('ul')[0], config);


How do you share constants in NodeJS modules?

I found the solution Dominic suggested to be the best one, but it still misses one feature of the "const" declaration. When you declare a constant in JS with the "const" keyword, the existence of the constant is checked at parse time, not at runtime. So if you misspelled the name of the constant somewhere later in your code, you'll get an error when you try to start your node.js program. Which is a far more better misspelling check.

If you define the constant with the define() function like Dominic suggested, you won't get an error if you misspelled the constant, and the value of the misspelled constant will be undefined (which can lead to debugging headaches).

But I guess this is the best we can get.

Additionally, here's a kind of improvement of Dominic's function, in constans.js:

global.define = function ( name, value, exportsObject )
    if ( !exportsObject )
        if ( exports.exportsObject )
            exportsObject = exports.exportsObject;
            exportsObject = exports;        

    Object.defineProperty( exportsObject, name, {
        'value': value,
        'enumerable': true,
        'writable': false,

exports.exportObject = null;

In this way you can use the define() function in other modules, and it allows you to define constants both inside the constants.js module and constants inside your module from which you called the function. Declaring module constants can then be done in two ways (in script.js).


require( './constants.js' );

define( 'SOME_LOCAL_CONSTANT', "const value 1", this ); // constant in script.js
define( 'SOME_OTHER_LOCAL_CONSTANT', "const value 2", this ); // constant in script.js

define( 'CONSTANT_IN_CONSTANTS_MODULE', "const value x" ); // this is a constant in constants.js module


constants = require( './constants.js' );

// More convenient for setting a lot of constants inside the module
constants.exportsObject = this;
define( 'SOME_CONSTANT', "const value 1" ); // constant in script.js
define( 'SOME_OTHER_CONSTANT', "const value 2" ); // constant in script.js

Also, if you want the define() function to be called only from the constants module (not to bloat the global object), you define it like this in constants.js:

exports.define = function ( name, value, exportsObject )

and use it like this in script.js:

constants.define( 'SOME_CONSTANT', "const value 1" );

How to call function of one php file from another php file and pass parameters to it?



    function func1($param1, $param2)
        echo $param1 . ', ' . $param2;




    func1('Hello', 'world');

See manual

Find size of object instance in bytes in c#

For anyone looking for a solution that doesn't require [Serializable] classes and where the result is an approximation instead of exact science. The best method I could find is json serialization into a memorystream using UTF32 encoding.

private static long? GetSizeOfObjectInBytes(object item)
    if (item == null) return 0;
        // hackish solution to get an approximation of the size
        var jsonSerializerSettings = new JsonSerializerSettings
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
            DateTimeZoneHandling = DateTimeZoneHandling.Utc,
            MaxDepth = 10,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        var formatter = new JsonMediaTypeFormatter { SerializerSettings = jsonSerializerSettings };
        using (var stream = new MemoryStream()) { 
            formatter.WriteToStream(item.GetType(), item, stream, Encoding.UTF32);
            return stream.Length / 4; // 32 bits per character = 4 bytes per character
    catch (Exception)
        return null;

No, this won't give you the exact size that would be used in memory. As previously mentioned, that is not possible. But it'll give you a rough estimation.

Note that this is also pretty slow.

How to put a horizontal divisor line between edit text's in a activity

How about defining your own view? I have used the class below, using a LinearLayout around a view whose background color is set. This allows me to pre-define layout parameters for it. If you don't need that just extend View and set the background color instead.

public class HorizontalRulerView extends LinearLayout {

    static final int COLOR = Color.DKGRAY;
    static final int HEIGHT = 2;
    static final int VERTICAL_MARGIN = 10;
    static final int HORIZONTAL_MARGIN = 5;
    static final int TOP_MARGIN = VERTICAL_MARGIN;
    static final int BOTTOM_MARGIN = VERTICAL_MARGIN;
    static final int LEFT_MARGIN = HORIZONTAL_MARGIN;
    static final int RIGHT_MARGIN = HORIZONTAL_MARGIN;

    public HorizontalRulerView(Context context) {
        this(context, null);

    public HorizontalRulerView(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);

    public HorizontalRulerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        View v = new View(context);
        LayoutParams lp = new LayoutParams(
        lp.topMargin = TOP_MARGIN;
        lp.bottomMargin = BOTTOM_MARGIN;
        lp.leftMargin = LEFT_MARGIN;
        lp.rightMargin = RIGHT_MARGIN;
        addView(v, lp);


Use it programmatically or in Eclipse (Custom & Library Views -- just pull it into your layout).

The cast to value type 'Int32' failed because the materialized value is null

I see that this question is already answered. But if you want it to be split into two statements, following may be considered.

var credits = from u in context.User
              join ch in context.CreditHistory 
                  on u.ID equals ch.UserID                                        
              where u.ID == userID
              select ch;

var creditSum= credits.Sum(x => (int?)x.Amount) ?? 0;

How to compile makefile using MinGW?

You have to actively choose to install MSYS to get the make.exe. So you should always have at least (the native) mingw32-make.exe if MinGW was installed properly. And if you installed MSYS you will have make.exe (in the MSYS subfolder probably).

Note that many projects require first creating a makefile (e.g. using a configure script or automake .am file) and it is this step that requires MSYS or cygwin. Makes you wonder why they bothered to distribute the native make at all.

Once you have the makefile, it is unclear if the native executable requires a different path separator than the MSYS make (forward slashes vs backward slashes). Any autogenerated makefile is likely to have unix-style paths, assuming the native make can handle those, the compiled output should be the same.

How to pass table value parameters to stored procedure from .net code

Further to Ryan's answer you will also need to set the DataColumn's Ordinal property if you are dealing with a table-valued parameter with multiple columns whose ordinals are not in alphabetical order.

As an example, if you have the following table value that is used as a parameter in SQL:

  ID int not null
  Code nvarchar(10) not null,

You would need to order your columns as such in C#:

// this also bumps Code to ordinal of 1
// if you have more than 2 cols then you would need to set more ordinals

If you fail to do this you will get a parse error, failed to convert nvarchar to int.

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

-- I like this as the data type and the format remains consistent with a date time data type

;with cte as(
        cast(utcdate as date) UtcDay, DATEPART(hour, utcdate) UtcHour, count(*) as Counts
    from dbo.mytable cd 
    where utcdate between '2014-01-14' and '2014-01-15'
    group by
        cast(utcdate as date), DATEPART(hour, utcdate)
select dateadd(hour, utchour, cast(utcday as datetime)) as UTCDateHour, Counts
from cte

Convert char array to string use C

You can use strcpy but remember to end the array with '\0'

char array[20]; char string[100];

array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; array[5]='\0';
strcpy(string, array);
printf("%s\n", string);

How do I get the directory that a program is running from?

For Windows system at console you can use system(dir) command. And console gives you information about directory and etc. Read about the dir command at cmd. But for Unix-like systems, I don't know... If this command is run, read bash command. ls does not display directory...


int main()
    system("pause"); //this wait for Enter-key-press;
    return 0;

Does a finally block always get executed in Java?

Yes, because no control statement can prevent finally from being executed.

Here is a reference example, where all code blocks will be executed:

| x | Current result | Code 
|---|----------------|------ - - -
|   |                |     
|   |                | public static int finallyTest() {
| 3 |                |     int x = 3;
|   |                |     try {
|   |                |        try {
| 4 |                |             x++;
| 4 | return 4       |             return x;
|   |                |         } finally {
| 3 |                |             x--;
| 3 | throw          |             throw new RuntimeException("Ahh!");
|   |                |         }
|   |                |     } catch (RuntimeException e) {
| 4 | return 4       |         return ++x;
|   |                |     } finally {
| 3 |                |         x--;
|   |                |     }
|   |                | }
|   |                |
|---|----------------|------ - - -
|   | Result: 4      |

In the variant below, return x; will be skipped. Result is still 4:

public static int finallyTest() {
    int x = 3;
    try {
        try {
            if (true) throw new RuntimeException("Ahh!");
            return x; // skipped
        } finally {
    } catch (RuntimeException e) {
        return ++x;
    } finally {

References, of course, track their status. This example returns a reference with value = 4:

static class IntRef { public int value; }
public static IntRef finallyTest() {
    IntRef x = new IntRef();
    x.value = 3;
    try {
        return x;
    } finally {
        x.value++; // will be tracked even after return

How to change the MySQL root account password on CentOS7?

Please stop all services MySQL with following command /etc/init.d/mysqld stop After it use this

mysqld_safe --skip-grant-tables

its may work properly

Transition color fade on hover?

What do you want to fade? The background or color attribute?

Currently you're changing the background color, but telling it to transition the color property. You can use all to transition all properties.

.clicker { 
    -moz-transition: all .2s ease-in;
    -o-transition: all .2s ease-in;
    -webkit-transition: all .2s ease-in;
    transition: all .2s ease-in;
    background: #f5f5f5; 
    padding: 20px;

.clicker:hover { 
    background: #eee;

Otherwise just use transition: background .2s ease-in.

Git/GitHub can't push to master

Use Mark Longair's answer, but make sure to use the HTTPS link to the repository:

git remote set-url origin

You can use then git push origin master.

what's the differences between r and rb in fopen

On most POSIX systems, it is ignored. But, check your system to be sure.


The mode string can also include the letter 'b' either as last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with ISO/IEC 9899:1990 ('ISO C90') and has no effect; the 'b' is ignored.


The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two- character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-UNIX environments.)

How to use linux command line ftp with a @ sign in my username?

Try to define the account in a ~/.netrc file like this:

machine host login [email protected] password mypassword

Check man netrc for details.

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

Java program to find the largest & smallest number in n numbers without using arrays

@user3168844: try the below code:

import java.util.Scanner;

public class LargestSmallestNum {

    public void findLargestSmallestNo() {

        int smallest = Integer.MAX_VALUE;
        int large = 0;
        int num;

        System.out.println("enter the number");

        Scanner input = new Scanner(;

        int n = input.nextInt();

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

            num = input.nextInt();

            if (num > large)
                large = num;

            if (num < smallest)
                smallest = num;

            System.out.println("the largest is:" + large);
            System.out.println("Smallest no is : "  + smallest);

    public static void main(String...strings){
        LargestSmallestNum largestSmallestNum = new LargestSmallestNum();

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

For Intellij IDEA version 11.0.2

File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.

Next goto Build | Build artifacts --> choose your artifact.


How to get object length

Here's a jQuery-ised function of Innuendo's answer, ready for use.

    keyCount : function(o) {
        if(typeof o == "object") {
            var i, count = 0;
            for(i in o) {
                if(o.hasOwnProperty(i)) {
            return count;
        } else {
            return false;

Can be called like this:

var cnt = $.keyCount({"foo" : "bar"}); //cnt = 1;

sqlalchemy filter multiple columns

There are number of ways to do it:

Using filter() (and operator)

query = meta.Session.query(User).filter(,

Using filter_by() (and operator)

query = meta.Session.query(User).filter_by(,

Chaining filter() or filter_by() (and operator)

query = meta.Session.query(User).\

Using or_(), and_(), and not()

from sqlalchemy import and_, or_, not_

query = meta.Session.query(User).filter(

How do I make a placeholder for a 'select' box?

This HTML + CSS solution worked for me:

form select:invalid {_x000D_
  color: gray;_x000D_
form select option:first-child {_x000D_
  color: gray;_x000D_
form select:invalid option:not(:first-child) {_x000D_
  color: black;_x000D_
  <select required>_x000D_
    <option value="">Select Planet...</option>_x000D_
    <option value="earth">Earth</option>_x000D_
    <option value="pandora">Pandora</option>_x000D_

Good Luck...

Check if a string contains another string

You can also use the special word like:

Public Sub Search()
  If "My Big String with, in the middle" Like "*,*" Then
    Debug.Print ("Found ','")
  End If
End Sub

Finding the second highest number in array

The simplest way is -

public class SecondLargest {
    public static void main(String[] args) {
        int[] arr = { 1, 2, 5, 6, 3 };

        int first = Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            // If current element is smaller than first then update both first
            // and second
            if (arr[i] > first) {
                second = first;
                first = arr[i];
            // If arr[i] is in between first and second then update second
            else if (arr[i] > second && arr[i] != first) {
                second = arr[i];

Preventing iframe caching in browser

Make the URL of the iframe point to a page on your site which acts as a proxy to retrieve and return the actual contents of the iframe. Now you are no longer bound by the same-origin policy (EDIT: does not prevent the iframe caching issue).

How to parse an RSS feed using JavaScript?

Trying to find a good solution for this now, I happened upon the FeedEk jQuery RSS/ATOM Feed Plugin that does a great job of parsing and displaying RSS and Atom feeds via the jQuery Feed API. For a basic XML-based RSS feed, I've found it works like a charm and needs no server-side scripts or other CORS workarounds for it to run even locally.

Switch statement with returns -- code correctness

I would take a different tack entirely. Don't RETURN in the middle of the method/function. Instead, just put the return value in a local variable and send it at the end.

Personally, I find the following to be more readable:

String result = "";

switch (something) {
case 0:
  result = "blah";
case 1:
  result = "foo";

return result;

Error: fix the version conflict (google-services plugin)


You have to use:

classpath ''

This fixed my problem

Extract Google Drive zip from Google colab notebook

You can simply use this

!unzip file_location

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

Here's a better approach where you don't have to delete/move anything for Android Studio 3.+.

  1. Open Android Studio and click cancel/ignore for error prompts on missing SDK for each project.
  2. Close all your open projects. You can do this by File > Close Project.
  3. After you do step 1 for all projects, the Welcome screen appears.
  4. The welcome screen will detect you are missing the SDK and give you options to fix the problem, i.e., install the SDKs for you.

copy-item With Alternate Credentials

PowerShell 3.0 now supports for credentials on the FileSystem provider. To use alternate credentials, simply use the Credential parameter on the New-PSDrive cmdlet

PS > New-PSDrive -Name J -PSProvider FileSystem -Root \\server001\sharename -Credential mydomain\travisj -Persist

After this command you can now access the newly created drive and do other operations including copy or move files like normal drive. here is the full solution:

$Source = "C:\Downloads\myfile.txt"
$Dest   = "\\\c$\skumar"
$Username = "administrator"
$Password = ConvertTo-SecureString "Complex_Passw0rd" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential($Username, $Password)

New-PSDrive -Name J -PSProvider FileSystem -Root $Dest -Credential $mycreds -Persist
Copy-Item -Path $Source -Destination "J:\myfile.txt"

Windows-1252 to UTF-8 encoding

If you want to rename multiple files in a single command - let's say you want to convert all *.txt files - here is the command:

find . -name "*.txt" -exec iconv -f WINDOWS-1252 -t UTF-8 {} -o {}.ren \; -a -exec mv {}.ren {} \;

Find the day of a week

Use the lubridate package and function wday:

df$date <- as.Date(df$date)
wday(df$date, label=TRUE)
[1] Wed   Wed   Thurs
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat

ldconfig error: is not a symbolic link

You need to include the path of the libraries inside /etc/, and rerun ldconfig to upate the list

Other possibility is to include in the env variable LD_LIBRARY_PATH the path to your library, and rerun the executable.

check the symbolic links if they point to a valid library ...

You can add the path directly in /etc/, without include...

run ldconfig -p to see whether your library is well included in the cache.

How to Check if value exists in a MySQL database

    IF city='C7'
    THEN city
    ELSE 'somethingelse'
    END as `city`
FROM `table` WHERE `city` = 'c7'

Sites not accepting wget user agent header

It seems Yahoo server does some heuristic based on User-Agent in a case Accept header is set to */*.

Accept: text/html

did the trick for me.


wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"

Note: if you don't declare Accept header then wget automatically adds Accept:*/* which means give me anything you have.

SELECT INTO using Oracle


create table new_table_name 
select column_name,[more columns] from Existed_table;


create table dept
select empno, ename from emp;

If the table already exists:

insert into new_tablename select columns_list from Existed_table;

What is Python Whitespace and how does it work?


In Python


C pass int array pointer as parameter into a function

In your new code,

int func(int *B){
    *B[0] = 5;

B is a pointer to int, thus B[0] is an int, and you can't dereference an int. Just remove the *,

int func(int *B){
    B[0] = 5;

and it works.

In the initialisation

int B[10] = {NULL};

you are initialising anint with a void* (NULL). Since there is a valid conversion from void* to int, that works, but it is not quite kosher, because the conversion is implementation defined, and usually indicates a mistake by the programmer, hence the compiler warns about it.

int B[10] = {0};

is the proper way to 0-initialise an int[10].

How to make an autocomplete TextBox in ASP.NET?

1-Install AjaxControl Toolkit easily by Nugget

PM> Install-Package AjaxControlToolkit

2-then in markup

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  

<asp:TextBox ID="txtMovie" runat="server"></asp:TextBox>  

<asp:AutoCompleteExtender  ID="AutoCompleteExtender1"  TargetControlID="txtMovie"   
    runat="server" />  

3- in code-behind : to get the suggestions

    public static string[] GetCompletionList(string prefixText, int count, string contextKey) {  
        // Create array of movies  
        string[] movies = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"};  

        // Return matching movies  
        return (from m in movies where m.StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();  


Node.js – events js 72 throw er unhandled 'error' event

Close nodejs app running in another shell. Restart the terminal and run the program again.

Another server might be also using the same port that you have used for nodejs. Kill the process that is using nodejs port and run the app.

To find the PID of the application that is using port:8000

$ fuser 8000/tcp
8000/tcp:            16708

Here PID is 16708 Now kill the process using the kill [PID] command

$ kill 16708

Deleting folders in python recursively

Here's my pure pathlib recursive directory unlinker:

from pathlib import Path

def rmdir(directory):
    directory = Path(directory)
    for item in directory.iterdir():
        if item.is_dir():


How to read/write from/to file using Go?

The Read method takes a byte parameter because that is the buffer it will read into. It's a common Idiom in some circles and makes some sense when you think about it.

This way you can determine how many bytes will be read by the reader and inspect the return to see how many bytes actually were read and handle any errors appropriately.

As others have pointed in their answers bufio is probably what you want for reading from most files.

I'll add one other hint since it's really useful. Reading a line from a file is best accomplished not by the ReadLine method but the ReadBytes or ReadString method instead.

Can I set a breakpoint on 'memory access' in GDB?

Assuming the first answer is referring to the C-like syntax (char *)(0x135700 +0xec1a04f) then the answer to do rwatch *0x135700+0xec1a04f is incorrect. The correct syntax is rwatch *(0x135700+0xec1a04f).

The lack of ()s there caused me a great deal of pain trying to use watchpoints myself.

Programmatically read from STDIN or input file in Perl

Here is how I made a script that could take either command line inputs or have a text file redirected.

if ($#ARGV < 1) {
    @ARGV = ();
    @ARGV = <>;

This will reassign the contents of the file to @ARGV, from there you just process @ARGV as if someone was including command line options.


If no file is redirected, the program will sit their idle because it is waiting for input from STDIN.

I have not figured out a way to detect if a file is being redirected in yet to eliminate the STDIN issue.

How to get the public IP address of a user in C#

lblmessage.Text =Request.ServerVariables["REMOTE_HOST"].ToString();

How to create Python egg file

I think you should use python wheels for distribution instead of egg now.

Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

How to send password securely over HTTP?

You can use a challenge response scheme. Say the client and server both know a secret S. Then the server can be sure that the client knows the password (without giving it away) by:

  1. Server sends a random number, R, to client.
  2. Client sends H(R,S) back to the server (where H is a cryptographic hash function, like SHA-256)
  3. Server computes H(R,S) and compares it to the client's response. If they match, the server knows the client knows the password.


There is an issue here with the freshness of R and the fact that HTTP is stateless. This can be handled by having the server create a secret, call it Q, that only the server knows. Then the protocol goes like this:

  1. Server generates random number R. It then sends to the client H(R,Q) (which cannot be forged by the client).
  2. Client sends R, H(R,Q), and computes H(R,S) and sends all of it back to the server (where H is a cryptographic hash function, like SHA-256)
  3. Server computes H(R,S) and compares it to the client's response. Then it takes R and computes (again) H(R,Q). If the client's version of H(R,Q) and H(R,S) match the server's re-computation, the server deems the client authenticated.

To note, since H(R,Q) cannot be forged by the client, H(R,Q) acts as a cookie (and could therefore be implemented actually as a cookie).

Another Edit:

The previous edit to the protocol is incorrect as anyone who has observed H(R,Q) seems to be able to replay it with the correct hash. The server has to remember which R's are no longer fresh. I'm CW'ing this answer so you guys can edit away at this and work out something good.

Log to the base 2 in python

>>> def log2( x ):
...     return math.log( x ) / math.log( 2 )
>>> log2( 2 )
>>> log2( 4 )
>>> log2( 8 )
>>> log2( 2.4 )

print spaces with String.format()

int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");

How can I execute Python scripts using Anaconda's version of Python?

The instructions in the official Python documentation worked for me:

  1. Launch a command prompt.

  2. Associate the correct file group with .py scripts:

    assoc .py=Python.File

Redirect all Python files to the new executable:

    ftype Python.File=C:\Path\to\pythonw.exe "%1" %*

The example shows how to associate the .py extension with the .pyw executable, but it works if you want to associate the .py extension with the Anaconda Python executable. You need administrative rights. The name "Python.File" could be anything, you just have to make sure is the same name in the ftype command. When you finish and before you try double-clicking the .py file, you must change the "Open with" in the file properties. The file type will be now ".py" and it is opened with the Anaconda python.exe.

C#, Looping through dataset and show each record from a dataset column

I believe you intended it more this way:

foreach (DataTable table in ds.Tables)
    foreach (DataRow dr in table.Rows)
        DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
        rpt.SetParameterValue("TaskStartDate", TaskStart);

You always accessed your first row in your dataset.

serialize/deserialize java 8 java.time with Jackson JSON mapper

If you are using Jersey then you need to add the Maven dependency (jackson-datatype-jsr310) as the others suggested and register your object mapper instance like so:

public class JacksonObjectMapper implements ContextResolver<ObjectMapper> {

  final ObjectMapper defaultObjectMapper;

  public JacksonObjectMapper() {
    defaultObjectMapper = createDefaultMapper();

  public ObjectMapper getContext(Class<?> type) {
    return defaultObjectMapper;

  private static ObjectMapper createDefaultMapper() {
    final ObjectMapper mapper = new ObjectMapper();    
    mapper.registerModule(new JavaTimeModule());
    return mapper;

When registering Jackson in your resources, you need to add this mapper like so:

final ResourceConfig rc = new ResourceConfig().packages("<your package>");

How to wrap async function calls into a sync function in Node.js or Javascript?

You've got to use promises:

const asyncOperation = () => {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{resolve("hi")}, 3000)

const asyncFunction = async () => {
    return await asyncOperation();

const topDog = () => {
    asyncFunction().then((res) => {

I like arrow function definitions more. But any string of the form "() => {...}" could also be written as "function () {...}"

So topDog is not async despite calling an async function.

enter image description here

EDIT: I realize a lot of the times you need to wrap an async function inside a sync function is inside a controller. For those situations, here's a party trick:

const getDemSweetDataz = (req, res) => {
    (async () => {
                await asyncOperation()
            res.status(500).json(serviceResponse); //or whatever
    })() //So we defined and immediately called this async function.

Utilizing this with callbacks, you can do a wrap that doesn't use promises:

const asyncOperation = () => {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{resolve("hi")}, 3000)

const asyncFunction = async (callback) => {
    let res = await asyncOperation();

const topDog = () => {
    let callback = (res) => {

    (async () => {
        await asyncFunction(callback)

By applying this trick to an EventEmitter, you can get the same results. Define the EventEmitter's listener where I've defined the callback, and emit the event where I called the callback.

@class vs. #import

Look at the Objective-C Programming Language documentation on ADC

Under the section on Defining a Class | Class Interface it describes why this is done:

The @class directive minimizes the amount of code seen by the compiler and linker, and is therefore the simplest way to give a forward declaration of a class name. Being simple, it avoids potential problems that may come with importing files that import still other files. For example, if one class declares a statically typed instance variable of another class, and their two interface files import each other, neither class may compile correctly.

I hope this helps.

Sort an Array by keys based on another Array?

How about this solution

$order = array(1,5,2,4,3,6);

$array = array(
    1 => 'one',
    2 => 'two',
    3 => 'three',
    4 => 'four',
    5 => 'five',
    6 => 'six'

uksort($array, function($key1, $key2) use ($order) {
    return (array_search($key1, $order) > array_search($key2, $order));

"git pull" or "git merge" between master and development branches

my rule of thumb is:

rebase for branches with the same name, merge otherwise.

examples for same names would be master, origin/master and otherRemote/master.

if develop exists only in the local repository, and it is always based on a recent origin/master commit, you should call it master, and work there directly. it simplifies your life, and presents things as they actually are: you are directly developing on the master branch.

if develop is shared, it should not be rebased on master, just merged back into it with --no-ff. you are developing on develop. master and develop have different names, because we want them to be different things, and stay separate. do not make them same with rebase.

Woocommerce get products

Always use tax_query to get posts/products from a particular category or any other taxonomy. You can also get the products using ID/slug of particular taxonomy...

$the_query = new WP_Query( array(
    'post_type' => 'product',
    'tax_query' => array(
        array (
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => 'accessories',
) );

while ( $the_query->have_posts() ) :
    the_title(); echo "<br>";


Put icon inside input element in a form

 <label for="fileEdit">
    <i class="fa fa-cloud-upload">
    <input id="fileEdit" class="hidden" type="file" name="addImg" ng-file-change="onImageChange( $files )" ng-multiple="false" accept="{{ contentType }}"/>

For example you can use this : label with hidden input (icon is present).

Locate Git installation folder on Mac OS X

On Linux the command is whereis. Alternatively you can issue find / -name git and wait for an eternity. Alternatively try echo $PATH | sed "s/:/ /g" | xargs -L 1 ls | grep git

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

Using a HTTP debugging proxy can cause this - such as Fiddler.

I was loading a PFX certificate from a local file (authentication to and it failed because Fiddler wasn't able to pass this certificate on.

Try disabling Fiddler to check and if that is the solution then you need to probably install the certificate on your machine or in some way that Fiddler can use it.

Reload activity in Android

in some cases it's the best practice in other it's not a good idea it's context driven if you chose to do so using the following is the best way to pass from an activity to her sons :

    Intent i = new Intent(myCurrentActivityName.this,activityIWishToRun.class);    
    startActivityForResult(i, GlobalDataStore.STATIC_INTEGER_VALUE);

the thing is whenever you finish() from activityIWishToRun you return to your a living activity

Excel Date to String conversion

In some contexts using a ' character beforehand will work, but if you save to CSV and load again this is impossible.

'01/01/2010 14:30:00

How to copy only a single worksheet to another workbook using vba

The much longer example below combines some of the useful snippets above:

  • You can specify any number of sheets you want to copy across
  • You can copy entire sheets, i.e. like dragging the tab across, or you can copy over the contents of cells as values-only but preserving formatting.

It could still do with a lot of work to make it better (better error-handling, general cleaning up), but it hopefully provides a good start.

Note that not all formatting is carried across because the new sheet uses its own theme's fonts and colours. I can't work out how to copy those across when pasting as values only.

 Option Explicit

Sub copyDataToNewFile()
    Application.ScreenUpdating = False

    ' Allow different ways of copying data:
    ' sheet = copy the entire sheet
    ' valuesWithFormatting = create a new sheet with the same name as the
    '                        original, copy values from the cells only, then
    '                        apply original formatting. Formatting is only as
    '                        good as the Paste Special > Formats command - theme
    '                        colours and fonts are not preserved.
    Dim copyMethod As String
    copyMethod = "valuesWithFormatting"

    Dim newFilename As String           ' Name (+optionally path) of new file
    Dim themeTempFilePath As String     ' To temporarily save the source file's theme

    Dim sourceWorkbook As Workbook      ' This file
    Set sourceWorkbook = ThisWorkbook

    Dim newWorkbook As Workbook         ' New file

    Dim sht As Worksheet                ' To iterate through sheets later on.
    Dim sheetFriendlyName As String     ' To store friendly sheet name
    Dim sheetCount As Long              ' To avoid having to count multiple times

    ' Sheets to copy over, using internal code names as more reliable.
    Dim colSheetObjectsToCopy As New Collection
    colSheetObjectsToCopy.Add Sheet1
    colSheetObjectsToCopy.Add Sheet2

    ' Get filename of new file from user.
        newFilename = InputBox("Please Specify the name of your new workbook." & vbCr & vbCr & "Either enter a full path or just a filename, in which case the file will be saved in the same location (" & sourceWorkbook.Path & "). Don't use the name of a workbook that is already open, otherwise this script will break.", "New Copy")
        If newFilename = "" Then MsgBox "You must enter something.", vbExclamation, "Filename needed"
    Loop Until newFilename > ""

    ' If they didn't supply a path, assume same location as the source workbook.
    ' Not perfect - simply assumes a path has been supplied if a path separator
    ' exists somewhere. Could still be a badly-formed path. And, no check is done
    ' to see if the path actually exists.
    If InStr(1, newFilename, Application.PathSeparator, vbTextCompare) = 0 Then
        newFilename = sourceWorkbook.Path & Application.PathSeparator & newFilename
    End If

    ' Create a new workbook and save as the user requested.
    ' NB This fails if the filename is the same as a workbook that's
    ' already open - it should check for this.
    Set newWorkbook = Application.Workbooks.Add(xlWBATWorksheet)
    newWorkbook.SaveAs Filename:=newFilename, _

    ' Theme fonts and colours don't get copied over with most paste-special operations.
    ' This saves the theme of the source workbook and then loads it into the new workbook.
    ' BUG: Doesn't work!
    'themeTempFilePath = Environ("temp") & Application.PathSeparator & sourceWorkbook.Name & " - Theme.xml"
    'sourceWorkbook.Theme.ThemeFontScheme.Save themeTempFilePath
    'sourceWorkbook.Theme.ThemeColorScheme.Save themeTempFilePath
    'newWorkbook.Theme.ThemeFontScheme.Load themeTempFilePath
    'newWorkbook.Theme.ThemeColorScheme.Load themeTempFilePath
    'On Error Resume Next
    'Kill themeTempFilePath  ' kill = delete in VBA-speak
    'On Error GoTo 0

    ' getWorksheetNameFromObject returns null if the worksheet object doens't
    ' exist
    For Each sht In colSheetObjectsToCopy
        sheetFriendlyName = getWorksheetNameFromObject(sourceWorkbook, sht)
        Application.StatusBar = "VBL Copying " & sheetFriendlyName
        If Not IsNull(sheetFriendlyName) Then
            Select Case copyMethod
                Case "sheet"
                    sourceWorkbook.Sheets(sheetFriendlyName).Copy _
                Case "valuesWithFormatting"
                    newWorkbook.Sheets.Add After:=newWorkbook.Sheets(newWorkbook.Sheets.count), _
                    sheetCount = newWorkbook.Sheets.count
                    newWorkbook.Sheets(sheetCount).Name = sheetFriendlyName
                    ' Copy all cells in current source sheet to the clipboard. Could copy straight
                    ' to the new workbook by specifying the Destination parameter but in this case
                    ' we want to do a paste special as values only and the Copy method doens't allow that.
                    sourceWorkbook.Sheets(sheetFriendlyName).Cells.Copy ' Destination:=newWorkbook.Sheets(newWorkbook.Sheets.Count).[A1]
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlValues
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlFormats
                    newWorkbook.Sheets(sheetCount).Tab.Color = sourceWorkbook.Sheets(sheetFriendlyName).Tab.Color
                    Application.CutCopyMode = False
            End Select
        End If
    Next sht

    Application.StatusBar = False
    Application.ScreenUpdating = True

How to validate an email address using a regular expression?

I use


Which is the one used in ASP.NET by the RegularExpressionValidator.

How to deep watch an array in angularjs?

$watchCollection accomplishes what you want to do. Below is an example copied from angularjs website$rootScope.Scope While it's convenient, the performance needs to be taken into consideration especially when you watch a large collection.

  $scope.names = ['igor', 'matias', 'misko', 'james'];
  $scope.dataCount = 4;

  $scope.$watchCollection('names', function(newNames, oldNames) {
     $scope.dataCount = newNames.length;


  //still at 4 ... no changes


  //now there's been a change

Where to put Gradle configuration (i.e. credentials) that should not be committed?




authentication(userName: mavenUser, password: mavenPassword)

Get user info via Google API

If you only want to fetch the Google user id, name and picture for a visitor of your web app - here is my pure PHP service side solution for the year 2020 with no external libraries used -

If you read the Using OAuth 2.0 for Web Server Applications guide by Google (and beware, Google likes to change links to its own documentation), then you have to perform only 2 steps:

  1. Present the visitor a web page asking for the consent to share her name with your web app
  2. Then take the "code" passed by the above web page to your web app and fetch a token (actually 2) from Google.

One of the returned tokens is called "id_token" and contains the user id, name and photo of the visitor.

Here is the PHP code of a web game by me. Initially I was using Javascript SDK, but then I have noticed that fake user data could be passed to my web game, when using client side SDK only (especially the user id, which is important for my game), so I have switched to using PHP on the server side:


const APP_ID       = '';
const APP_SECRET   = 'abcdefghijklmnopq';

const REDIRECT_URI = 'https://the/url/of/this/PHP/script/';
const LOCATION     = 'Location:';
const TOKEN_URL    = '';
const ERROR        = 'error';
const CODE         = 'code';
const STATE        = 'state';
const ID_TOKEN     = 'id_token';

# use a "random" string based on the current date as protection against CSRF
$CSRF_PROTECTION   = md5(date('m.d.y'));

if (isset($_REQUEST[ERROR]) && $_REQUEST[ERROR]) {

    $tokenRequest = [
        'code'          => $_REQUEST[CODE],
        'client_id'     => APP_ID,
        'client_secret' => APP_SECRET,
        'redirect_uri'  => REDIRECT_URI,
        'grant_type'    => 'authorization_code',

    $postContext = stream_context_create([
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($tokenRequest)

    # Step #2: send POST request to token URL and decode the returned JWT id_token
    $tokenResult = json_decode(file_get_contents(TOKEN_URL, false, $postContext), true);
    error_log(print_r($tokenResult, true));
    $id_token    = $tokenResult[ID_TOKEN];
    # Beware - the following code does not verify the JWT signature! 
    $userResult  = json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', explode('.', $id_token)[1]))), true);

    $user_id     = $userResult['sub'];
    $given_name  = $userResult['given_name'];
    $family_name = $userResult['family_name'];
    $photo       = $userResult['picture'];

    if ($user_id != NULL && $given_name != NULL) {
        # print your web app or game here, based on $user_id etc.

$userConsent = [
    'client_id'     => APP_ID,
    'redirect_uri'  => REDIRECT_URI,
    'response_type' => 'code',
    'scope'         => 'profile',
    'state'         => $CSRF_PROTECTION,

# Step #1: redirect user to a the Google page asking for user consent
header(LOCATION . http_build_query($userConsent));


You could use a PHP library to add additional security by verifying the JWT signature. For my purposes it was unnecessary, because I trust that Google will not betray my little web game by sending fake visitor data.

Also, if you want to get more personal data of the visitor, then you need a third step:

const USER_INFO    = '';
const ACCESS_TOKEN = 'access_token'; 

# Step #3: send GET request to user info URL
$access_token = $tokenResult[ACCESS_TOKEN];
$userResult = json_decode(file_get_contents(USER_INFO . $access_token), true);

Or you could get more permissions on behalf of the user - see the long list at the OAuth 2.0 Scopes for Google APIs doc.

Finally, the APP_ID and APP_SECRET constants used in my code - you get it from the Google API console:


How to change UIButton image in Swift

Swift 5 and ensures the image scales to the size of the button but stays within the buttons bounds.

yourButton.clipsToBounds = true
yourButton.contentMode = .scaleAspectFill

// Use setBackgroundImage or setImage
yourButton.setBackgroundImage(UIImage(named: "yourImage"), for: .normal)

JavaScript - Get minutes between two dates

Subtracting 2 Date objects gives you the difference in milliseconds, e.g.:

var diff = Math.abs(new Date('2011/10/09 12:00') - new Date('2011/10/09 00:00'));

Math.abs is used to be able to use the absolute difference (so new Date('2011/10/09 00:00') - new Date('2011/10/09 12:00') gives the same result).

Dividing the result by 1000 gives you the number of seconds. Dividing that by 60 gives you the number of minutes. To round to whole minutes, use Math.floor or Math.ceil:

var minutes = Math.floor((diff/1000)/60);

In this example the result will be 720

How to use Python's pip to download and keep the zipped files for a package?

pip wheel is another option you should consider:

pip wheel mypackage -w .\outputdir

It will download packages and their dependencies to a directory (current working directory by default), but it performs the additional step of converting any source packages to wheels.

It conveniently supports requirements files:

pip wheel -r requirements.txt -w .\outputdir

Add the --no-deps argument if you only want the specifically requested packages:

pip wheel mypackage -w .\outputdir --no-deps

R cannot be resolved - Android error

One shoudn't try to import android.R. Try to fix all errors that appear in XML files, including the manifest file. When all errors are cleared, will reappear.

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything

# exception to the rule

Commit your .gitignore and .gitkeep files and this should resolve your issue.

How to install Python MySQLdb module using pip?


pip install pymysql

Then put the code below into (projectname/

import pymysql

My environment is (python3.5, django1.10) and this solution works for me!

Hope this helps!!

LINQ order by null column where order is ascending and nulls should be last

This is what I came up with because I am using extension methods and also my item is a string, thus no .HasValue:

.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)

This works with LINQ 2 objects in memory. I did not test it with EF or any DB ORM.

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

As it allows to install more than one version of java, I had install many 3 versions unknowingly but it was point to latest version "11.0.2"

I could able to solve this issue with below steps to move to "1.8"

$java -version

openjdk version "11.0.2" 2019-01-15 OpenJDK Runtime Environment 18.9 (build 11.0.2+9) OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)

cd /Library/Java/JavaVirtualMachines

jdk1.8.0_201.jdk jdk1.8.0_202.jdk openjdk-11.0.2.jdk

sudo rm -rf openjdk-11.0.2.jdk
sudo rm -rf jdk1.8.0_201.jdk


java -version

java version "1.8.0_202-ea" Java(TM) SE Runtime Environment (build 1.8.0_202-ea-b03) Java HotSpot(TM) 64-Bit Server VM (build 25.202-b03, mixed mode)

PHP - Session destroy after closing browser

Use the following code to destroy the session:


How to get Android crash logs?

I have created this library to solve all your problems. Crash Reporter is a handy tool to capture all your crashes and log them in device locally

Just add this dependency and you're good to go.

compile ''

Find all your crashes in device locally and fix them at your convenience. Crashes are saved using date and time format easy to track. Plus it also provides API for capture Logged Exceptions using below method.

CrashRepoter.logException(Exception e)

How to set shape's opacity?

In general you just have to define a slightly transparent color when creating the shape.

You can achieve that by setting the colors alpha channel.

#FF000000 will get you a solid black whereas #00000000 will get you a 100% transparent black (well it isn't black anymore obviously).

The color scheme is like this #AARRGGBB there A stands for alpha channel, R stands for red, G for green and B for blue.

The same thing applies if you set the color in Java. There it will only look like 0xFF000000.


In your case you'd have to add a solid node. Like below.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android=""
    <stroke android:width="4dp" android:color="#636161" />
    <padding android:left="20dp"
        android:bottom="20dp" />
    <corners android:radius="24dp" />
    <solid android:color="#88000000" />

The color here is a half transparent black.

How to set "style=display:none;" using jQuery's attr method?

Please try below code for it :



Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

How can I count the numbers of rows that a MySQL query returned?

If your SQL query has a LIMIT clause and you want to know how many results total are in that data set you can use SQL_CALC_FOUND_ROWS followed by SELECT FOUND_ROWS(); This returns the number of rows A LOT more efficiently that using COUNT(*)
Example (straight from MySQL docs):

    -> WHERE id > 100 LIMIT 10;

How do you write multiline strings in Go?

For me this is what I use if adding \n is not a problem.

fmt.Sprintf("Hello World\nHow are you doing today\nHope all is well with your go\nAnd code")

Else you can use the raw string

multiline := `Hello Brothers and sisters of the Code
              The grail needs us.

How to assign more memory to docker container

Allocate maximum memory to your docker machine from (docker preference -> advance )

Screenshot of advance settings: Screenshot of advance settings.

This will set the maximum limit docker consume while running containers. Now run your image in new container with -m=4g flag for 4 gigs ram or more. e.g.

docker run -m=4g {imageID}

Remember to apply the ram limit increase changes. Restart the docker and double check that ram limit did increased. This can be one of the factor you not see the ram limit increase in docker containers.

How to shutdown my Jenkins safely?

You can also look in the init script area (e.g. centos vi /etc/init.d/jenkins ) for details on how the service is actually started and stopped.

How to Right-align flex item?

'justify-content: flex-end' worked within price box container.

.price-box {
    justify-content: flex-end;

How to do INSERT into a table records extracted from another table

Remove "values" when you're appending a group of rows, and remove the extra parentheses. You can avoid the circular reference by using an alias for avg(CurrencyColumn) (as you did in your example) or by not using an alias at all.

If the column names are the same in both tables, your query would be like this:

INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn) as CurrencyColumn1
FROM Table1
GROUP BY LongIntColumn;

And it would work without an alias:

INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn)
FROM Table1
GROUP BY LongIntColumn;

Why does background-color have no effect on this DIV?

Floats don't have a height so the containing div has a height of zero.

<div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>

overflow:hidden clears the float for most browsers.

zoom:1 clears the float for IE.

How to hide a navigation bar from first ViewController in Swift?

Call the set hide method in view Will appear and Disappear. if you will not call the method in view will disappear with status false.It will hide the navigation bar in complete navigation hierarchy

 override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(true, animated: true)

override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(false, animated:true)

C# DateTime to "YYYYMMDDHHMMSS" format

Chances are slim that any of the above answers wouldn't has solved your problem. Nonetheless, I'm sharing my method which always works for me for different format of datetimes.

     public static DateTime ConvertPlainStringToDatetime(string Date, string inputFormat, string  outputFormat)
                DateTime date;
                CultureInfo enUS = new CultureInfo("en-US");
                DateTime.TryParseExact(Date, inputFormat, enUS,
                                    DateTimeStyles.AdjustToUniversal, out date);

                string formatedDateTime = date.ToString(outputFormat);
                return Convert.ToDateTime(formatedDateTime);   

    string oFormat = "yyyy-MM-dd HH:mm:ss";
    DateTime requiredDT = ConvertPlainStringToDatetime("20190205","yyyyMMddHHmmss", oFormat  );
    DateTime requiredDT = ConvertPlainStringToDatetime("20190508-12:46:42","yyyyMMdd-HH:mm:ss", oFormat);

Pass variables between two PHP pages without using a form or the URL of page


$message1 = "A message";
$message2 = "Another message";

$_SESSION['firstMessage'] = $message1;
$_SESSION['secondMessage'] = $message2; 

Stores the sessions on page 1 then on page 2 do


echo $_SESSION['firstMessage'];
echo $_SESSION['secondMessage'];

How to prevent column break within an element?

ul li{display: table;}  

works perfectly

Insert HTML with React Variable Statements (JSX)

If anyone else still lands here. With ES6 you can create your html variable like so:

    var thisIsMyCopy = (
        <p>copy copy copy <strong>strong copy</strong></p>

How to send email attachments?

The simplest code I could get to is:

#for attachment email
from django.core.mail import EmailMessage

    def attachment_email(request):
            email = EmailMessage(
            'Hello', #subject
            'Body goes here', #body
            '[email protected]', #from
            ['[email protected]'], #to
            ['[email protected]'], #bcc
            reply_to=['[email protected]'],
            headers={'Message-ID': 'foo'},


It was based on the official Django documentation

Java multiline string

Two answers to this question:

  1. In you want to stick to pure Java, with Java 14 being released in March 2020, you can leverage the JEP 368 - Text Blocks, in Second Preview mode. Actually the feature is in preview mode in other releases (at least 13 has it). I created and example set here.
  2. While this feature is useful, it can be easily abused. Remember that Java requires compilation - having large character arrays in your code can be an easy way to shoot yourself in the leg (if you want a quick change, you will need recompilation - that toolset might not be available to the guy operating your application).

In my experience, it is advisable to keep large strings (and generally strings that could/should be altered at runtime by app operators) in configuration files.

Summary: use text blocks responsibly :).

Create dynamic variable name

This is not possible, it will give you a compile time error,

You can use array for this type of requirement .

For your Reference :

How to quit android application programmatically

There is no application quitting in android, SampleActivity.this.finish(); will finish the current activity.

When you switch from one activity to another keep finish the previous one

Intent homeintent = new Intent(SampleActivity.this,SecondActivity.class);

What is the correct way of reading from a TCP socket in C/C++?

1) Others (especially dirkgently) have noted that buffer needs to be allocated some memory space. For smallish values of N (say, N <= 4096), you can also allocate it on the stack:

#define BUFFER_SIZE 4096
char buffer[BUFFER_SIZE]

This saves you the worry of ensuring that you delete[] the buffer should an exception be thrown.

But remember that stacks are finite in size (so are heaps, but stacks are finiter), so you don't want to put too much there.

2) On a -1 return code, you should not simply return immediately (throwing an exception immediately is even more sketchy.) There are certain normal conditions that you need to handle, if your code is to be anything more than a short homework assignment. For example, EAGAIN may be returned in errno if no data is currently available on a non-blocking socket. Have a look at the man page for read(2).

Create a new TextView programmatically then display it below another TextView

Try this code:

final String[] str = {"one","two","three","asdfgf"};
final RelativeLayout rl = (RelativeLayout) findViewById(;
final TextView[] tv = new TextView[10];

for (int i=0; i<str.length; i++)
    tv[i] = new TextView(this); 
    RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
    params.leftMargin = 50;
    params.topMargin  = i*50;
    tv[i].setTextSize((float) 20);
    tv[i].setPadding(20, 50, 20, 50);

Show how many characters remaining in a HTML text box using JavaScript

try this code in here...this is done using javascript onKeyUp() function...

function toCount(entrance,exit,text,characters) {  
var entranceObj=document.getElementById(entrance);  
var exitObj=document.getElementById(exit);  
var length=characters - entranceObj.value.length;  
if(length <= 0) {  
text='<span class="disable"> '+text+' <\/span>';  
exitObj.innerHTML = text.replace("{CHAR}",length);  

textarea counter demo

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

1) To redirect to the login page / from the login page, don't use the Redirect() methods. Use FormsAuthentication.RedirectToLoginPage() and FormsAuthentication.RedirectFromLoginPage() !

2) You should just use RedirectToAction("action", "controller") in regular scenarios.. You want to redirect in side the Initialize method? Why? I don't see why would you ever want to do this, and in most cases you should review your approach imo.. If you want to do this for authentication this is DEFINITELY the wrong way (with very little chances foe an exception) Use the [Authorize] attribute on your controller or method instead :)

UPD: if you have some security checks in the Initialise method, and the user doesn't have access to this method, you can do a couple of things: a)

Response.StatusCode = 403;

This will send the user back to the login page. If you want to send him to a custom location, you can do something like this (cautios: pseudocode)

Response.Redirect(Url.Action("action", "controller"));

No need to specify the full url. This should be enough. If you completely insist on the full url:

Response.Redirect(new Uri(Request.Url, Url.Action("action", "controller")).ToString());

Nested routes with react router v4 / v5

A complete answer for React Router v6 or version 6 just in case needed.

import Dashboard from "./dashboard/Dashboard";
import DashboardDefaultContent from "./dashboard/dashboard-default-content";
import { Route, Routes } from "react-router";
import { useRoutes } from "react-router-dom";

/*Routes is used to be Switch*/
const Router = () => {

  return (
      <Route path="/" element={<LandingPage />} />
      <Route path="games" element={<Games />} />
      <Route path="game-details/:id" element={<GameDetails />} />
      <Route path="dashboard" element={<Dashboard />}>
        <Route path="/" element={<DashboardDefaultContent />} />
        <Route path="inbox" element={<Inbox />} />
        <Route path="settings-and-privacy" element={<SettingsAndPrivacy />} />
        <Route path="*" element={<NotFound />} />
      <Route path="*" element={<NotFound />} />
export default Router;
import DashboardSidebarNavigation from "./dashboard-sidebar-navigation";
import { Grid } from "@material-ui/core";
import { Outlet } from "react-router";

const Dashboard = () => {
  return (
      <DashboardSidebarNavigation />
      <Outlet />

export default Dashboard;

Github repo is here.

matplotlib colorbar for scatter

Here is the OOP way of adding a colorbar:

fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)