Programs & Examples On #Gpc

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

The simple answer:

  • doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice

  • ADD 1 is probably faster than INC here

  • MOV 2 and DIV is very expensive; just shift right

  • 64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code

If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.

PHP call Class method / function

You need to create Object for the class.

$obj = new Functions();
$var = $obj->filter($_GET['params']);

WCF named pipe minimal example

I created this simple example from different search results on the internet.

public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
  //Create base address
  string baseAddress = "net.pipe://localhost/MyService";

  ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));

  //Net named pipe
  NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
  serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);

  //MEX - Meta data exchange
  ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
  serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");

  return serviceHost;

Using the above URI I can add a reference in my client to the web service.

How to use sha256 in php5.3.0

You should use Adaptive hashing like for securing passwords

What is a mixin, and why are they useful?

I'd advise against mix-ins in new Python code, if you can find any other way around it (such as composition-instead-of-inheritance, or just monkey-patching methods into your own classes) that isn't much more effort.

In old-style classes you could use mix-ins as a way of grabbing a few methods from another class. But in the new-style world everything, even the mix-in, inherits from object. That means that any use of multiple inheritance naturally introduces MRO issues.

There are ways to make multiple-inheritance MRO work in Python, most notably the super() function, but it means you have to do your whole class hierarchy using super(), and it's considerably more difficult to understand the flow of control.

How to turn off magic quotes on shared hosting?

As per the manual you can often install a custom php.ini on shared hosting, where mod_php isn't used and the php_value directive thus leads to an error. For suexec/FastCGI setups it is quite common to have a per-webspace php.ini in any case.


I don't think O (uppercase letter o) is a valid value to set an ini flag. You need to use a true/false, 1/0, or "on"/"off" value.

ini_set( 'magic_quotes_gpc', 0 );   // doesn't work


After checking the list of ini settings, I see that magic_quotes_gpc is a PHP_INI_PERDIR setting (after 4.2.3), which means you can't change it with ini_set() (only PHP_INI_ALL settings can be changed with ini_set())

What this means is you have to use an .htaccess file to do this - OR - implement a script to reverse the effects of magic quotes. Something like this

if ( in_array( strtolower( ini_get( 'magic_quotes_gpc' ) ), array( '1', 'on' ) ) )
    $_POST = array_map( 'stripslashes', $_POST );
    $_GET = array_map( 'stripslashes', $_GET );
    $_COOKIE = array_map( 'stripslashes', $_COOKIE );

Padding a table row

You could simply add this style to the table.

table {
    border-spacing: 15px;

Restore a postgres backup file using the command line?

If you have a backup SQL file then you can easily Restore it. Just follow the instructions, given in the below

1. At first, create a database using pgAdmin or whatever you want (for example my_db is our created db name)
2. Now Open command line window
3. Go to Postgres bin folder. For example:  cd "C:\ProgramFiles\PostgreSQL\pg10\bin"
4. Enter the following command to restore your database: psql.exe -U postgres -d my_db -f D:\Backup\backup_file_name.sql 

Type password for your postgres user if needed and let Postgres to do its work. Then you can check the restore process.

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>


<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;

These updates can be seen in this JSBin demo.

Multiple Errors Installing Visual Studio 2015 Community Edition

This is a very elusive problem. No (simple) solution looks to apply. I tried -all- the previous options with the same negative result: multiple packages errors.
Resorted to install VS 2013, success no issues, then VS 15 (Preview) success no issues (btw very cool).
Finally what works for me, was to install the very basic first 'Visual Studio 2015' with -NO- updates. During the installation, setup automatically downloaded 'Update 2' and the installation finished successfully.

Missing visible-** and hidden-** in Bootstrap v4

The hidden-* and visible-* classes no longer exist in Bootstrap 4. The same fucntion can be achieved in Bootstrap 4 by using the d-* for the specific tiers.

Spark - repartition() vs coalesce()

One additional point to note here is that, as the basic principle of Spark RDD is immutability. The repartition or coalesce will create new RDD. The base RDD will continue to have existence with its original number of partitions. In case the use case demands to persist RDD in cache, then the same has to be done for the newly created RDD.

scala> pairMrkt.repartition(10)
res16: org.apache.spark.rdd.RDD[(String, Array[String])] =MapPartitionsRDD[11] at repartition at <console>:26

scala> res16.partitions.length
res17: Int = 10

scala>  pairMrkt.partitions.length
res20: Int = 2

Writing an mp4 video using python opencv

For someone whoe still struggle with the problem. According this article I used this sample and it works for me:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'X264')
out = cv2.VideoWriter('output.mp4',fourcc, 20.0, (640,480))

    ret, frame =
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame

        if cv2.waitKey(1) & 0xFF == ord('q'):

# Release everything if job is finished

So I had to use cv2.VideoWriter_fourcc(*'X264') codec. Tested with OpenCV 3.4.3 compiled from sources.

SQLAlchemy IN clause

An alternative way is using raw SQL mode with SQLAlchemy, I use SQLAlchemy 0.9.8, python 2.7, MySQL 5.X, and MySQL-Python as connector, in this case, a tuple is needed. My code listed below:

id_list = [1, 2, 3, 4, 5] # in most case we have an integer list or set
s = text('SELECT id, content FROM myTable WHERE id IN :id_list')
conn = engine.connect() # get a mysql connection
rs = conn.execute(s, id_list=tuple(id_list)).fetchall()

Hope everything works for you.

How to send email by using javascript or jquery

You can send Email by Jquery just follow these steps 

include this link : <script src=""></script>
after that use this code :

$( document ).ready(function() {
Host : "",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});

SQL Server command line backup statement

Combine Remove Old Backup files with above script then this can perform backup by a scheduler, keep last 10 backup files

echo off
:: set folder to save backup files ex. BACKUPPATH=c:\backup
set BACKUPPATH=<<back up folder here>>

:: set Sql Server location ex. set SERVERNAME=localhost\SQLEXPRESS
set SERVERNAME=<<sql host here>>

:: set Database name to backup
set DATABASENAME=<<db name here>>

:: filename format Name-Date (eg MyDatabase-2009-5-19_1700.bak)
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

set DATESTAMP=%mydate%_%mytime%


:: In this case, we are choosing to keep the most recent 10 files
:: Also, the files we are looking for have a 'bak' extension
for /f "skip=10 delims=" %%F in ('dir %BACKUPPATH%\*.bak /s/b/o-d/a-d') do del "%%F"

How to check the version of GitLab?

If you are an admin and if you want to see the Gitlab version (and more you didn't know about) click on the wrench/admin menu icon and under Components you can see a lot , especially if you are using Omnibus.

Index (zero based) must be greater than or equal to zero

In this line:

Aboutme.Text = String.Format("{2}", reader.GetString(0));

The token {2} is invalid because you only have one item in the parms. Use this instead:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

Difference between Encapsulation and Abstraction

Let me explain it in with the same example discussed above. Kindly consider the same TV.

Encapsulation: The adjustments we can make with the remote is a good example - Volume UP/DOWN, Color & Contrast - All we can do is adjust it to the min and max value provided and cannot do anything beyond what is provided in the remote - Imagine the getter and setter here(The setter function will check whether the value provided is valid if Yes, it process the operation if not won't allow us to make changes - like we cannot decrease the volume beyond zero even we press the volume down button a hundred times).

Abstraction: We can take the same example here but with a higher Degree/Context. The volume down button will decrease the volume - and this is the info we provide to the user and the user is not aware of neither the infrared transmitter inside the remote nor the receiver in the TV and the subsequent process of parsing the signal and the microprocessor architecture inside the TV. Simply put it is not needed in the context - Just provide what is necessary. One can easily relate the Text book definition here ie., Hiding the inner implementation and only providing what it will do rather than how it do that!

Hope it clarifies a bit!

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.

How to call a shell script from python code?

Please Try the following codes :

Import Execute 


The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

This seems to happen from time to time with programs that are very sensitive to command lines, but one option is to just use the DOS path instead of the Windows path. This means that C:\Program Files\ would resolve to C:\PROGRA~1\ and generally avoid any issues with spacing.

To get the short path you can create a quick Batch file that echos the short path:

echo %~s1

Which is then called as follows:

C:\>shortPath.bat "C:\Program Files"

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Found this on a different forum

If you're wondering why that leading zero is important, it's because permissions are set as an octal integer, and Python automagically treats any integer with a leading zero as octal. So os.chmod("file", 484) (in decimal) would give the same result.

What you are doing is passing 664 which in octal is 1230

In your case you would need

os.chmod("/tmp/test_file", 436)

[Update] Note, for Python 3 you have prefix with 0o (zero oh). E.G, 0o666

Format a JavaScript string using placeholders and an object of substitutions?

Here is another way of doing this by using es6 template literals dynamically at runtime.

const str = 'My name is ${name} and my age is ${age}.'_x000D_
const obj = {name:'Simon', age:'33'}_x000D_
const result = new Function('const {' + Object.keys(obj).join(',') + '} = this.obj;return `' + str + '`').call({obj})_x000D_
document.body.innerHTML = result

How to get the azure account tenant Id?

The tenant id is also present in the management console URL when you browse to the given Active Directory instance, e.g.,<morestuffhere>/ActiveDirectoryExtension/Directory/BD848865-BE84-4134-91C6-B415927B3AB1

Azure Mgmt Console Active Directory

Handling a timeout error in python sockets

from foo import * 

adds all the names without leading underscores (or only the names defined in the modules __all__ attribute) in foo into your current module.

In the above code with from socket import * you just want to catch timeout as you've pulled timeout into your current namespace.

from socket import * pulls in the definitions of everything inside of socket but doesn't add socket itself.

    # socketstuff
except timeout:
    print 'caught a timeout'

Many people consider import * problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.

For example, consider the following three python files:

def foo():
    print "this is a's foo function"

def foo():
    print "this is b's foo function"

from a import *
from b import *

If you run you'll see just the output "this is b's foo function".

For this reason I'd suggest either importing the module and using it or importing specific names from the module:

For example, your code would look like this with explicit imports:

import socket
from socket import AF_INET, SOCK_DGRAM

def main():
    client_socket = socket.socket(AF_INET, SOCK_DGRAM)
    server_host = 'localhost'
    server_port = 1234
        client_socket.sendto('Message', (server_host, server_port))
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.timeout:
            #more code

Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.

Sort an ArrayList based on an object field

You can use the Bean Comparator to sort on any property in your custom class.

Convert object string to JSON

Douglas Crockford has a converter, but I'm not sure it will help with bad JSON to good JSON.

How to install CocoaPods?

sudo gem install -n /usr/local/bin cocoapods

This worked for me, -n helps you fix the permission error.

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

run pod install inside ios folder then go back to root folder and run npx react-native run-ios

How to open select file dialog via js?

With jquery library

<button onclick="$('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">

How can I use Timer (formerly NSTimer) in Swift?

If you init method of timer

let timer = Timer(timeInterval: 3, target: self, selector: #selector(update(_:)), userInfo: [key : value], repeats: false)

func update(_ timer : Timer) {


then add it to loop using method other selector will not be called

RunLoop.main.add(timer!, forMode: .defaultRunLoopMode)

NOTE : If you are want this to repeat make repeats true and keep the reference of timer otherwise update method will not be called.

If you are using this method.

Timer.scheduledTimer(timeInterval: seconds, target: self, selector: #selector(update(_:)), userInfo: nil, repeats: true)

keep a reference for later use if repeats is true.

Restful API service

Also when I hit the post(Config.getURL("login"), values) the app seems to pause for a while (seems weird - thought the idea behind a service was that it runs on a different thread!)

No you have to create a thread yourself, a Local service runs in the UI thread by default.

How to set a primary key in MongoDB?

This is the syntax of creating primary key

db.< collection >.createIndex( < key and index type specification>, { unique: true } )

Let's take that our database have collection named student and it's document have key named student_id which we need to make a primary key. Then the command should be like below.


You can check whether this student_id set as primary key by trying to add duplicate value to the student collection.

prefer this document for further informations

How to add icons to React Native app

You can import react-native-elements and use the font-awesome icons to your react native app


npm install --save react-native-elements

then import that where you want to use icons

import { Icon } from 'react-native-elements'

Use it like

render() {

How do I select an element with its name attribute in jQuery?

it's very simple getting a name:


Resource: (google search: get element by name jQuery - first result)

Negative list index?

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

How to remove text from a string?


Today 2021.01.14 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions.


For all browsers

  • solutions Ba, Cb, and Db are fast/fastest for long strings
  • solutions Ca, Da are fast/fastest for short strings
  • solutions Ab and E are slow for long strings
  • solutions Ba, Bb and F are slow for short strings

enter image description here


I perform 2 tests cases:

  • short string - 10 chars - you can run it HERE
  • long string - 1 000 000 chars - you can run it HERE

Below snippet presents solutions Aa Ab Ba Bb Ca Cb Da Db E F


function Aa(str,strToRemove) {
  return str.replace(strToRemove,'');

function Ab(str,strToRemove) {
  return str.replaceAll(strToRemove,'');

function Ba(str,strToRemove) {
  let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
  return str.replace(new RegExp(re),'');

function Bb(str,strToRemove) {
  let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
  return str.replaceAll(new RegExp(re,'g'),'');

function Ca(str,strToRemove) {
  let start = str.indexOf(strToRemove);
  return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);

function Cb(str,strToRemove) {
  let start =;
  return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);

function Da(str,strToRemove) {
  let start = str.indexOf(strToRemove);
  return str.substr(0, start) + str.substr(start + strToRemove.length);

function Db(str,strToRemove) {
  let start =;
  return str.substr(0, start) + str.substr(start + strToRemove.length);

function E(str,strToRemove) {
  return str.split(strToRemove).join('');

function F(str,strToRemove) {
    var n =;
    while ( > -1) {
        n =;
        str = str.substring(0, n) + str.substring(n + strToRemove.length, str.length);
    return str;

let str = "data-123";
let strToRemove = "data-";

[Aa,Ab,Ba,Bb,Ca,Cb,Da,Db,E,F].map( f=> console.log(`${,' ')} ${f(str,strToRemove)}`));
This shippet only presents functions used in performance tests - it not perform tests itself!

And here are example results for chrome

enter image description here

Receive result from DialogFragment

Or share ViewModel like showed here:

public class SharedViewModel extends ViewModel {
    private final MutableLiveData<Item> selected = new MutableLiveData<Item>();

    public void select(Item item) {

    public LiveData<Item> getSelected() {
        return selected;

public class MasterFragment extends Fragment {
    private SharedViewModel model;
    public void onCreate(Bundle savedInstanceState) {
        model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        itemSelector.setOnClickListener(item -> {

public class DetailFragment extends Fragment {
    public void onCreate(Bundle savedInstanceState) {
        SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        model.getSelected().observe(this, { item ->
           // Update the UI.

CSS transition with visibility not working

Visibility is an animatable property according to the spec, but transitions on visibility do not work gradually, as one might expect. Instead transitions on visibility delay hiding an element. On the other hand making an element visible works immediately. This is as it is defined by the spec (in the case of the default timing function) and as it is implemented in the browsers.

This also is a useful behavior, since in fact one can imagine various visual effects to hide an element. Fading out an element is just one kind of visual effect that is specified using opacity. Other visual effects might move away the element using e.g. the transform property, also see

It is often useful to combine the opacity transition with a visibility transition! Although opacity appears to do the right thing, fully transparent elements (with opacity:0) still receive mouse events. So e.g. links on an element that was faded out with an opacity transition alone, still respond to clicks (although not visible) and links behind the faded element do not work (although being visible through the faded element). See

This strange behavior can be avoided by just using both transitions, the transition on visibility and the transition on opacity. Thereby the visibility property is used to disable mouse events for the element while opacity is used for the visual effect. However care must be taken not to hide the element while the visual effect is playing, which would otherwise not be visible. Here the special semantics of the visibility transition becomes handy. When hiding an element the element stays visible while playing the visual effect and is hidden afterwards. On the other hand when revealing an element, the visibility transition makes the element visible immediately, i.e. before playing the visual effect.

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

Command find_package has two modes: Module mode and Config mode. You are trying to use Module mode when you actually need Config mode.

Module mode

Find<package>.cmake file located within your project. Something like this:


CMakeLists.txt content:


add_executable(Bar Bar.hpp Bar.cpp)
target_link_libraries(Bar ${FOO_LIBRARIES} ${BOO_LIBRARIES})

Note that CMAKE_MODULE_PATH has high priority and may be usefull when you need to rewrite standard Find<package>.cmake file.

Config mode (install)

<package>Config.cmake file located outside and produced by install command of other project (Foo for example).

foo library:

> cat CMakeLists.txt 
cmake_minimum_required(VERSION 2.8)

add_library(foo Foo.hpp Foo.cpp)
install(FILES Foo.hpp DESTINATION include)
install(TARGETS foo DESTINATION lib)
install(FILES FooConfig.cmake DESTINATION lib/cmake/Foo)

Simplified version of config file:

> cat FooConfig.cmake 
add_library(foo STATIC IMPORTED)

By default project installed in CMAKE_INSTALL_PREFIX directory:

> cmake -H. -B_builds
> cmake --build _builds --target install
-- Install configuration: ""
-- Installing: /usr/local/include/Foo.hpp
-- Installing: /usr/local/lib/libfoo.a
-- Installing: /usr/local/lib/cmake/Foo/FooConfig.cmake

Config mode (use)

Use find_package(... CONFIG) to include FooConfig.cmake with imported target foo:

> cat CMakeLists.txt 
cmake_minimum_required(VERSION 2.8)

# import library target `foo`
find_package(Foo CONFIG REQUIRED)

add_executable(boo Boo.cpp Boo.hpp)
target_link_libraries(boo foo)
> cmake --build _builds
Linking CXX executable Boo
/usr/bin/c++ ... -o Boo /usr/local/lib/libfoo.a

Note that imported target is highly configurable. See my answer.


VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

C# listView, how do I add items to columns 2, 3 and 4 etc?

Here is the msdn documentation on the listview object and the listviewItem object.

I would highly recommend that you at least take the time to skim the documentation on any objects you use from the .net framework. While the documentation can be pretty poor at some times it is still invaluable especially when you run into situations like this.

But as James Atkinson said it's simply a matter of adding subitems to a listviewitem like so:

ListViewItem i = new ListViewItem("column1");

PHP: How to use array_filter() to filter array keys?

Here is a more flexible solution using a closure:

$my_array = array("foo" => 1, "hello" => "world");
$allowed = array("foo", "bar");
$result = array_flip(array_filter(array_flip($my_array), function ($key) use ($allowed)
    return in_array($key, $allowed);


array(1) {
  'foo' =>

So in the function, you can do other specific tests.

Generate list of all possible permutations of a string

The following Java recursion prints all permutations of a given string:

//call it as permut("",str);

public void permut(String str1,String str2){
    if(str2.length() != 0){
        char ch = str2.charAt(0);
        for(int i = 0; i <= str1.length();i++)
            permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),

Following is the updated version of above "permut" method which makes n! (n factorial) less recursive calls compared to the above method

//call it as permut("",str);

public void permut(String str1,String str2){
   if(str2.length() > 1){
       char ch = str2.charAt(0);
       for(int i = 0; i <= str1.length();i++)
          permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),
    char ch = str2.charAt(0);
    for(int i = 0; i <= str1.length();i++)
        System.out.println(str1.substring(0,i) + ch +    str1.substring(i,str1.length()),

What does "TypeError 'xxx' object is not callable" means?

That error occurs when you try to call, with (), an object that is not callable.

A callable object can be a function or a class (that implements __call__ method). According to Python Docs:

object.__call__(self[, args...]): Called when the instance is “called” as a function

For example:

x = 1
print x()

x is not a callable object, but you are trying to call it as if it were it. This example produces the error:

TypeError: 'int' object is not callable

For better understaing of what is a callable object read this answer in another SO post.

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In my case, I had a collection of radio buttons that needed to be in a group. I just included a 'Selected' property in the model. Then, in the loop to output the radiobuttons just do...

@Html.RadioButtonFor(m => Model.Selected, Model.Categories[i].Title)

This way, the name is the same for all radio buttons. When the form is posted, the 'Selected' property is equal to the category title (or id or whatever) and this can be used to update the binding on the relevant radiobutton, like this...

model.Categories.Find(m => m.Title.Equals(model.Selected)).Selected = true;

May not be the best way, but it does work.

How to export a CSV to Excel using Powershell

If you want to convert CSV to Excel without Excel being installed, you can use the great .NET library EPPlus (under LGPL license) to create and modify Excel Sheets and also convert CSV to Excel really fast!


  1. Download the latest stable EPPlus version
  2. Extract EPPlus to your preferred location (e.g. to $HOME\Documents\WindowsPowerShell\Modules\EPPlus)
  3. Right Click EPPlus.dll, select Properties and at the bottom of the General Tab click "Unblock" to allow loading of this dll. If you don't have the rights to do this, try [Reflection.Assembly]::UnsafeLoadFrom($DLLPath) | Out-Null

Detailed Powershell Commands to import CSV to Excel

# Create temporary CSV and Excel file names
$FileNameCSV = "$HOME\Downloads\test.csv"
$FileNameExcel = "$HOME\Downloads\test.xlsx"

# Create CSV File (with first line containing type information and empty last line)
Get-Process | Export-Csv -Delimiter ';' -Encoding UTF8 -Path $FileNameCSV

# Load EPPlus
$DLLPath = "$HOME\Documents\WindowsPowerShell\Modules\EPPlus\EPPlus.dll"
[Reflection.Assembly]::LoadFile($DLLPath) | Out-Null

# Set CSV Format
$Format = New-object -TypeName OfficeOpenXml.ExcelTextFormat
$Format.Delimiter = ";"
# use Text Qualifier if your CSV entries are quoted, e.g. "Cell1","Cell2"
$Format.TextQualifier = '"'
$Format.Encoding = [System.Text.Encoding]::UTF8
$Format.SkipLinesBeginning = '1'
$Format.SkipLinesEnd = '1'

# Set Preferred Table Style
$TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium1

# Create Excel File
$ExcelPackage = New-Object OfficeOpenXml.ExcelPackage 
$Worksheet = $ExcelPackage.Workbook.Worksheets.Add("FromCSV")

# Load CSV File with first row as heads using a table style
$null=$Worksheet.Cells.LoadFromText((Get-Item $FileNameCSV),$Format,$TableStyle,$true) 

# Load CSV File without table style

# Fit Column Size to Size of Content

# Save Excel File

Write-Host "CSV File $FileNameCSV converted to Excel file $FileNameExcel"

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

This meta tag is used by all responsive web pages, that is those that are designed to layout well across device types - phone, tablet, and desktop. The attributes do what they say. However, as MDN's Using the viewport meta tag to control layout on mobile browsers indicates,

On high dpi screens, pages with initial-scale=1 will effectively be zoomed by browsers.

I've found that the following ensures that the page displays with zero zoom by default.

<meta name="viewport" content="width=device-width, initial-scale=0.86, maximum-scale=3.0, minimum-scale=0.86">

Conversion from List<T> to array T[]

Use ToArray() on List<T>.

jQuery send HTML data through POST

_x000D_,{ content: "John" } )_x000D_
 .done(function( data ) {_x000D_

I used the technique what u have replied above, it works fine but my problem is i need to generate a pdf conent using john as text . I have been able to echo the passed data. but getting empty in when generating pdf uisng below content ples check

   include_once(JPATH_SITE .'/components/com_gaevents/pdfgenerator.php');_x000D_
   $content = ob_get_clean();_x000D_
    $test = $_SESSION['content'] ;_x000D_
            $html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8',0 );   _x000D_

What .NET collection provides the fastest search

You should read this blog that speed tested several different types of collections and methods for each using both single and multi-threaded techniques.

According to the results, a BinarySearch on a List and SortedList were the top performers constantly running neck-in-neck when looking up something as a "value".

When using a collection that allows for "keys", the Dictionary, ConcurrentDictionary, Hashset, and HashTables performed the best overall.

Swift extract regex matches

Most of the solutions above only give the full match as a result ignoring the capture groups e.g.: ^\d+\s+(\d+)

To get the capture group matches as expected you need something like (Swift4) :

public extension String {
    public func capturedGroups(withRegex pattern: String) -> [String] {
        var results = [String]()

        var regex: NSRegularExpression
        do {
            regex = try NSRegularExpression(pattern: pattern, options: [])
        } catch {
            return results
        let matches = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.count))

        guard let match = matches.first else { return results }

        let lastRangeIndex = match.numberOfRanges - 1
        guard lastRangeIndex >= 1 else { return results }

        for i in 1...lastRangeIndex {
            let capturedGroupIndex = match.range(at: i)
            let matchedString = (self as NSString).substring(with: capturedGroupIndex)

        return results

PHP Curl And Cookies

Solutions which are described above, even with unique CookieFile names, can cause a lot of problems on scale.

We had to serve a lot of authentications with this solution and our server went down because of high file read write actions.

The solution for this was to use Apache Reverse Proxy and omit CURL requests at all.

Details how to use Proxy on Apache can be found here:

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

Type on terminal:

chmod -Rf 700 ~/.ssh/

And try again.

Splitting a string into chunks of a certain size

class StringHelper
    static void Main(string[] args)
        string str = "Hi my name is vikas bansal and my email id is [email protected]";
        int offSet = 10;

        List<string> chunks = chunkMyStr(str, offSet);


    static List<string> chunkMyStr(string str, int offSet)

        List<string> resultChunks = new List<string>();

        for (int i = 0; i < str.Length; i += offSet)
            string temp = str.Substring(i, (str.Length - i) > offSet ? offSet : (str.Length - i));


        return resultChunks;

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

Just copy paste the code below!

-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {

       UITableViewRowAction *editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Clona" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
          //insert your editAction here
       editAction.backgroundColor = [UIColor blueColor];

       UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Delete"  handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
          //insert your deleteAction here
       deleteAction.backgroundColor = [UIColor redColor];
return @[deleteAction,editAction];

How can I do an asc and desc sort using underscore.js?

Underscore Mixins

Extending on @emil_lundberg's answer, you can also write a "mixin" if you're using Underscore to make a custom function for sorting if it's a kind of sorting you might repeat in an application somewhere.

For example, maybe you have a controller or view sorting results with sort order of "ASC" or "DESC", and you want to toggle between that sort, you could do something like this:


    sortByOrder: function(stooges, prop, order) {
      if (String(order) === "desc") {
          return _.sortBy(stooges, prop).reverse();
      } else if (String(order) === "asc") {
          return _.sortBy(stooges, prop);
      } else {
          return stooges;

Usage Example

var sort_order = "asc";
var stooges = [
  {name: 'moe', age: 40}, 
  {name: 'larry', age: 50}, 
  {name: 'curly', age: 60},
  {name: 'July', age: 35},
  {name: 'mel', age: 38}

    sortByOrder: function(stooges, prop, order) {
    if (String(order) === "desc") {
        return _.sortBy(stooges, prop).reverse();
    } else if (String(order) === "asc") {
        return _.sortBy(stooges, prop);
    } else {
        return stooges;

// find elements
var banner = $("#banner-message");
var sort_name_btn = $("button.sort-name");
var sort_age_btn = $("button.sort-age");

function showSortedResults(results, sort_order, prop) {
    banner.append("<p>Sorting: " + prop + ', ' + sort_order + "</p><hr>")
  _.each(results, function(r) {
    banner.append('<li>' + + ' is '+ r.age + ' years old.</li>');

// handle click and add class
sort_name_btn.on("click", function() {
  sort_order = (sort_order === "asc") ? "desc" : "asc"; 
    var sortedResults = _.sortByOrder(stooges, 'name', sort_order);
  showSortedResults(sortedResults, sort_order, 'name');

sort_age_btn.on('click', function() {
    sort_order = (sort_order === "asc") ? "desc" : "asc"; 
    var sortedResults = _.sortByOrder(stooges, 'age', sort_order);
  showSortedResults(sortedResults, sort_order, 'age');

Here's a JSFiddle demonstrating this: JSFiddle for SortBy Mixin

SQLite table constraint - unique on multiple columns

Well, your syntax doesn't match the link you included, which specifies:

 CREATE TABLE name (column defs) 
    CONSTRAINT constraint_name    -- This is new
    UNIQUE (col_name1, col_name2) ON CONFLICT REPLACE

Add User to Role ASP.NET Identity

Below is an alternative implementation of a 'create user' controller method using Claims based roles.

The created claims then work with the Authorize attribute e.g. [Authorize(Roles = "Admin, User.*, User.Create")]

    // POST api/User/Create
    public async Task<IHttpActionResult> Create([FromBody]CreateUserModel model)
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        // Generate long password for the user
        var password = System.Web.Security.Membership.GeneratePassword(25, 5);

        // Create the user
        var user = new ApiUser() { UserName = model.UserName };
        var result = await UserManager.CreateAsync(user, password);
        if (!result.Succeeded)
            return GetErrorResult(result);

        // Add roles (permissions) for the user
        foreach (var perm in model.Permissions)
            await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, perm));

        return Ok<object>(new { UserName = user.UserName, Password = password });

Print string and variable contents on the same line in R

you can use paste0 or cat method to combine string with variable values in R

For Example:

paste0("Value of A : ", a)

cat("Value of A : ", a)

Python way to clone a git repository

For python 3

First install module:

pip3 install gitpython

and later, code it :)

import os
from git.repo.base import Repo
Repo.clone_from("*****", "folderToSave")

I hope this helps you

Flash CS4 refuses to let go

I have found one related behaviour that may help (sounds like your specific problem runs deeper though):

Flash checks whether a source file needs recompiling by looking at timestamps. If its compiled version is older than the source file, it will recompile. But it doesn't check whether the compiled version was generated from the same source file or not.

Specifically, if you have your actionscript files under version control, and you Revert a change, the reverted file will usually have an older timestamp, and Flash will ignore it.

throwing exceptions out of a destructor

Set an alarm event. Typically alarm events are better form of notifying failure while cleaning up objects

Which version of MVC am I using?

In Mvc You can do it by opening Web.config file it comes under bottom of your project file

DateTime.MinValue and SqlDateTime overflow

Basically, don't use DateTime.MinValue to represent a missing value. You can't use DateTime.MinValue in a SQL Server DateTime field, as SQL Server has a minimum value of the start of 1753.

Instead, make your BirthDate property a Nullable<DateTime> (aka DateTime?), and set it to null when you don't have a value. Also make sure your database field is nullable. Then you just need to make sure that that null ends up as a NULL value in the database. Exactly how you do that will depend on your data access, which you haven't told us anything about.

SQL statement to get column type

In my case I needed to get the data type for Dynamic SQL (Shudder!) anyway here is a function that I created that returns the full data type. For example instead of returning 'decimal' it would return DECIMAL(18,4): dbo.GetLiteralDataType

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

In addition of Stack: to avoid floating container on keyboard, use this

return Scaffold(
    appBar: getAppBar(title),
    resizeToAvoidBottomInset: false,

Threading Example in Android

Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.

Android code -


import android.os.Bundle;
import android.widget.TextView;

public class Test12Activity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        final TextView txt1 = (TextView) findViewById(;

        new Thread(new Runnable() { 
            public void run(){        


Android application xml - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

    android:id = "@+id/sm"


How do I show running processes in Oracle DB?

After looking at sp_who, Oracle does not have that ability per se. Oracle has at least 8 processes running which run the db. Like RMON etc.

You can ask the DB which queries are running as that just a table query. Look at the V$ tables.

Quick Example:

FROM v$session_longops
WHERE sofar != totalwork;

How to beautify JSON in Python?

The cli command I've used with python for this is:

cat myfile.json | python -mjson.tool

You should be able to find more info here:

How to implement "Access-Control-Allow-Origin" header in

Configuring the CORS response headers on the server wasn't really an option. You should configure a proxy in client side.

Sample to Angular - So, I created a proxy.conf.json file to act as a proxy server. Below is my proxy.conf.json file:

  "/api": {
    "target": "http://localhost:49389",
    "secure": true,
    "pathRewrite": {
      "^/api": "/api"
    "changeOrigin": true

Put the file in the same directory the package.json then I modified the start command in the package.json file like below

"start": "ng serve --proxy-config proxy.conf.json"

now, the http call from the app component is as follows:

return this.http.get('/api/customers').map((res: Response) => res.json());

Lastly to run use npm start or ng serve --proxy-config proxy.conf.json

Select 50 items from list at random to write to file

One easy way to select random items is to shuffle then slice.

import random
a = [1,2,3,4,5,6,7,8,9]
print a[:4] # prints 4 random variables

How to restart Postgresql

Try this as root (maybe you can use sudo or su):

/etc/init.d/postgresql restart

Without any argument the script also gives you a hint on how to restart a specific version

[Uqbar@Feynman ~] /etc/init.d/postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status} [version ...]

Similarly, in case you have it, you can also use the service tool:

[Uqbar@Feynman ~] service postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force reload|status} [version ...]

Please, pay attention to the optional [version ...] trailing argument. That's meant to allow you, the user, to act on a specific version, in case you were running multiple ones. So you can restart version X while keeping version Y and Z untouched and running.

Finally, in case you are running systemd, then you can use systemctl like this:

[support@Feynman ~] systemctl status postgresql
? postgresql.service - PostgreSQL database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2017-11-14 12:33:35 CET; 7min ago

You can replace status with stop, start or restart as well as other actions. Please refer to the documentation for full details. In order to operate on multiple concurrent versions, the syntax is slightly different. For example to stop v12 and reload v13 you can run:

systemctl stop postgresql-12.service
systemctl reload postgresql-13.service

Thanks to @Jojo for pointing me to this very one. Finally Keep in mind that root permissions may be needed for non-informative tasks as in the other cases seen earlier.

How do HashTables deal with collisions?

Update since Java 8: Java 8 uses a self-balanced tree for collision-handling, improving the worst case from O(n) to O(log n) for lookup. The use of a self-balanced tree was introduced in Java 8 as an improvement over chaining (used until java 7), which uses a linked-list, and has a worst case of O(n) for lookup (as it needs to traverse the list)

To answer the second part of your question, insertion is done by mapping a given element to a given index in the underlying array of the hashmap, however, when a collision occurs, all elements must still be preserved (stored in a secondary data-structure, and not just replaced in the underlying array). This is usually done by making each array-component (slot) be a secondary datastructure (aka bucket), and the element is added to the bucket residing on the given array-index (if the key does not already exist in the bucket, in which case it is replaced).

During lookup, the key is hashed to it's corresponding array-index, and search is performed for an element matching the (exact) key in the given bucket. Because the bucket does not need to handle collisions (compares keys directly), this solves the problem of collisions, but does so at the cost of having to perform insertion and lookup on the secondary datastructure. The key point is that in a hashmap, both the key and the value is stored, and so even if the hash collides, keys are compared directly for equality (in the bucket), and thus can be uniquely identified in the bucket.

Collission-handling brings the worst-case performance of insertion and lookup from O(1) in the case of no collission-handling to O(n) for chaining (a linked-list is used as secondary datastructure) and O(log n) for self-balanced tree.


Java 8 has come with the following improvements/changes of HashMap objects in case of high collisions.

  • The alternative String hash function added in Java 7 has been removed.

  • Buckets containing a large number of colliding keys will store their entries in a balanced tree instead of a linked list after certain threshold is reached.

Above changes ensure performance of O(log(n)) in worst case scenarios (

How to set <Text> text to upper case in react native

iOS textTransform support has been added to react-native in 0.56 version. Android textTransform support has been added in 0.59 version. It accepts one of these options:

  • none
  • uppercase
  • lowercase
  • capitalize

The actual iOS commit, Android commit and documentation


  <Text style={{ textTransform: 'uppercase'}}>
    This text should be uppercased.
  <Text style={{ textTransform: 'capitalize'}}>
    Mixed:{' '}
    <Text style={{ textTransform: 'lowercase'}}>
      lowercase{' '}

Copying from one text file to another using Python

The oneliner:

open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l])

Recommended with with:

with open("in.txt") as f:
    lines = f.readlines()
    lines = [l for l in lines if "ROW" in l]
    with open("out.txt", "w") as f1:

Using less memory:

with open("in.txt") as f:
    with open("out.txt", "w") as f1:
        for line in f:
            if "ROW" in line:

Check if inputs form are empty jQuery

$('input[type="text"]').get().some(item => item.value !== '');

Bootstrap modal not displaying

I had the same issue and I realized that my <button>had a type="submit"when Bootstrap states that it needs to be type="button"

Does Notepad++ show all hidden characters?

For non-printing characters, you can do the following:

  • if you could identify the character, where cursor takes 2 arrow keys to move, just select that character.
  • do Ctrl-F
  • now you can count or replace or even mark all such characters

Generate a range of dates using SQL

I don't have the answer to re-use the digits table but here is a code sample that will work at least in SQL server and is a bit faster.

print("code sample");

select  top 366 current_timestamp - row_number() over( order by l.A * r.A) as DateValue
from (
select  1 as A union
select  2 union
select  3 union
select  4 union
select  5 union
select  6 union
select  7 union
select  8 union
select  9 union
select  10 union
select  11 union
select  12 union
select  13 union
select  14 union
select  15 union
select  16 union
select  17 union
select  18 union
select  19 union
select  20 union
select  21 
) l
cross join (
select 1 as A union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
select 13 union
select 14 union
select 15 union
select 16 union
select 17 union
select 18
) r
print("code sample");

Angular 4 img src is not found

Copy your images into the assets folder. Angular can only access static files like images and config files from assets folder.

Try like this: <img src="assets/img/myimage.png">

How to force a view refresh without having it trigger automatically from an observable?

I have created a JSFiddle with my bindHTML knockout binding handler here:

First, save the binding handler into its own (or a common) file and include after Knockout.

If you use this switch your bindings to this:

<div data-bind="bindHTML: htmlValue"></div>


<!-- ko bindHTML: htmlValue --><!-- /ko -->

Update a column value, replacing part of a string

UPDATE yourtable
SET url = REPLACE(url, '', '')
WHERE url LIKE ('');

relevant docs:

Concatenating variables and strings in React

You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {} - you need to indicate which are variables and which are string literals. Since anything inside {} is an inline JSX expression, you can do:

href={"#demo" +}

This will use the string literal #demo and concatenate it to the value of This can then be applied to all strings. Consider this:

var text = "world";

And this:

{"Hello " + text + " Andrew"}

This will yield:

Hello world Andrew 

You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr} (interpolated expression), which is closer to what you seem to be trying to do:


This will basically substitute the value of, concatenating it to #demo. It is equivalent to doing: "#demo" +

What is the difference between a HashMap and a TreeMap?

TreeMap is an example of a SortedMap, which means that the order of the keys can be sorted, and when iterating over the keys, you can expect that they will be in order.

HashMap on the other hand, makes no such guarantee. Therefore, when iterating over the keys of a HashMap, you can't be sure what order they will be in.

HashMap will be more efficient in general, so use it whenever you don't care about the order of the keys.

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

In order to handle arrays with the $resource service, it's suggested that you use the query method. As you can see below, the query method is built to handle arrays.

    { 'get':    {method:'GET'},
      'save':   {method:'POST'},
      'query':  {method:'GET', isArray:true},
      'remove': {method:'DELETE'},
      'delete': {method:'DELETE'} 

User $resource("apiUrl").query();

Condition within JOIN or WHERE

Agree with 2nd most vote answer that it will make big difference when using LEFT JOIN or RIGHT JOIN. Actually, the two statements below are equivalent. So you can see that AND clause is doing a filter before JOIN while the WHERE clause is doing a filter after JOIN.

FROM dbo.Customers AS CUS 
LEFT JOIN dbo.Orders AS ORD 
ON CUS.CustomerID = ORD.CustomerID
AND ORD.OrderDate >'20090515'

FROM dbo.Customers AS CUS 
LEFT JOIN (SELECT * FROM dbo.Orders WHERE OrderDate >'20090515') AS ORD 
ON CUS.CustomerID = ORD.CustomerID

How do I set an ASP.NET Label text from code behind on page load?

Try something like this in your aspx page

<asp:Label ID="myLabel" runat="server"></asp:Label>

and then in your codebehind you can just do

myLabel.Text = "My Label";

SMTPAuthenticationError when sending mail using gmail and python

Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct

EDIT: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:

Go to this link and select Turn On

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

You can use

c map (t => t.getP -> t) toMap

but be aware that this needs 2 traversals.

PHP prepend leading zero before single digit number, on-the-fly

The universal tool for string formatting, sprintf:

$stamp = sprintf('%s%02s', $year, $month);

Running CMD command in PowerShell

You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.

If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock option.

How to give the background-image path in CSS?

Use the below.

background-image: url("././images/image.png");

This shall work.

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

SQL: Group by minimum value in one field while selecting distinct rows

This a old question, but this can useful for someone In my case i can't using a sub query because i have a big query and i need using min() on my result, if i use sub query the db need reexecute my big query. i'm using Mysql

select t.* 
    from (select m.*, @g := 0
        from MyTable m --here i have a big query
        order by id, record_date) t
    where (1 = case when @g = 0 or @g <> id then 1 else  0 end )
          and (@g := id) IS NOT NULL

Basically I ordered the result and then put a variable in order to get only the first record in each group.

CASE statement in SQLite query

The syntax is wrong in this clause (and similar ones)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2

It's either

    CASE WHEN [condition] THEN [expression] ELSE [expression] END


    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

So in your case it would read:

    CASE WHEN lkey > 5 THEN
        lkey + 2

Check out the documentation (The CASE expression):

Making a button invisible by clicking another button in HTML

try this

function demoShow() {   


<input type="button" value="click me" onclick="demoShow()" id="but" />

<input type="button" value="hide" id="but1" />

How to resize an image to fit in the browser window?

My general lazy CSS rule:

background: url('yoururl.jpg') no-repeat center;
background-position: 50% 50%;
background-size: 100% cover!important;

This may zoom in on your image if it is low-res to begin with (that's to do with your image quality and size in dimensions. To center your image, you may also try (in the CSS)

margin: auto 0; 

to center your image

in your HTML:

<div class="background"></div>

Java Returning method which returns arraylist?

MyClass obj = new MyClass();
ArrayList<Integer> numbers = obj.myNumbers();

How to do SVN Update on my project using the command line

I think I got it. It's:

"SVN Client Path"  /command:update / path:"My folder path"

Protect .NET code from reverse engineering?

A secret that you share with lots of people is not a secret. If you have secret stuff in your code, obfuscating it is no protection; it only has to be deobfuscated once. If you have a secret that you don't want to share with your customers, then don't share it with your customers. Write your code as a web service and keep your super secret code on your own server, where only you can see it.

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']

this is the method i use..

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Booting from CD to rescue the installation and editing /etc/selinux/config: changed SELINUX from enforcing to permissive. Rebooted and system booted

/etc/selinux/config before change:

SELINUX=enforcing and SELINUXTYPE=permissive

/etc/selinux/config after change: SELINUX=permissive and SELINUXTYPE=permissive

jQuery append() and remove() element

Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.

<span class="inputname">
    Project Images:
    <a href="#" class="add_project_file">
        <img src="images/add_small.gif" border="0" />

<ul class="project_images">
    <li><input name="upload_project_images[]" type="file" /></li>

Wrapping the file inputs inside li elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:

// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {

      + '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
      + '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
      + '</li>');

// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {


RegEx for matching "A-Z, a-z, 0-9, _" and "."

You could simply use ^[\w.]+ to match A-Z, a-z, 0-9 and _

SQL comment header examples

Here is my preferred variant:

/* =====================================================================
DESC:   Some notes about what this does
           tabbed in if you need additional lines
NOTES:  Additional notes
           tabbed in if you need additional lines
======================================================================== */

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

If you have just one query I don't know how to set timeout on T-SQL level.

However if you have a few queries (i.e. collecting data into temporary tables) inside stored procedure you can just control time of execution with GETDATE(), DATEDIFF() and a few INT variables storing time of execution of each part.

The Eclipse executable launcher was unable to locate its companion launcher jar windows

I Had same problem and it seems that there is wrong "--launcher.library " address in eclipse.ini file. so I have just changed it and

Android: why is there no maxHeight for a View?

I used a custom ScrollView made in Kotlin which uses maxHeight. Example of use:




Here is the code of ScrollViewWidthMaxHeight:

import android.content.Context
import android.util.AttributeSet
import android.widget.ScrollView
import timber.log.Timber

class ScrollViewWithMaxHeight @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ScrollView(context, attrs, defStyleAttr) {

companion object {

private var maxHeight = WITHOUT_MAX_HEIGHT_VALUE

init {
    val a = context.obtainStyledAttributes(
        attrs, R.styleable.ScrollViewWithMaxHeight,
        defStyleAttr, 0
    try {
        maxHeight = a.getDimension(
    } finally {

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    var heightMeasure = heightMeasureSpec
    try {
        var heightSize = MeasureSpec.getSize(heightMeasureSpec)
        if (maxHeight != WITHOUT_MAX_HEIGHT_VALUE) {
            heightSize = maxHeight
            heightMeasure = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.AT_MOST)
        } else {
            heightMeasure = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.UNSPECIFIED)
        layoutParams.height = heightSize
    } catch (e: Exception) {
        Timber.e(e, "Error forcing height")
    } finally {
        super.onMeasure(widthMeasureSpec, heightMeasure)

fun setMaxHeight(maxHeight: Int) {
    this.maxHeight = maxHeight

which needs also this declaration in values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<declare-styleable name="ScrollViewWithMaxHeight">
        <attr name="android:maxHeight" />

Typescript sleep

import { timer } from 'rxjs';

await timer(1000).pipe(take(1)).toPromise();

this works better for me

How do I compile a .c file on my Mac?

You can use gcc, in Terminal, by doing gcc -c tat.c -o tst

however, it doesn't come installed by default. You have to install the XCode package from tour install disc or download from

Here is where to download past developer tools from, which includes XCode 3.1, 3.0, 2.5 ...

How to force Chrome browser to reload .css file while debugging in Visual Studio?

With macOS I can force Chrome to reload the CSS file in by doing

? + SHIFT + R

Found this answer buried in the comments here but it deserved more exposure.

What killed my process and why?

We have had recurring problems under Linux at a customer site (Red Hat, I think), with OOMKiller (out-of-memory killer) killing both our principle application (i.e. the reason the server exists) and it's data base processes.

In each case OOMKiller simply decided that the processes were using to much resources... the machine wasn't even about to fail for lack of resources. Neither the application nor it's database has problems with memory leaks (or any other resource leak).

I am not a Linux expert, but I rather gathered it's algorithm for deciding when to kill something and what to kill is complex. Also, I was told (I can't speak as to the accuracy of this) that OOMKiller is baked into the Kernel and you can't simply not run it.

How can I add private key to the distribution certificate?

Yes, the error you are getting means that there is not a private key on your Mac associated with the distribution certificate you are trying to use to sign the app.

There are two possible solutions, depending on whether the computer who requested the distribution certificate is available or not.

If the computer who requested the distribution certificate is available (or there is a backup of the distribution assets somewhere)

  1. From the computer where the distribution asset was generated, open Xcode.
  2. Click on Window, Organizer.
  3. Expand the Teams section.
  4. Select your team, select the certificate of "iOS Distribution" type, click Export and follow the instructions.
  5. Save the exported file and go to your computer.
  6. Repeat steps 1-3.
  7. Click Import and select the file you exported before.

If the computer where the distribution profile was created is not accessible anymore (and there is not a backup)

You have to revoke the certificate and create a new one.

You may need to ask your team admin or agent to give you some privileges in order to generate distribution certificates. Once you have enough privileges, follow these steps (accurate as of 15-May-2013):

  1. Go to this webpage:
  2. Click on "Member Center" and enter your iOS developer credentials.
  3. Click on "Certificates, Identifiers & Profiles".
  4. Click on "Certificates" under the "iOS Apps" section.
  5. Expand the Certificates section on the left, select Distribution, and click on your distribution certificate.
  6. Click Revoke and follow the instructions.
  7. Click on the plus sign to add a new certificate.
  8. Select "App Store and Ad Hoc" option, and click Continue.
  9. Follow the steps printed in the webpage. That involves opening the Keychain application on your Mac and generate a Certificate Signing Request from there. Click Continue.
  10. Upload the .csr file and click Continue.
  11. A certificate is generated for distribution. Download it and double click it to integrate it in your keychain.

Reopen Xcode and check your project configuration to see if you can now select an "iPhone Distribution" certificate (i.e. it's not grayed out).

Why the switch statement cannot be applied on strings?

That's because C++ turns switches into jump tables. It performs a trivial operation on the input data and jumps to the proper address without comparing. Since a string is not a number, but an array of numbers, C++ cannot create a jump table from it.

movf    INDEX,W     ; move the index value into the W (working) register from memory
addwf   PCL,F       ; add it to the program counter. each PIC instruction is one byte
                    ; so there is no need to perform any multiplication. 
                    ; Most architectures will transform the index in some way before 
                    ; adding it to the program counter

table                   ; the branch table begins here with this label
    goto    index_zero  ; each of these goto instructions is an unconditional branch
    goto    index_one   ; of code
    goto    index_two
    goto    index_three

    ; code is added here to perform whatever action is required when INDEX = zero


(code from wikipedia

How to get current working directory in Java?

I just used:

import java.nio.file.Path;
import java.nio.file.Paths;


Path workingDirectory=Paths.get(".").toAbsolutePath();

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

In case of Request to a REST Service:

You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:

@CrossOrigin(origins = "http://localhost:8080")

Very good tutorial:

Printing *s as triangles in Java?

You might be interested in this too

      Scanner sc = new Scanner(;
      int n=sc.nextInt();
      int b=0;
      for(int i=n;i>=1;i--){
      for(int k=1;k<=b;k++){
      System.out.print(" ");
       for(int j=i;j>=1;j--){
       System.out.print(" ");

Output:: 5

       * * * * * 
         * * * * 
           * * * 
             * * 

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Well the thing is that you probably actually don't want the test to run indefinitely. You just want to wait a longer amount of time before the library decides the element doesn't exist. In that case, the most elegant solution is to use implicit wait, which is designed for just that:

driver.manage().timeouts().implicitlyWait( ... )

AngularJS : ng-model binding not updating when changed with jQuery

You have to trigger the change event of the input element because ng-model listens to input events and the scope will be updated. However, the regular jQuery trigger didn't work for me. But here is what works like a charm

$("#myInput")[0].dispatchEvent(new Event("input", { bubbles: true })); //Works

Following didn't work

$("#myInput").trigger("change"); // Did't work for me

You can read more about creating and dispatching synthetic events.

Java current machine name and logged in user?

To get the currently logged in user:


To get the host name of the machine:


To answer the last part of your question, the Java API says that getHostName() will return

the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.

How to place div in top right hand corner of page

Try css:

    right: 10px;

you can play with the top and right properties.

If you want to float the div even when you scroll down, just change position:absolute; to position:fixed;.

Hope it helps.

Reading DataSet

If this is from a SQL Server datebase you could issue this kind of query...

Select Top 1 DepartureTime From TrainSchedule where DepartureTime > 
Order By DepartureTime ASC

GetDate() could also be used, not sure how dates are being stored.

I am not sure how the data is being stored and/or read.

How can I find the current OS in Python?

import os

This gives you the essential information you will usually need. To distinguish between, say, different editions of Windows, you will have to use a platform-specific method.

How to get last inserted id?

I had the same need and found this answer ..

This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.


CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]

 @comp_name varchar(55) = 'Big Company',

 @comp_regno nchar(8) = '12345678',

 @comp_email nvarchar(50) = '[email protected]',


-- The '@recID' is used to hold the Company auto generated ID number that we are about to grab



  DECLARE @tableVar TABLE (tempID INT)

-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '@recID'.

  INSERT INTO comp(comp_name, comp_regno, comp_email) 

  OUTPUT inserted.comp_id INTO @tableVar

-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.

  VALUES (@comp_name, @comp_regno, @comp_email)

  SET @recID = (SELECT tempID FROM @tableVar)

-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '@recID'. '@recID' now has the ID number you want and you can use it how you want like i have used it below.

  INSERT INTO staff(Staff_comp_id) 
  VALUES (@recID)


-- So there you go. You can actually grab what ever you want in the 'OUTPUT inserted.WhatEverFieldNameYouWant' line and create what fields you want in your tempory table and access it to use how ever you want.

I was looking for something like this for ages, with this detailed break down, I hope this helps.

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like


(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

md-table - How to update the column width

Let's take an example. If your table has columns as follows:

<!-- ID Column -->
  <ng-container matColumnDef="id" >
    <th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
    <td mat-cell *matCellDef="let row"> {{row.sid}} </td>

 <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
    <td mat-cell *matCellDef="let row"> {{}} </td>

As this contain two columns. then we can set the width of columns using

    width: <witdh-size>% !important;

for this example, we take

    width: 20% !important;      
    width: 80% !important;

Reload child component when variables on parent component changes. Angular2

Use @Input to pass your data to child components and then use ngOnChanges ( to see if that @Input changed on the fly.

Difference between HashMap and Map in Java..?

Map<K,V> is an interface, HashMap<K,V> is a class that implements Map.

you can do

Map<Key,Value> map = new HashMap<Key,Value>();

Here you have a link to the documentation of each one: Map, HashMap.

Check if a row exists, otherwise insert

This is something I just recently had to do:

ALTER PROCEDURE [dbo].[cjso_UpdateCustomerLogin]
      @CustomerID AS INT,
      @UserName AS VARCHAR(25),
      @Password AS BINARY(16)
        IF ISNULL((SELECT CustomerID FROM tblOnline_CustomerAccount WHERE CustomerID = @CustomerID), 0) = 0
            INSERT INTO [tblOnline_CustomerAccount] (
            ) VALUES ( 
                /* CustomerID - int */ @CustomerID,
                /* UserName - varchar(25) */ @UserName,
                /* Password - binary(16) */ @Password,
                /* LastLogin - datetime */ NULL ) 
            UPDATE  [tblOnline_CustomerAccount]
            SET     UserName = @UserName,
                    Password = @Password
            WHERE   CustomerID = @CustomerID    


SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Paste this code to your pom.xml file. It works for me.


How do I get rid of the b-prefix in a string in python?

****How to remove b' ' chars which is decoded string in python ****

import base64

limit text length in php and provide 'Read more' link

<?php $string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
if (strlen($string) > 25) {
$trimstring = substr($string, 0, 25). ' <a href="#">readmore...</a>';
} else {
$trimstring = $string;
echo $trimstring;
//Output : Lorem Ipsum is simply dum [readmore...][1]

How to find the Git commit that introduced a string in any branch?

Not sure why the accepted answer doesn't work in my environment, finally I run below command to get what I need

git log --pretty=format:"%h - %an, %ar : %s"|grep "STRING"

How to put a link on a button with bootstrap?

The easiest solution is the first one of your examples:

<a href="#link" class="btn btn-info" role="button">Link Button</a>

The reason it's not working for you is most likely, as you say, a problem in the theme you're using. There is no reason to resort to bloated extra markup or inline Javascript for this.

Non-invocable member cannot be used like a method?

As the error clearly states, OffenceBox.Text() is not a function and therefore doesn't make sense.

Modify a Column's Type in sqlite3

It is possible by dumping, editing and reimporting the table.

This script will do it for you (Adapt the values at the start of the script to your needs):



echo "### create dump"
echo ".dump '$TABLE'" | sqlite3 "$DB" >$TMP

echo "### editing the create statement"
sed -i "s|$FIELD $OLD|$FIELD $NEW|g" $TMP

read -rsp $'Press any key to continue deleting and recreating the table $TABLE ...\n' -n1 key 

echo "### rename the original to '$TABLE"_backup"'"
sqlite3 "$DB" "PRAGMA busy_timeout=20000; ALTER TABLE '$TABLE' RENAME TO '$TABLE"_backup"'"

echo "### delete the old indexes"
for idx in $(echo "SELECT name FROM sqlite_master WHERE type == 'index' AND tbl_name LIKE '$TABLE""%';" | sqlite3 $DB); do
  echo "DROP INDEX '$idx';" | sqlite3 $DB

echo "### reinserting the edited table"
cat $TMP | sqlite3 $DB

org.xml.sax.SAXParseException: Content is not allowed in prolog

I followed the instructions found here and i got the same error.

I tried several things to solve it (ie changing the encoding, typing the XML file rather than copy-pasting it ect) in Notepad and XML Notepad but nothing worked.

The problem got solved when I edited and saved my XML file in Notepad++ (encoding --> utf-8 without BOM)

How do I view executed queries within SQL Server Management Studio?

If you want to see queries that are already executed there is no supported default way to do this. There are some workarounds you can try but don’t expect to find all.

You won’t be able to see SELECT statements for sure but there is a way to see other DML and DDL commands by reading transaction log (assuming database is in full recovery mode).

You can do this using DBCC LOG or fn_dblog commands or third party log reader like ApexSQL Log (note that tool comes with a price)

Now, if you plan on auditing statements that are going to be executed in the future then you can use SQL Profiler to catch everything.

Where to find htdocs in XAMPP Mac

From the Finder menu, click Go->Go to Folder. Type in /Applications/XAMPP

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Like the answer previous, but I'd put ::before, just for stacking purposes. If you want to include text over the overlay (a common use case), using ::before will should fix that.

.dimmed {
  position: relative;

.dimmed:before {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);

Hide text within HTML?

you can use css property to hide style="display:none;"

<div style="display:none;">CREDITS_HERE</div>

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied


sudo pip install virtualenv

Apparently you will have powers of administrator when adding "sudo" before the line... just don't forget your password.

How can I replace the deprecated set_magic_quotes_runtime in php?

add these code into the top of your script to solve problem

ini_set('magic_quotes_runtime', 0);

Echoing the last command run in Bash?

The command history is an interactive feature. Only complete commands are entered in the history. For example, the case construct is entered as a whole, when the shell has finished parsing it. Neither looking up the history with the history built-in (nor printing it through shell expansion (!:p)) does what you seem to want, which is to print invocations of simple commands.

The DEBUG trap lets you execute a command right before any simple command execution. A string version of the command to execute (with words separated by spaces) is available in the BASH_COMMAND variable.

trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
echo "last command is $previous_command"

Note that previous_command will change every time you run a command, so save it to a variable in order to use it. If you want to know the previous command's return status as well, save both in a single command.

cmd=$previous_command ret=$?
if [ $ret -ne 0 ]; then echo "$cmd failed with error code $ret"; fi

Furthermore, if you only want to abort on a failed commands, use set -e to make your script exit on the first failed command. You can display the last command from the EXIT trap.

set -e
trap 'echo "exit $? due to $previous_command"' EXIT

Note that if you're trying to trace your script to see what it's doing, forget all this and use set -x.

How to auto-generate a C# class file from a JSON string

Visual Studio 2012 (with ASP.NET and Web Tools 2012.2 RC installed) supports this natively.

Visual Studio 2013 onwards have this built-in.

Visual Studio Paste JSON as Classes screenshot (Image courtesy: robert.muehsig)

PHP - Get bool to echo false when false

This will print out boolean value as it is, instead of 1/0.

    $bool = false;

    echo json_encode($bool);   //false

How can I stop Chrome from going into debug mode?

For anyone that's searching why their chrome debugger is automatically jumping to sources tab on every page load, event though all of the breakpoints/pauses/etc have been disabled.

For me it was the "breakOnLoad": true line in VS Code launch.json config.

Service Temporarily Unavailable Magento?

I had the same issue but have not found the maintenance.flag file in my Magento root. I simply deleted cache and sessions files and all worked again.

Invalid self signed SSL cert - "Subject Alternative Name Missing"

Here is a very simple way to create an IP certificate that Chrome will trust.

The ssl.conf file...

[ req ]
default_bits       = 4096
distinguished_name = req_distinguished_name
req_extensions     = req_ext
prompt             = no

[ req_distinguished_name ]
commonName                  =

[ req_ext ]
subjectAltName = IP:

Where, of course is the local network IP we want Chrome to trust.

Create the certificate:

openssl genrsa -out key1.pem
openssl req -new -key key1.pem -out csr1.pem -config ssl.conf
openssl x509 -req -days 9999 -in csr1.pem -signkey key1.pem -out cert1.pem -extensions req_ext -extfile ssl.conf
rm csr1.pem

On Windows import the certificate into the Trusted Root Certificate Store on all client machines. On Android Phone or Tablet download the certificate to install it. Now Chrome will trust the certificate on windows and Android.

On windows dev box the best place to get openssl.exe is from "c:\Program Files\Git\usr\bin\openssl.exe"

mysqli_select_db() expects parameter 1 to be mysqli, string given

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));

You got the order of the arguments to mysqli_select_db() backwards. And mysqli_error() requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.

Note also that with mysqli you can specify the DB in mysqli_connect():

$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
  die("Database connection failed: " . mysqli_connect_error();

You must use mysqli_connect_error(), not mysqli_error(), to get the error from mysqli_connect(), since the latter requires you to supply a valid connection.

try/catch blocks with async/await

catching in this fashion, in my experience, is dangerous. Any error thrown in the entire stack will be caught, not just an error from this promise (which is probably not what you want).

The second argument to a promise is already a rejection/failure callback. It's better and safer to use that instead.

Here's a typescript typesafe one-liner I wrote to handle this:

function wait<R, E>(promise: Promise<R>): [R | null, E | null] {
  return (promise.then((data: R) => [data, null], (err: E) => [null, err]) as any) as [R, E];

// Usage
const [currUser, currUserError] = await wait<GetCurrentUser_user, GetCurrentUser_errors>(

Ant: How to execute a command for each file in directory?

You can use the ant-contrib task "for" to iterate on the list of files separate by any delimeter, default delimeter is ",".

Following is the sample file which shows this:

<project name="modify-files" default="main" basedir=".">
    <taskdef resource="net/sf/antcontrib/antlib.xml"/>
    <target name="main">
        <for list="FileA,FileB,FileC,FileD,FileE" param="file">
            <echo>Updating file: @{file}</echo>
            <!-- Do something with file here -->

Check if datetime instance falls in between other two datetime objects

You can use:

if ((DateTime.Compare(dateToCompare, dateIn) == 1) && (DateTime.Compare(dateToCompare, dateOut) == 1)
   //do code here


if ((dateToCompare.CompareTo(dateIn) == 1) && (dateToCompare.CompareTo(dateOut) == 1))
   //do code here

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

I faced the same problem but on Ubuntu Server. So all I did is changed to superuser before I activate virtual environment for django and then I ran the django server. It worked fine for me.

First copy paste

sudo su

Then activate the virtual environment if you have one.

source myvenv/bin/activate

At last run your django server.

python3 runserver

Hope, this will help you.

Word-wrap in an HTML table

style="table-layout:fixed; width:98%; word-wrap:break-word"

<table bgcolor="white" id="dis" style="table-layout:fixed; width:98%; word-wrap:break-word" border="0" cellpadding="5" cellspacing="0" bordercolordark="white" bordercolorlight="white" >

Demo -

This worked great for me. I had long links that would cause the table to exceed 100% on web browsers. Tested on IE, Chrome, Android and Safari.

Clear the value of bootstrap-datepicker

You can use this syntax to reset your bootstrap datepicker



Download a file with Android, and showing the progress in a ProgressDialog

Yes the code above will work .But if you are updating your progressbar in onProgressUpdate of Asynctask and you press back button or finish your activity AsyncTask looses its track with your UI .And when you go back to your activity, even if download is running in background you will see no update on progressbar. So on OnResume() try to run a thread like runOnUIThread with a timer task that updates ur progressbar with values updating from the AsyncTask running background.

private void updateProgressBar(){
    Runnable runnable = new updateProgress();
    background = new Thread(runnable);

public class updateProgress implements Runnable {
    public void run() {
            //while (!Thread.currentThread().isInterrupted()) {
            try {
                Message msg = new Message();
                progress = getProgressPercentage();        
            } catch (InterruptedException e) {
            } catch (Exception e) {

private Handler handler = new Handler(){
    public void handleMessage(Message msg) {

Don't forget to Destroy the thread when ur activity is not visible.

private void destroyRunningThreads() {
    if (background != null) {

How to create JSON string in C#

You could use the JavaScriptSerializer class, check this article to build an useful extension method.

Code from article:

namespace ExtensionMethods
    public static class JSONHelper
        public static string ToJSON(this object obj)
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);

        public static string ToJSON(this object obj, int recursionDepth)
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(obj);


using ExtensionMethods;


List<Person> people = new List<Person>{
                   new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
                   new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}

string jsonString = people.ToJSON();

Java: How to stop thread?

The recommended way will be to build this into the thread. So no you can't (or rather shouldn't) kill the thread from outside.

Have the thread check infrequently if it is required to stop. (Instead of blocking on a socket until there is data. Use a timeout and every once in a while check if the user indicated wanting to stop)

Django TemplateDoesNotExist?

Works on Django 3

I found I believe good way, I have the base.html in root folder, and all other html files in App folders, I

import os

# This settings are to allow store templates,static and media files in root folder

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
MEDIA_DIR = os.path.join(BASE_DIR,'media')

# This is default path from Django, must be added 
#AFTER our BASE_DIR otherwise DB will be broken.
BASE_DIR = Path(__file__).resolve().parent.parent

# add your apps to Installed apps

# Now add TEMPLATE_DIR to  'DIRS' where in TEMPLATES like bellow
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
# On end of put this refferences to Static and Media files
STATIC_URL = '/static/'

MEDIA_URL = '/media/'

If you have problem with Database, please check if you put the original BASE_DIR bellow the new BASE_DIR otherwise change

# Original
'NAME': BASE_DIR / 'db.sqlite3',
# to
'NAME': os.path.join(BASE_DIR,'db.sqlite3'),

Django now will be able to find the HTML and Static files both in the App folders and in Root folder without need of adding the name of App folder in front of the file.

    -static(css,JS ...)
    -templates(base.html, ....)
    -other django files like (, ....)
        -templates(index1.html, other html files can extend now base.html too)
        -other App1 files
        -templates(index2.html, other html files can extend now base.html too)
        -other App2 files

cannot make a static reference to the non-static field

You are trying to access non static field directly from static method which is not legal in java. balance is a non static field, so either access it using object reference or make it static.

Paused in debugger in chrome?

And there is some options below ,if you have checked some,when the condition is active,the breakpoint debugger also active

How do I set vertical space between list items?

<br>between <li></li> line entries seems to work perfectly well in all web browsers that I've tried, but it fails to pass the on-line W3C CSS3 checker. It gives me precisely the line spacing I am after. As far as I am concerned, since it undoubtedly works, I am persisting in using it, whatever W3C says, until someone can come up with a good legal alternative.

How to calculate number of days between two dates

This works for me:

const from = '2019-01-01';_x000D_
const to   = '2019-01-08';_x000D_
    moment(from, 'YYYY-MM-DD')_x000D_
      .diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')_x000D_
  ) + 1_x000D_

Copy files from one directory into an existing directory

Depending on some details you might need to do something like this:

case "$TARG" in
    /*) p=$r;;
    *) p="";;
cd "$SRC" && cp -r . "$p/$TARG"
cd "$r"

... this basically changes to the SRC directory and copies it to the target, then returns back to whence ever you started.

The extra fussing is to handle relative or absolute targets.

(This doesn't rely on subtle semantics of the cp command itself ... about how it handles source specifications with or without a trailing / ... since I'm not sure those are stable, portable, and reliable beyond just GNU cp and I don't know if they'll continue to be so in the future).

Changing plot scale by a factor in matplotlib

Instead of changing the ticks, why not change the units instead? Make a separate array X of x-values whose units are in nm. This way, when you plot the data it is already in the correct format! Just make sure you add a xlabel to indicate the units (which should always be done anyways).

from pylab import *

# Generate random test data in your range
N = 200
epsilon = 10**(-9.0)
X = epsilon*(50*random(N) + 1)
Y = random(N)

# X2 now has the "units" of nanometers by scaling X
X2 = (1/epsilon) * X


xlim(1, 50)


enter image description here

MySQL case sensitive query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'

How can I connect to a Tor hidden service using cURL in PHP?

TL;DR: Set CURLOPT_PROXYTYPE to use CURLPROXY_SOCKS5_HOSTNAME if you have a modern PHP, the value 7 otherwise, and/or correct the CURLOPT_PROXY value.

As you correctly deduced, you cannot resolve .onion domains via the normal DNS system, because this is a reserved top-level domain specifically for use by Tor and such domains by design have no IP addresses to map to.

Using CURLPROXY_SOCKS5 will direct the cURL command to send its traffic to the proxy, but will not do the same for domain name resolution. The DNS requests, which are emitted before cURL attempts to establish the actual connection with the Onion site, will still be sent to the system's normal DNS resolver. These DNS requests will surely fail, because the system's normal DNS resolver will not know what to do with a .onion address unless it, too, is specifically forwarding such queries to Tor.

Instead of CURLPROXY_SOCKS5, you must use CURLPROXY_SOCKS5_HOSTNAME. Alternatively, you can also use CURLPROXY_SOCKS4A, but SOCKS5 is much preferred. Either of these proxy types informs cURL to perform both its DNS lookups and its actual data transfer via the proxy. This is required to successfully resolve any .onion domain.

There are also two additional errors in the code in the original question that have yet to be corrected by previous commenters. These are:

  • Missing semicolon at end of line 1.
  • The proxy address value is set to an HTTP URL, but its type is SOCKS; these are incompatible. For SOCKS proxies, the value must be an IP or domain name and port number combination without a scheme/protocol/prefix.

Here is the correct code in full, with comments to indicate the changes.

$url = 'http://jhiwjjlqpyawmpjx.onion/'; // Note the addition of a semicolon.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, ""); // Note the address here is just `IP:port`, not an HTTP URL.
$output = curl_exec($ch);
$curl_error = curl_error($ch);


You can also omit setting CURLOPT_PROXYTYPE entirely by changing the CURLOPT_PROXY value to include the socks5h:// prefix:

// Note no trailing slash, as this is a SOCKS address, not an HTTP URL.
curl_setopt(CURLOPT_PROXY, 'socks5h://');

Using "margin: 0 auto;" in Internet Explorer 8

Add <!doctype html> at the top of your HTML output.

Python error when trying to access list by index - "List indices must be integers, not str"

player['score'] is your problem. player is apparently a list which means that there is no 'score' element. Instead you would do something like:

name, score = player[0], player[1]
return name + ' ' + str(score)

Of course, you would have to know the list indices (those are the 0 and 1 in my example).

Something like player['score'] is allowed in python, but player would have to be a dict.

You can read more about both lists and dicts in the python documentation.

Best Way to read rss feed in .net Using C#

This is an old post, but to save people some time if you get here now like I did, I suggest you have a look at the CodeHollow.FeedReader package which supports a wider range of RSS versions, is easier to use and seems more robust.

Get the Selected value from the Drop down box in PHP

You have to give a name attribute on your <select /> element, and then use it from the $_POST or $_GET (depending on how you transmit data) arrays in PHP. Be sure to sanitize user input, though.

How to set image for bar button with swift?

Just choose Original image option when adding an image to assets in Xcode

enter image description here

Count rows with not empty value

You can define a custom function using Apps Script (Tools > Script editor) called for example numNonEmptyRows :

function numNonEmptyRows(range) {
  if (range && range.constructor === Array) {
    return{return a.join('')}).filter(Boolean).length
  else {
    return range ? 1 : 0;

And then use it in a cell like this =numNonEmptyRows(A23:C25) to count the number of non empty rows in the range A23:C25;

Create database from command line

Change the user to postgres :

su - postgres

Create User for Postgres

$ createuser testuser

Create Database

$ createdb testdb

Acces the postgres Shell

psql ( enter the password for postgressql)

Provide the privileges to the postgres user

$ alter user testuser with encrypted password 'qwerty';
$ grant all privileges on database testdb to testuser;

Initializing C dynamic arrays

p = {1,2,3} is wrong.

You can never use this:

int * p;
p = {1,2,3};

loop is right

int *p,i;
p = malloc(3*sizeof(int));
for(i = 0; i<3; ++i)
    p[i] = i;

Clicking a button within a form causes page refresh

You can try to prevent default handler:


<button ng-click="saveUser($event)">


$scope.saveUser = function (event) {
  // your code

How to return a list of keys from a Hash Map?

 for(int i=0;i<ytFiles.size();i++){

                    int key = ytFiles.keyAt(i);
                    Log.e("key", String.valueOf(key));
                    String format = ytFiles.get(key).getFormat().toString();
                    String url = ytFiles.get(key).getUrl();

you can get key by method keyat and you have to pass the index then it will return key at that particular index. this loop will get all the key

Writing a dictionary to a text file?

If you want a dictionary you can import from a file by name, and also that adds entries that are nicely sorted, and contains strings you want to preserve, you can try this:

data = {'A': 'a', 'B': 'b', }

with open('','w') as file:
    file.write("dictionary_name = { \n")
    for k in sorted (data.keys()):
        file.write("'%s':'%s', \n" % (k, data[k]))

Then to import:

from file import dictionary_name

nodejs get file name from absolute path?

var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.parse(filepath).name;
// returns

Above code returns the name of the file without extension, if you need the name with extention use

var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.basename(filepath);
// returns

LINQ Where with AND OR condition

Well, you're going to have to check for null somewhere. You could do something like this:

from item in db.vw_Dropship_OrderItems
         where (listStatus == null || listStatus.Contains(item.StatusCode)) 
            && (listMerchants == null || listMerchants.Contains(item.MerchantId))
         select item;

Which rows are returned when using LIMIT with OFFSET in MySQL?

OFFSET is nothing but a keyword to indicate starting cursor in table

SELECT column FROM table LIMIT 18 OFFSET 8 -- fetch 18 records, begin with record 9 (OFFSET 8)

you would get the same result form

SELECT column FROM table LIMIT 8, 18

visual representation (R is one record in the table in some order)

 OFFSET        LIMIT          rest of the table
 __||__   _______||_______   __||__
/      \ /                \ /
             your result

How to do a non-greedy match in grep?

You're looking for a non-greedy (or lazy) match. To get a non-greedy match in regular expressions you need to use the modifier ? after the quantifier. For example you can change .* to .*?.

By default grep doesn't support non-greedy modifiers, but you can use grep -P to use the Perl syntax.

Google Maps API OVER QUERY LIMIT per second limit

The geocoder has quota and rate limits. From experience, you can geocode ~10 locations without hitting the query limit (the actual number probably depends on server loading). The best solution is to delay when you get OVER_QUERY_LIMIT errors, then retry. See these similar posts:

Is there an equivalent for var_dump (PHP) in Javascript?

If you are using firefox then the firebug plug-in console is an excellent way of examining objects


Alternatively you can loop through the properties (including methods) like this:

for (property in object) {
    // do what you want with property, object[property].value

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

You can use it like this, I hope you wont get outdated message now.

  <td valign="top" style="white-space:nowrap" width="237">

As pointed by @ThiefMaster it is recommended to put width and valign to CSS (note: CSS calls it vertical-align).


<td style="white-space:nowrap; width:237px; vertical-align:top;">

2) We can make a CSS class like this, it is more elegant way

In style section


In HTML section

<td class="td-some-name">

How to get data out of a Node.js http get request

from learnyounode:

var http = require('http')
var bl = require('bl')

http.get(process.argv[2], function (response) {
    response.pipe(bl(function (err, data) {
        if (err)
            return console.error(err)
        data = data.toString()

How to trigger a click on a link using jQuery

We can do it in many ways...

CASE - 1

We can use trigger like this : $("#myID").trigger("click");

CASE - 2

We can use click() function like this : $("#myID").click();

CASE - 3

If we want to write function on programmatically click then..

$("#myID").click(function() {
// Do here whatever you want

CASE - 4

// Triggering a native browser event using the simulate plugin
$("#myID").simulate( "click" );  

Also you can refer this :

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

    <h:commandLink value="link text" action="destination" />

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

    <h:commandLink value="link text" action="destination?faces-redirect=true" />

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

Take n rows from a spark dataframe and pass to toPandas()

Try it:

def showDf(df, count=None, percent=None, maxColumns=0):
    if (df == None): return
    import pandas
    from IPython.display import display
    pandas.set_option('display.encoding', 'UTF-8')
    # Pandas dataframe
    dfp = None
    # maxColumns param
    if (maxColumns >= 0):
        if (maxColumns == 0): maxColumns = len(df.columns)
        pandas.set_option('display.max_columns', maxColumns)
    # count param
    if (count == None and percent == None): count = 10 # Default count
    if (count != None):
        count = int(count)
        if (count == 0): count = df.count()
        pandas.set_option('display.max_rows', count)
        dfp = pandas.DataFrame(df.head(count), columns=df.columns)
    # percent param
    elif (percent != None):
        percent = float(percent)
        if (percent >=0.0 and percent <= 1.0):
            import datetime
            now =
            seed = long(now.strftime("%H%M%S"))
            dfs = df.sample(False, percent, seed)
            count = df.count()
            pandas.set_option('display.max_rows', count)
            dfp = dfs.toPandas()    

Examples of usages are:

# Shows the ten first rows of the Spark dataframe
showDf(df, 10)
showDf(df, count=10)

# Shows a random sample which represents 15% of the Spark dataframe
showDf(df, percent=0.15) 

How can I stop python.exe from closing immediately after I get an output?

Auxiliary answer

Manoj Govindan's answer is correct but I saw that comment:

Run it from the terminal.

And got to thinking about why this is so not obvious to windows users and realized it's because CMD.EXE is such a poor excuse for a shell that it should start with:

Windows command interpreter copyright 1999 Microsoft
Mein Gott!! Whatever you do, don't use this!!

Which leads me to point at

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

The simplest code would be like, keep your properties files into resources folder, either in src/main/resource or in src/test/resource. Then use below code to read properties files:

public class Utilities {
    static {
        rb1 = ResourceBundle.getBundle("fileNameWithoutExtension"); 
              // do not use .properties extension
    public static String getConfigProperties(String keyString) {
        return rb1.getString(keyString);

Press TAB and then ENTER key in Selenium WebDriver

Using Java:

private WebDriver driver = new FirefoxDriver();
WebElement element = driver.findElement("<ElementID>"));//Enter ID for the element. You can use Name, xpath, cssSelector whatever you like

Using C#:

private IWebDriver driver = new FirefoxDriver();
IWebElement element = driver.FindElement(By.Name("q"));

Skipping every other element after the first

items = range(10)
print items
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print items[1::2] # every other item after the second; slight variation
>>> [1, 3, 5, 7, 9]

How do I pass multiple ints into a vector at once?

You can do it with initializer list:

std::vector<unsigned int> array;

// First argument is an iterator to the element BEFORE which you will insert:
// In this case, you will insert before the end() iterator, which means appending value
// at the end of the vector.
array.insert(array.end(), { 1, 2, 3, 4, 5, 6 });