Programs & Examples On #Flex datagrid

Grid component, part of Adobe Flex framework.

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

This blog post explains very well:

(just replace 9.X by your version. e.g: 9.6)

A. If installed PostgreSQL with homebrew, enter brew uninstall postgresql

B. If you used the EnterpriseDB installer, follow the following step.

Run the uninstaller on terminal window: sudo /Library/PostgreSQL/9.X/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh

C. If installed with Postgres Installer, do:

open /Library/PostgreSQL/9.X/uninstall-postgresql.app

Remove the PostgreSQL and data folders. The Wizard will notify you that these were not removed.

sudo rm -rf /Library/PostgreSQL

Remove the ini file:

sudo rm /etc/postgres-reg.ini

Remove the PostgreSQL user using System Preferences -> Users & Groups.

Unlock the settings panel by clicking on the padlock and entering your password. Select the PostgreSQL user and click on the minus button. Restore your shared memory settings: sudo rm /etc/sysctl.conf

ImportError: No module named 'pygame'

I was trying to figure this out for at least an hour. And you're right the problem is that the installation files are all for 32 bit.

Luckily I found a link to the 64 pygame download! Here it is: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame

Just pick the corresponding version according to your python version and it should work like magic. The installation feature will bring you to a bright-blue screen as the installation (at this point you know that the installation is correct for you.

Then go into the Python IDLE and type "import pygame" and you should not get any more errors.

Props go to @yuvi who shared the link with StackOverflow.

Select2 open dropdown on focus

For me using Select2.full.js Version 4.0.3 none of the above solutions was working the way it should be. So I wrote a combination of the solutions above. First of all I modified Select2.full.js to transfer the internal focus and blur events to jquery events as "Thomas Molnar" did in his answer.

EventRelay.prototype.bind = function (decorated, container, $container) {
    var self = this;
    var relayEvents = [
      'open', 'opening',
      'close', 'closing',
      'select', 'selecting',
      'unselect', 'unselecting',
      'focus', 'blur'
    ];

And then I added the following code to handle focus and blur and focussing the next element

$("#myId").select2(   ...   ).one("select2:focus", select2Focus).on("select2:blur", function ()
{
    var select2 = $(this).data('select2');
    if (select2.isOpen() == false)
    {
        $(this).one("select2:focus", select2Focus);
    }
}).on("select2:close", function ()
{
    setTimeout(function ()
    {
        // Find the next element and set focus on it.
        $(":focus").closest("tr").next("tr").find("select:visible,input:visible").focus();            
    }, 0);
});
function select2Focus()
{
    var select2 = $(this).data('select2');
    setTimeout(function() {
        if (!select2.isOpen()) {
            select2.open();
        }
    }, 0);  
}

How to get the mobile number of current sim card in real device?

As many said:

String phoneNumber = TelephonyManager.getDefault().getLine1Number();

The availability depends strictly on the carrier and the way the number is encoded on the SIM card. If it is hardcoded by the company that makes the SIMs or by the mobile carrier itself. This returns the same as in Settings->about phone.

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

Those slanted double quotes are not ASCII characters. The error message is misleading about them being 'multi-byte'.

SELECT *, COUNT(*) in SQLite

If you want to count the number of records in your table, simply run:

    SELECT COUNT(*) FROM your_table;

Batch file. Delete all files and folders in a directory

I just put this together from what morty346 posted:

set folder="C:\test"
IF EXIST "%folder%" (
    cd /d %folder%
    for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
)

It adds a quick check that the folder defined in the variable exists first, changes directory to the folder, and deletes the contents.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

As @swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.

Connection Pooling

Hibernate itself admits that its connection pooling strategy is minimal

Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.
As stated in Reference : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

I personally use C3P0. however there are other alternatives available including DBCP.
Check out

Below is a minimal configuration of C3P0 used in my application:

<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">1</property> 
<property name="c3p0.idle_test_period">100</property> <!-- seconds --> 
<property name="c3p0.max_size">100</property> 
<property name="c3p0.max_statements">0</property> 
<property name="c3p0.min_size">10</property> 
<property name="c3p0.timeout">1800</property> <!-- seconds --> 

By default, pools will never expire Connections. If you wish Connections to be expired over time in order to maintain "freshness", set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool. maxConnectionAge forces the pool to cull any Connections that were acquired from the database more than the set number of seconds in the past.
As stated in Reference : http://www.mchange.com/projects/c3p0/index.html#managing_pool_size

Edit:
I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier. The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:

Create a file “c3p0.properties” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)

# c3p0.properties
c3p0.testConnectionOnCheckout=true

With this configuration each connection is tested before being used. It however might affect the performance of the site.

Breaking up long strings on multiple lines in Ruby without stripping newlines

Maybe this is what you're looking for?

string = "line #1"\
         "line #2"\
         "line #3"

p string # => "line #1line #2line #3"

Send data through routing paths in Angular

Best I found on internet for this is ngx-navigation-with-data. It is very simple and good for navigation the data from one component to another component. You have to just import the component class and use it in very simple way. Suppose you have home and about component and want to send data then

HOME COMPONENT

import { Component, OnInit } from '@angular/core';
import { NgxNavigationWithDataComponent } from 'ngx-navigation-with-data';

@Component({
 selector: 'app-home',
 templateUrl: './home.component.html',
 styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

constructor(public navCtrl: NgxNavigationWithDataComponent) { }

 ngOnInit() {
 }

 navigateToABout() {
  this.navCtrl.navigate('about', {name:"virendta"});
 }

}

ABOUT COMPONENT

import { Component, OnInit } from '@angular/core';
import { NgxNavigationWithDataComponent } from 'ngx-navigation-with-data';

@Component({
 selector: 'app-about',
 templateUrl: './about.component.html',
 styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {

 constructor(public navCtrl: NgxNavigationWithDataComponent) {
  console.log(this.navCtrl.get('name')); // it will console Virendra
  console.log(this.navCtrl.data); // it will console whole data object here
 }

 ngOnInit() {
 }

}

For any query follow https://www.npmjs.com/package/ngx-navigation-with-data

Comment down for help.

Android WebView style background-color:transparent ignored on android 2.2

This worked for me. try setting the background color after the data is loaded. for that setWebViewClient on your webview object like:

    webView.setWebViewClient(new WebViewClient(){

        @Override
        public void onPageFinished(WebView view, String url)
        {
            super.onPageFinished(view, url);
            webView.setBackgroundColor(Color.BLACK);
        }
    });

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

This is how I solved it, You can follow step by step here:

MongoDB Steps:

  • Download the latest 64-bit MSI version of MongoDB for Windows.

  • Run the installer (.msi file)

  • Add it to your PATH of environment variables. it Should be from:
    C:\Program Files\MongoDB\Server\3.0\bin

now Create a “\data\db” folder in C:/ which is used by mongodb to store all data. You should have this folder:

C:\data\db

Note: This is the default directory location expected by mongoDB, don’t create anywhere else

.

Finally, open command prompt and type:

>> mongod

You should see it asking for permissions (allow it) and then listen to a port. After that is done, open another command prompt, leaving the previous one running the server.

Type in the new command prompt

>> mongo

You should see it display the version and connect to a test database.

This proves successful install!=)

Reference link

How to make Unicode charset in cmd.exe by default?

Open an elevated Command Prompt (run cmd as administrator). query your registry for available TT fonts to the console by:

    REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"

You'll see an output like :

    0    REG_SZ    Lucida Console
    00    REG_SZ    Consolas
    936    REG_SZ    *???
    932    REG_SZ    *MS ????

Now we need to add a TT font that supports the characters you need like Courier New, we do this by adding zeros to the string name, so in this case the next one would be "000" :

    REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"

Now we implement UTF-8 support:

    REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f

Set default font to "Courier New":

    REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f

Set font size to 20 :

    REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f

Enable quick edit if you like :

    REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f

Maven not found in Mac OSX mavericks

brew install maven

Please ensure that you've installed the latest Xcode and Command Line tools.

xcode-select --install

What is getattr() exactly and how do I use it?

For me, getattr is easiest to explain this way:

It allows you to call methods based on the contents of a string instead of typing the method name.

For example, you cannot do this:

obj = MyObject()
for x in ['foo', 'bar']:
    obj.x()

because x is not of the type builtin, but str. However, you CAN do this:

obj = MyObject()
for x in ['foo', 'bar']:
    getattr(obj, x)()

It allows you to dynamically connect with objects based on your input. I've found it useful when dealing with custom objects and modules.

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

Barcode scanner for mobile phone for Website in form

Check this out: http://qrdroid.com/web-masters.php

You can create a link in your web form, something like:

http://qrdroid.com/scan?q=http://www.your-site.com/your-form.php?code={CODE}

When somebody clicks that link, an app to scan the code will be opened. After the user scans the code, http://www.your-site.com/your-form.php?code={CODE} will be automatically called. You can then make your-form.php read the parameter code to prepopulate the field.

How to use the CancellationToken property?

You have to pass the CancellationToken to the Task, which will periodically monitors the token to see whether cancellation is requested.

// CancellationTokenSource provides the token and have authority to cancel the token
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;  

// Task need to be cancelled with CancellationToken 
Task task = Task.Run(async () => {     
  while(!token.IsCancellationRequested) {
      Console.Write("*");         
      await Task.Delay(1000);
  }
}, token);

Console.WriteLine("Press enter to stop the task"); 
Console.ReadLine(); 
cancellationTokenSource.Cancel(); 

In this case, the operation will end when cancellation is requested and the Task will have a RanToCompletion state. If you want to be acknowledged that your task has been cancelled, you have to use ThrowIfCancellationRequested to throw an OperationCanceledException exception.

Task task = Task.Run(async () =>             
{                 
    while (!token.IsCancellationRequested) {
         Console.Write("*");                      
         await Task.Delay(1000);                
    }           
    token.ThrowIfCancellationRequested();               
}, token)
.ContinueWith(t =>
 {
      t.Exception?.Handle(e => true);
      Console.WriteLine("You have canceled the task");
 },TaskContinuationOptions.OnlyOnCanceled);  
 
Console.WriteLine("Press enter to stop the task");                 
Console.ReadLine();                 
cancellationTokenSource.Cancel();                 
task.Wait(); 

Hope this helps to understand better.

Package doesn't exist error in intelliJ

In case you're facing very weird "unable to resolve java, sun packages problem", try the following:

  1. Open Project Structure and change Project SDK to another version, example: java 8 -> 9; 11->13, etc, and wait until it re-index all jdk's jars. Switch between jdks with same version may not work! (Ex: jetbrains jdk11 -> openjdk 11)
  2. Open a new project (or create a empty one); pause new project's indexing; close the old one; start indexing; open the old project and pause the new project's indexing and wait.

What is the difference between logical data model and conceptual data model?

These terms are unfortunately overloaded with several possible definitions. According to the ANSI-SPARC "three schema" model for instance, the Conceptual Schema or Conceptual Model consists of the set of objects in a database (tables, views, etc) in contrast to the External Schema which are the objects that users see.

In the data management professions and especially among data modellers / architects, the term Conceptual Model is frequently used to mean a semantic model whereas the term Logical Model is used to mean a preliminary or virtual database design. This is probably the usage you are most likely to come across in the workplace.

In academic usage and when describing DBMS architectures however, the Logical level means the database objects (tables, views, tables, keys, constraints, etc), as distinct from the Physical level (files, indexes, storage). To confuse things further, in the workplace the term Physical model is often used to mean the design as implemented or planned for implementation in an actual database. That may include both "physical" and "logical" level constructs (both tables and indexes for example).

When you come across any of these terms you really need to seek clarification on what is being described unless the context makes it obvious.

For a discussion of these differences, check out Data Modelling Essentials by Simsion and Witt for example.

How do I test axios in Jest?

I used axios-mock-adapter. In this case the service is described in ./chatbot. In the mock adapter you specify what to return when the API endpoint is consumed.

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';

describe('Chatbot', () => {
    it('returns data when sendMessage is called', done => {
        var mock = new MockAdapter(axios);
        const data = { response: true };
        mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);

        chatbot.sendMessage(0, 'any').then(response => {
            expect(response).toEqual(data);
            done();
        });
    });
});

You can see it the whole example here:

Service: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js

Test: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js

What is the size of ActionBar in pixels?

On my Galaxy S4 having > 441dpi > 1080 x 1920 > Getting Actionbar height with getResources().getDimensionPixelSize I got 144 pixels.

Using formula px = dp x (dpi/160), I was using 441dpi, whereas my device lies
in the category 480dpi. so putting that confirms the result.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved

Try the following steps:

  1. Make sure you have connectivity (you can browse) (This kind of error is usually due to connectivity with Internet)

  2. Download Maven and unzip it

  3. Create a JAVA_HOME System Variable

  4. Create an M2_HOME System Variable

  5. Add %JAVA_HOME%\bin;%M2_HOME%\bin; to your PATH variable

  6. Open a command window cmd. Check: mvn -v

  7. If you have a proxy, you will need to configure it

http://maven.apache.org/guides/mini/guide-proxies.html

  1. Make sure you have .m2/repository (erase all the folders and files below)

  2. If you are going to use Eclipse, You will need to create the settings.xml

Maven plugin in Eclipse - Settings.xml file is missing

You can see more detail in

http://maven.apache.org/ref/3.2.5/maven-settings/settings.html

Finding absolute value of a number without using Math.abs()

-num will equal to num for Integer.MIN_VALUE as

 Integer.MIN_VALUE =  Integer.MIN_VALUE * -1

How can I deploy an iPhone application from Xcode to a real iPhone device?

I was going through the Apple Developer last night and there in the Provisioning Certificate I found something like - "Signing Team Members". I think there is a way to add team members to the paid profile. You can just ask to the App Id Owner(paid one) to add you as a team member. I am not sure. Still searching on that.

Start HTML5 video at a particular position when loading?

WITHOUT USING JAVASCRIPT

Just add #t=[(start_time), (end_time)] to the end of your media URL. The only setback (if you want to see it that way) is you'll need to know how long your video is to indicate the end time. Example:

<video>
    <source src="splash.mp4#t=10,20" type="video/mp4">
</video>

Notes: Not supported in IE

How to set DOM element as the first child?

I think you're looking for the .prepend function in jQuery. Example code:

$("#E").prepend("<p>Code goes here, yo!</p>");

How to create a string with format?

let str = "\(INT_VALUE), \(FLOAT_VALUE), \(DOUBLE_VALUE), \(STRING_VALUE)"

Update: I wrote this answer before Swift had String(format:) added to it's API. Use the method given by the top answer.

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

By converting the matrix to array by using

n12 = np.squeeze(np.asarray(n2))

X12 = np.squeeze(np.asarray(x1))

solved the issue.

How to set child process' environment variable in Makefile

I only needed the environment variables locally to invoke my test command, here's an example setting multiple environment vars in a bash shell, and escaping the dollar sign in make.

SHELL := /bin/bash

.PHONY: test tests
test tests:
    PATH=./node_modules/.bin/:$$PATH \
    JSCOVERAGE=1 \
    nodeunit tests/

How to install gem from GitHub source?

Bundler allows you to use gems directly from git repositories. In your Gemfile:

# Use the http(s), ssh, or git protocol
gem 'foo', git: 'https://github.com/dideler/foo.git'
gem 'foo', git: '[email protected]:dideler/foo.git'
gem 'foo', git: 'git://github.com/dideler/foo.git'

# Specify a tag, ref, or branch to use
gem 'foo', git: '[email protected]:dideler/foo.git', tag: 'v2.1.0'
gem 'foo', git: '[email protected]:dideler/foo.git', ref: '4aded'
gem 'foo', git: '[email protected]:dideler/foo.git', branch: 'development'

# Shorthand for public repos on GitHub (supports all the :git options)
gem 'foo', github: 'dideler/foo'

For more info, see https://bundler.io/v2.0/guides/git.html

Can I open a dropdownlist using jQuery

It is not possible for javascript to "click" on an element (u can trigger the attached onclick event, but you can't literally click it)

To view all the items in the list, make the list a multiple list and increase its size, like such:

<select id="countries" multiple="multiple" size="10">
<option value="1">Country</option>
</select>

Can I force pip to reinstall the current version?

--force-reinstall

doesn't appear to force reinstall using python2.7 with pip-1.5

I've had to use

--no-deps --ignore-installed

Force “landscape” orientation mode

screen.orientation.lock('landscape');

Will force it to change to and stay in landscape mode. Tested on Nexus 5.

http://www.w3.org/TR/screen-orientation/#examples

How to negate a method reference predicate

If you're using Spring Boot (2.0.0+) you can use:

import org.springframework.util.StringUtils;

...
.filter(StringUtils::hasLength)
...

Which does: return (str != null && !str.isEmpty());

So it will have the required negation effect for isEmpty

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

Syntactic sugar, makes it more obvious to the casual reader that the join isn't an inner one.

How to hide Table Row Overflow?

Need to specify two attributes, table-layout:fixed on table and white-space:nowrap; on the cells. You also need to move the overflow:hidden; to the cells too

table { width:250px;table-layout:fixed; }
table tr { height:1em;  }
td { overflow:hidden;white-space:nowrap;  } 

Here's a Demo . Tested in Firefox 3.5.3 and IE 7

Angular JS Uncaught Error: [$injector:modulerr]

The problem was caused by missing inclusion of ngRoute module. Since version 1.1.6 it's a separate part:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>

var app = angular.module('myapp', ['ngRoute']);

This is getting reference from: AngularJS 1.2 $injector:modulerr David answer

How can I display a JavaScript object?

NB: In these examples, yourObj defines the object you want to examine.

First off my least favorite yet most utilized way of displaying an object:

This is the defacto way of showing the contents of an object

console.log(yourObj)

will produce something like : enter image description here

I think the best solution is to look through the Objects Keys, and then through the Objects Values if you really want to see what the object holds...

console.log(Object.keys(yourObj));
console.log(Object.values(yourObj));

It will output something like : enter image description here (pictured above: the keys/values stored in the object)

There is also this new option if you're using ECMAScript 2016 or newer:

Object.keys(yourObj).forEach(e => console.log(`key=${e}  value=${yourObj[e]}`));

This will produce neat output : enter image description here The solution mentioned in a previous answer: console.log(yourObj) displays too many parameters and is not the most user friendly way to display the data you want. That is why I recommend logging keys and then values separately.

Next up :

console.table(yourObj)

Someone in an earlier comment suggested this one, however it never worked for me. If it does work for someone else on a different browser or something, then kudos! Ill still put the code here for reference! Will output something like this to the console : enter image description here

Check play state of AVPlayer

For Swift:

AVPlayer:

let player = AVPlayer(URL: NSURL(string: "http://www.sample.com/movie.mov"))
if (player.rate != 0 && player.error == nil) {
   println("playing")
}

Update:
player.rate > 0 condition changed to player.rate != 0 because if video is playing in reverse it can be negative thanks to Julian for pointing out.
Note: This might look same as above(Maz's) answer but in Swift '!player.error' was giving me a compiler error so you have to check for error using 'player.error == nil' in Swift.(because error property is not of 'Bool' type)

AVAudioPlayer:

if let theAudioPlayer =  appDelegate.audioPlayer {
   if (theAudioPlayer.playing) {
       // playing
   }
}

AVQueuePlayer:

if let theAudioQueuePlayer =  appDelegate.audioPlayerQueue {
   if (theAudioQueuePlayer.rate != 0 && theAudioQueuePlayer.error == nil) {
       // playing
   }
}

Condition within JOIN or WHERE

I typically see performance increases when filtering on the join. Especially if you can join on indexed columns for both tables. You should be able to cut down on logical reads with most queries doing this too, which is, in a high volume environment, a much better performance indicator than execution time.

I'm always mildly amused when someone shows their SQL benchmarking and they've executed both versions of a sproc 50,000 times at midnight on the dev server and compare the average times.

Java regex capturing groups indexes

Parenthesis () are used to enable grouping of regex phrases.

The group(1) contains the string that is between parenthesis (.*) so .* in this case

And group(0) contains whole matched string.

If you would have more groups (read (...) ) it would be put into groups with next indexes (2, 3 and so on).

How to query a MS-Access Table from MS-Excel (2010) using VBA

Sub Button1_Click()
Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\Documents and Settings\XXXXXX\My Documents\my_access_table.accdb"
    strSql = "SELECT Count(*) FROM mytable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.Fields(0) & " rows in MyTable"

    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing

End Sub

Convert js Array() to JSon object for use with JQuery .ajax

Don't make it an Array if it is not an Array, make it an object:

var saveData = {};
saveData.a = 2;
saveData.c = 1;

// equivalent to...
var saveData = {a: 2, c: 1}

// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;

Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.

How to register ASP.NET 2.0 to web server(IIS7)?

The system I was working on is Windows Server 2008 Standard with IIS 7 (I guess that my experience will apply for all Windows systems of the same age).

Running

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

SEEMED to work, as

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -lv

showed the .Net framework v4 registered with IIS.

But, running the same for .Net v2, namely

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ir

did NOT result in

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -lv

showing the framework registered.

(And, for me, the installer for Kofax Capture Network Server was still missing ASP.NET.)

The solution was:

  • Open Server Manager
  • Go to Roles/Web Server (IIS)
  • Push Add Role Services
  • check ASP.NET under Application Development (and press Install)

After that, aspnet_regiis.exe -lv (either version) shows the framework registered. (And the Kofax installer was also happy and worked.)

Ignore files that have already been committed to a Git repository

To remove just a few specific files from being tracked:

git update-index --assume-unchanged path/to/file

If ever you want to start tracking it again:

git update-index --no-assume-unchanged path/to/file                      

What is the total amount of public IPv4 addresses?

According to Reserved IP addresses there are 588,514,304 reserved addresses and since there are 4,294,967,296 (2^32) IPv4 addressess in total, there are 3,706,452,992 public addresses.

And too many addresses in this post.

Oracle PL/SQL : remove "space characters" from a string

Since you're comfortable with regular expressions, you probably want to use the REGEXP_REPLACE function. If you want to eliminate anything that matches the [:space:] POSIX class

REGEXP_REPLACE( my_value, '[[:space:]]', '' )


SQL> ed
Wrote file afiedt.buf

  1  select '|' ||
  2         regexp_replace( 'foo ' || chr(9), '[[:space:]]', '' ) ||
  3         '|'
  4*   from dual
SQL> /

'|'||
-----
|foo|

If you want to leave one space in place for every set of continuous space characters, just add the + to the regular expression and use a space as the replacement character.

with x as (
  select 'abc 123  234     5' str
    from dual
)
select regexp_replace( str, '[[:space:]]+', ' ' )
  from x

How to add a bot to a Telegram Group?

Edit: now there is yet an easier way to do this - when creating your group, just mention the full bot name (eg. @UniversalAgent1Bot) and it will list it as you type. Then you can just tap on it to add it.

Old answer:

  1. Create a new group from the menu. Don't add any bots yet
  2. Find the bot (for instance you can go to Contacts and search for it)
  3. Tap to open
  4. Tap the bot name on the top bar. Your page becomes like this: Telegram bot settings
  5. Now, tap the triple ... and you will get the Add to Group button: Adding the bot
  6. Now select your group and add the bot - and confirm the addition

Android: Access child views from a ListView

int position = 0;
listview.setItemChecked(position, true);
View wantedView = adapter.getView(position, null, listview);

How to check "hasRole" in Java Code with Spring Security?

you can use the isUserInRole method of the HttpServletRequest object.

something like:

public String createForm(HttpSession session, HttpServletRequest request,  ModelMap   modelMap) {


    if (request.isUserInRole("ROLE_ADMIN")) {
        // code here
    }
}

How can I check if two segments intersect?

for segments AB and CD, find the slope of CD

slope=(Dy-Cy)/(Dx-Cx)

extend CD over A and B, and take the distance to CD going straight up

dist1=slope*(Cx-Ax)+Ay-Cy
dist2=slope*(Dx-Ax)+Ay-Dy

check if they are on opposite sides

return dist1*dist2<0

Search All Fields In All Tables For A Specific Value (Oracle)

Borrowing, slightly enhancing and simplifying from this Blog post the following simple SQL statement seems to do the job quite well:

SELECT DISTINCT (:val) "Search Value", TABLE_NAME "Table", COLUMN_NAME "Column"
FROM cols,
     TABLE (XMLSEQUENCE (DBMS_XMLGEN.GETXMLTYPE(
       'SELECT "' || COLUMN_NAME || '" FROM "' || TABLE_NAME || '" WHERE UPPER("'
       || COLUMN_NAME || '") LIKE UPPER(''%' || :val || '%'')' ).EXTRACT ('ROWSET/ROW/*')))
ORDER BY "Table";

Drop columns whose name contains a specific string from pandas DataFrame

This can be done neatly in one line with:

df = df.drop(df.filter(regex='Test').columns, axis=1)

MongoDB distinct aggregation

SQL Query: (group by & count of distinct)

select city,count(distinct(emailId)) from TransactionDetails group by city;

Equivalent mongo query would look like this:

db.TransactionDetails.aggregate([ 
{$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}},
{$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} } 
]);

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

R memory management / cannot allocate vector of size n Mb

The simplest way to sidestep this limitation is to switch to 64 bit R.

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

installing steps for nltk (I had python3 (3.6.2) installed already in MAC OS X

sudo easy_install pip

use ignore installed option to ignore uninstalling previous version of six, else, it gives an error while uninstalling and does not movie forward

sudo pip3 install -U nltk --ignore-installed six

Check the installation of pip and python, use the '3' versions

which python python2 python3
which pip pip2 pip3

Check if NLTK is installed

python3
import nltk
nltk.__path__
['/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/nltk']

Install SSL certificate prior to installing the examples book, else we will certificate error while installing the examples

/Applications/Python\ 3.6/Install\ Certificates.command
python3 -m nltk.downloader book

That completed the installation successfully of nltk and nltk_ata for book examples

What's the idiomatic syntax for prepending to a short python list?

What's the idiomatic syntax for prepending to a short python list?

You don't usually want to repetitively prepend to a list in Python.

If it's short, and you're not doing it a lot... then ok.

list.insert

The list.insert can be used this way.

list.insert(0, x)

But this is inefficient, because in Python, a list is an array of pointers, and Python must now take every pointer in the list and move it down by one to insert the pointer to your object in the first slot, so this is really only efficient for rather short lists, as you ask.

Here's a snippet from the CPython source where this is implemented - and as you can see, we start at the end of the array and move everything down by one for every insertion:

for (i = n; --i >= where; )
    items[i+1] = items[i];

If you want a container/list that's efficient at prepending elements, you want a linked list. Python has a doubly linked list, which can insert at the beginning and end quickly - it's called a deque.

deque.appendleft

A collections.deque has many of the methods of a list. list.sort is an exception, making deque definitively not entirely Liskov substitutable for list.

>>> set(dir(list)) - set(dir(deque))
{'sort'}

The deque also has an appendleft method (as well as popleft). The deque is a double-ended queue and a doubly-linked list - no matter the length, it always takes the same amount of time to preprend something. In big O notation, O(1) versus the O(n) time for lists. Here's the usage:

>>> import collections
>>> d = collections.deque('1234')
>>> d
deque(['1', '2', '3', '4'])
>>> d.appendleft('0')
>>> d
deque(['0', '1', '2', '3', '4'])

deque.extendleft

Also relevant is the deque's extendleft method, which iteratively prepends:

>>> from collections import deque
>>> d2 = deque('def')
>>> d2.extendleft('cba')
>>> d2
deque(['a', 'b', 'c', 'd', 'e', 'f'])

Note that each element will be prepended one at a time, thus effectively reversing their order.

Performance of list versus deque

First we setup with some iterative prepending:

import timeit
from collections import deque

def list_insert_0():
    l = []
    for i in range(20):
        l.insert(0, i)

def list_slice_insert():
    l = []
    for i in range(20):
        l[:0] = [i]      # semantically same as list.insert(0, i)

def list_add():
    l = []
    for i in range(20):
        l = [i] + l      # caveat: new list each time

def deque_appendleft():
    d = deque()
    for i in range(20):
        d.appendleft(i)  # semantically same as list.insert(0, i)

def deque_extendleft():
    d = deque()
    d.extendleft(range(20)) # semantically same as deque_appendleft above

and performance:

>>> min(timeit.repeat(list_insert_0))
2.8267281929729506
>>> min(timeit.repeat(list_slice_insert))
2.5210217320127413
>>> min(timeit.repeat(list_add))
2.0641671380144544
>>> min(timeit.repeat(deque_appendleft))
1.5863927800091915
>>> min(timeit.repeat(deque_extendleft))
0.5352169770048931

The deque is much faster. As the lists get longer, I would expect a deque to perform even better. If you can use deque's extendleft you'll probably get the best performance that way.

How do I decode a URL parameter using C#?

string decodedUrl = Uri.UnescapeDataString(url)

or

string decodedUrl = HttpUtility.UrlDecode(url)

Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop:

private static string DecodeUrlString(string url) {
    string newUrl;
    while ((newUrl = Uri.UnescapeDataString(url)) != url)
        url = newUrl;
    return newUrl;
}

Integrate ZXing in Android Studio

From version 4.x, only Android SDK 24+ is supported by default, and androidx is required.

Add the following to your build.gradle file:

repositories {
    jcenter()
}

dependencies {
    implementation 'com.journeyapps:zxing-android-embedded:4.1.0'
    implementation 'androidx.appcompat:appcompat:1.0.2'
}

android {
    buildToolsVersion '28.0.3' // Older versions may give compile errors
}

Older SDK versions

For Android SDK versions < 24, you can downgrade zxing:core to 3.3.0 or earlier for Android 14+ support:

repositories {
    jcenter()
}

dependencies {
    implementation('com.journeyapps:zxing-android-embedded:4.1.0') { transitive = false }
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.zxing:core:3.3.0'
}

android {
    buildToolsVersion '28.0.3'
}

You'll also need this in your Android manifest:

<uses-sdk tools:overrideLibrary="com.google.zxing.client.android" />

Source : https://github.com/journeyapps/zxing-android-embedded

Netbeans how to set command line arguments in Java

For a Maven project using NetBeans 8.x:

  1. Click Run >> Set Project Configuration >> Customise
  2. Select Actions
  3. Select Run file via main()
  4. Set name/value pair to include the arguments.
  5. Click OK

An example name/value pair might resemble:

javax.persistence.jdbc.password=PASSWORD

Then run your project:

  1. Open and focus the Java class that includes main(...).
  2. Press F6 to run the program.

The command line parameters should appear in the Run window.

Note that to obtain the value form with the program, use System.getProperty().

Additional actions for Test file, Run project, and other ways to run the application can have arguments defined. Repeat the steps above for the different actions to accomplish this task.

How to remove elements/nodes from angular.js array

My items have unique id's. I am deleting one by filtering the model with angulars $filter service:

var myModel = [{id:12345, ...},{},{},...,{}];
...
// working within the item
function doSthWithItem(item){
... 
  myModel = $filter('filter')(myModel, function(value, index) 
    {return value.id !== item.id;}
  );
}

As id you could also use the $$hashKey property of your model items: $$hashKey:"object:91"

Code-first vs Model/Database-first

Database first approach example:

Without writing any code: ASP.NET MVC / MVC3 Database First Approach / Database first

And I think it is better than other approaches because data loss is less with this approach.

Build an iOS app without owning a mac?

Some cloud solutions exist, such as macincloud (not free)

What is __stdcall?

C or C++ itself do not define those identifiers. They are compiler extensions and stand for certain calling conventions. That determines where to put arguments, in what order, where the called function will find the return address, and so on. For example, __fastcall means that arguments of functions are passed over registers.

The Wikipedia Article provides an overview of the different calling conventions found out there.

Handlebars.js Else If

in handlebars first register a function like below

Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
    return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});

you can register more than one function . to add another function just add like below

Handlebars.registerHelper('calculate', function(operand1, operator, operand2) {
    let result;
    switch (operator) {
        case '+':
            result = operand1 + operand2;            
            break;
        case '-':
            result = operand1 - operand2;            
            break;
        case '*':
            result = operand1 * operand2;            
            break;
        case '/':
            result = operand1 / operand2;            
            break;
    }

    return Number(result);
});

and in HTML page just include the conditions like

    {{#ifEquals day "mon"}}
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      //html code goes here
    </html>
   {{else ifEquals day "sun"}}
    <html>
     //html code goes here
    </html>
   {{else}}
     //html code goes here
   {{/ifEquals}}

JS: Uncaught TypeError: object is not a function (onclick)

I was able to figure it out by following the answer in this thread: https://stackoverflow.com/a/8968495/1543447

Basically, I renamed all values, function names, and element names to different values so they wouldn't conflict - and it worked!

HTML Drag And Drop On Mobile Devices

Jquery Touch Punch is great but what it also does is disable all the controls on the draggable div so to prevent this you have to alter the lines... (at the time of writing - line 75)

change

if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])){

to read

if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0]) || event.originalEvent.target.localName === 'textarea'
        || event.originalEvent.target.localName === 'input' || event.originalEvent.target.localName === 'button' || event.originalEvent.target.localName === 'li'
        || event.originalEvent.target.localName === 'a'
        || event.originalEvent.target.localName === 'select' || event.originalEvent.target.localName === 'img') {

add as many ors as you want for each of the elements you want to 'unlock'

Hope that helps someone

String.Replace ignoring case

You could use a Regex and perform a case insensitive replace:

class Program
{
    static void Main()
    {
        string input = "hello WoRlD";
        string result = 
           Regex.Replace(input, "world", "csharp", RegexOptions.IgnoreCase);
        Console.WriteLine(result); // prints "hello csharp"
    }
}

How to execute an .SQL script file using c#

This Works on Framework 4.0 or Higher. Supports "GO". Also show the error message, line, and sql command.

using System.Data.SqlClient;

        private bool runSqlScriptFile(string pathStoreProceduresFile, string connectionString)
    {
        try
        {
            string script = File.ReadAllText(pathStoreProceduresFile);

            // split script on GO command
            System.Collections.Generic.IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$",
                                     RegexOptions.Multiline | RegexOptions.IgnoreCase);
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                foreach (string commandString in commandStrings)
                {
                    if (commandString.Trim() != "")
                    {
                        using (var command = new SqlCommand(commandString, connection))
                        {
                        try
                        {
                            command.ExecuteNonQuery();
                        }
                        catch (SqlException ex)
                        {
                            string spError = commandString.Length > 100 ? commandString.Substring(0, 100) + " ...\n..." : commandString;
                            MessageBox.Show(string.Format("Please check the SqlServer script.\nFile: {0} \nLine: {1} \nError: {2} \nSQL Command: \n{3}", pathStoreProceduresFile, ex.LineNumber, ex.Message, spError), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return false;
                        }
                    }
                    }
                }
                connection.Close();
            }
        return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return false;
        }
    }

How to split the screen with two equal LinearLayouts?

To Split a layout to equal parts

Use Layout Weights. Keep in mind that it is important to set layout_width as 0dp on children to make it work as intended.

on parent layout:

  1. Set weightSum of parent Layout as 1 (android:weightSum="1")

on the child layout:

  1. Set layout_width as 0dp (android:layout_width="0dp")
  2. Set layout_weight as 0.5 [half of weight sum fr equal two] (android:layout_weight="0.5")


To split layout to three equal parts:

  • parent: weightSum 3
  • child: layout_weight: 1

To split layout to four equal parts:

  • parent: weightSum 1
  • child: layout_weight: 0.25

To split layout to n equal parts:

  • parent: weightSum n
  • child: layout_weight: 1


Below is an example layout for splitting layout to two equal parts.

<LinearLayout
    android:id="@+id/layout_top"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="1">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:orientation="vertical">

        <TextView .. />

        <EditText .../>

    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:orientation="vertical">

        <TextView ../>

        <EditText ../>

    </LinearLayout>

</LinearLayout>

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

Mysqli makes use of object oriented programming. Try using this approach instead:

function dbCon() {
        if($mysqli = new mysqli('$hostname','$username','$password','$databasename')) return $mysqli; else return false;
}

if(!dbCon())
exit("<script language='javascript'>alert('Unable to connect to database')</script>");
else $con=dbCon();

if (isset($_GET['part'])){
    $partid = $_GET['part'];
    $sql = "SELECT * 
        FROM $usertable 
        WHERE PartNumber = $partid";

    $result=$con->query($sql_query);
    $row = $result->fetch_assoc();

    $partnumber = $partid;
    $nsn = $row["NSN"];
    $description = $row["Description"];
    $quantity = $row["Quantity"];
    $condition = $row["Conditio"];
}

Let me know if you have any questions, I could not test this code so you might need to tripple check it!

Why isn't .ico file defined when setting window's icon?

I'm using Visual Studio Code. To make "favicon.ico" work, you need to specify in which folder you are working.

  • You press ctrl + shift + p to open the terminal cmd+shift+p on OSX.
  • In the terminal, you type: cd + the path where you are working. For example: cd C:\User\Desktop\MyProject

How does one sum only those rows in excel not filtered out?

When you use autofilter to filter results, Excel doesn't even bother to hide them: it just sets the height of the row to zero (up to 2003 at least, not sure on 2007).

So the following custom function should give you a starter to do what you want (tested with integers, haven't played with anything else):

Function SumVis(r As Range)
    Dim cell As Excel.Range
    Dim total As Variant

    For Each cell In r.Cells
        If cell.Height <> 0 Then
            total = total + cell.Value
        End If
    Next

    SumVis = total
End Function

Edit:

You'll need to create a module in the workbook to put the function in, then you can just call it on your sheet like any other function (=SumVis(A1:A14)). If you need help setting up the module, let me know.

Why is sed not recognizing \t as a tab?

Not all versions of sed understand \t. Just insert a literal tab instead (press Ctrl-V then Tab).

Identifier is undefined

You may also be missing using namespace std;

How to add Headers on RESTful call using Jersey Client API

ClientResponse response = webResource
                               .queryParams(queryParams) //
                               .header("Content-Type", "application/json") //
                               .header("id", "123") //
                               .get(ClientResponse.class) //
;

Lua - Current time in milliseconds

Kevlar is correct.

An alternative to a custom DLL is Lua Alien

Why is Spring's ApplicationContext.getBean considered bad?

One of the reasons is testability. Say you have this class:

interface HttpLoader {
    String load(String url);
}
interface StringOutput {
    void print(String txt);
}
@Component
class MyBean {
    @Autowired
    MyBean(HttpLoader loader, StringOutput out) {
        out.print(loader.load("http://stackoverflow.com"));
    }
}

How can you test this bean? E.g. like this:

class MyBeanTest {
    public void creatingMyBean_writesStackoverflowPageToOutput() {
        // setup
        String stackOverflowHtml = "dummy";
        StringBuilder result = new StringBuilder();

        // execution
        new MyBean(Collections.singletonMap("https://stackoverflow.com", stackOverflowHtml)::get, result::append);

        // evaluation
        assertEquals(result.toString(), stackOverflowHtml);
    }
}

Easy, right?

While you still depend on Spring (due to the annotations) you can remove you dependency on spring without changing any code (only the annotation definitions) and the test developer does not need to know anything about how spring works (maybe he should anyway, but it allows to review and test the code separately from what spring does).

It is still possible to do the same when using the ApplicationContext. However then you need to mock ApplicationContext which is a huge interface. You either need a dummy implementation or you can use a mocking framework such as Mockito:

@Component
class MyBean {
    @Autowired
    MyBean(ApplicationContext context) {
        HttpLoader loader = context.getBean(HttpLoader.class);
        StringOutput out = context.getBean(StringOutput.class);

        out.print(loader.load("http://stackoverflow.com"));
    }
}
class MyBeanTest {
    public void creatingMyBean_writesStackoverflowPageToOutput() {
        // setup
        String stackOverflowHtml = "dummy";
        StringBuilder result = new StringBuilder();
        ApplicationContext context = Mockito.mock(ApplicationContext.class);
        Mockito.when(context.getBean(HttpLoader.class))
            .thenReturn(Collections.singletonMap("https://stackoverflow.com", stackOverflowHtml)::get);
        Mockito.when(context.getBean(StringOutput.class)).thenReturn(result::append);

        // execution
        new MyBean(context);

        // evaluation
        assertEquals(result.toString(), stackOverflowHtml);
    }
}

This is quite a possibility, but I think most people would agree that the first option is more elegant and makes the test simpler.

The only option that is really a problem is this one:

@Component
class MyBean {
    @Autowired
    MyBean(StringOutput out) {
        out.print(new HttpLoader().load("http://stackoverflow.com"));
    }
}

Testing this requires huge efforts or your bean is going to attempt to connect to stackoverflow on each test. And as soon as you have a network failure (or the admins at stackoverflow block you due to excessive access rate) you will have randomly failing tests.

So as a conclusion I would not say that using the ApplicationContext directly is automatically wrong and should be avoided at all costs. However if there are better options (and there are in most cases), then use the better options.

Replace special characters in a string with _ (underscore)

string = string.replace(/[\W_]/g, "_");

What is the difference between a JavaBean and a POJO?

POJO: If the class can be executed with underlying JDK,without any other external third party libraries support then its called POJO

JavaBean: If class only contains attributes with accessors(setters and getters) those are called javabeans.Java beans generally will not contain any bussiness logic rather those are used for holding some data in it.

All Javabeans are POJOs but all POJO are not Javabeans

Angular CLI SASS options

Like Mertcan said, the best way to use scss is to create the project with that option:

ng new My_New_Project --style=scss 

Angular-cli also adds an option to change the default css preprocessor after the project has been created by using the command:

ng set defaults.styleExt scss

For more info you can look here for their documentation:

https://github.com/angular/angular-cli

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

Tracking changes in Windows registry

A straightforward way to do this with no extra tools is to export the registry to a text file before the install, then export it to another file after. Then, compare the two files.

Having said that, the Sysinternals tools are great for this.

show loading icon until the page is load?

HTML

<body>
    <div id="load"></div>
    <div id="contents">
          jlkjjlkjlkjlkjlklk
    </div>
</body>

JS

document.onreadystatechange = function () {
  var state = document.readyState
  if (state == 'interactive') {
       document.getElementById('contents').style.visibility="hidden";
  } else if (state == 'complete') {
      setTimeout(function(){
         document.getElementById('interactive');
         document.getElementById('load').style.visibility="hidden";
         document.getElementById('contents').style.visibility="visible";
      },1000);
  }
}

CSS

#load{
    width:100%;
    height:100%;
    position:fixed;
    z-index:9999;
    background:url("https://www.creditmutuel.fr/cmne/fr/banques/webservices/nswr/images/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}

Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.

DEMO

http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)

update

http://jsfiddle.net/d9ngT/

Using gradle to find dependency tree

You can render the dependency tree with the command gradle dependencies. For more information check the section 11.6.4 Listing project dependencies in the online user guide.

Call Python function from JavaScript code

You cannot run .py files from JavaScript without the Python program like you cannot open .txt files without a text editor. But the whole thing becomes a breath with a help of a Web API Server (IIS in the example below).

  1. Install python and create a sample file test.py

    import sys
    # print sys.argv[0] prints test.py
    # print sys.argv[1] prints your_var_1
    
    def hello():
        print "Hi" + " " + sys.argv[1]
    
    if __name__ == "__main__":
        hello()
    
  2. Create a method in your Web API Server

    [HttpGet]
    public string SayHi(string id)
    {
        string fileName = HostingEnvironment.MapPath("~/Pyphon") + "\\" + "test.py";          
    
        Process p = new Process();
        p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName + " " + id)
        {
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };
        p.Start();
    
        return p.StandardOutput.ReadToEnd();                  
    }
    
  3. And now for your JavaScript:

    function processSayingHi() {          
       var your_param = 'abc';
       $.ajax({
           url: '/api/your_controller_name/SayHi/' + your_param,
           type: 'GET',
           success: function (response) {
               console.log(response);
           },
           error: function (error) {
               console.log(error);
           }
        });
    }
    

Remember that your .py file won't run on your user's computer, but instead on the server.

How can I check if the current date/time is past a set date/time?

There's also the DateTime class which implements a function for comparison operators.

// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');

if ( $dtA > $dtB ) {
  echo 'dtA > dtB';
}
else {
  echo 'dtA <= dtB';
}

java.util.zip.ZipException: error in opening zip file

Make sure your jar file is not corrupted. If it's corrupted or not able to unzip, this error will occur.

Retrieving the first digit of a number

int firstDigit = Integer.parseInt(Character.toString(firstLetterChar));

Background image jumps when address bar hides iOS/Android/Mobile Chrome

The problem can be solved with a media query and some math. Here's a solution for a portait orientation:

@media (max-device-aspect-ratio: 3/4) {
  height: calc(100vw * 1.333 - 9%);
}
@media (max-device-aspect-ratio: 2/3) {
  height: calc(100vw * 1.5 - 9%);
}
@media (max-device-aspect-ratio: 10/16) {
  height: calc(100vw * 1.6 - 9%);
}
@media (max-device-aspect-ratio: 9/16) {
  height: calc(100vw * 1.778 - 9%);
}

Since vh will change when the url bar dissapears, you need to determine the height another way. Thankfully, the width of the viewport is constant and mobile devices only come in a few different aspect ratios; if you can determine the width and the aspect ratio, a little math will give you the viewport height exactly as vh should work. Here's the process

1) Create a series of media queries for aspect ratios you want to target.

  • use device-aspect-ratio instead of aspect-ratio because the latter will resize when the url bar dissapears

  • I added 'max' to the device-aspect-ratio to target any aspect ratios that happen to follow in between the most popular. THey won't be as precise, but they will be only for a minority of users and will still be pretty close to the proper vh.

  • remember the media query using horizontal/vertical , so for portait you'll need to flip the numbers

2) for each media query multiply whatever percentage of vertical height you want the element to be in vw by the reverse of the aspect ratio.

  • Since you know the width and the ratio of width to height, you just multiply the % you want (100% in your case) by the ratio of height/width.

3) You have to determine the url bar height, and then minus that from the height. I haven't found exact measurements, but I use 9% for mobile devices in landscape and that seems to work fairly well.

This isn't a very elegant solution, but the other options aren't very good either, considering they are:

  • Having your website seem buggy to the user,

  • having improperly sized elements, or

  • Using javascript for some basic styling,

The drawback is some devices may have different url bar heights or aspect ratios than the most popular. However, using this method if only a small number of devices suffer the addition/subtraction of a few pixels, that seems much better to me than everyone having a website resize when swiping.

To make it easier, I also created a SASS mixin:

@mixin vh-fix {
  @media (max-device-aspect-ratio: 3/4) {
    height: calc(100vw * 1.333 - 9%);
  }
  @media (max-device-aspect-ratio: 2/3) {
    height: calc(100vw * 1.5 - 9%);
  }
  @media (max-device-aspect-ratio: 10/16) {
    height: calc(100vw * 1.6 - 9%);
  }
  @media (max-device-aspect-ratio: 9/16) {
    height: calc(100vw * 1.778 - 9%);
  }
}

Changing git commit message after push (given that no one pulled from remote)

Changing history

If it is the most recent commit, you can simply do this:

git commit --amend

This brings up the editor with the last commit message and lets you edit the message. (You can use -m if you want to wipe out the old message and use a new one.)

Pushing

And then when you push, do this:

git push --force-with-lease <repository> <branch>

Or you can use "+":

git push <repository> +<branch>

Or you can use --force:

git push --force <repository> <branch>

Be careful when using these commands.

  • If someone else pushed changes to the same branch, you probably want to avoid destroying those changes. The --force-with-lease option is the safest, because it will abort if there are any upstream changes (

  • If you don't specify the branch explicitly, Git will use the default push settings. If your default push setting is "matching", then you may destroy changes on several branches at the same time.

Pulling / fetching afterwards

Anyone who already pulled will now get an error message, and they will need to update (assuming they aren't making any changes themselves) by doing something like this:

git fetch origin
git reset --hard origin/master # Loses local commits

Be careful when using reset --hard. If you have changes to the branch, those changes will be destroyed.

A note about modifying history

The destroyed data is really just the old commit message, but --force doesn't know that, and will happily delete other data too. So think of --force as "I want to destroy data, and I know for sure what data is being destroyed." But when the destroyed data is committed, you can often recover old commits from the reflog—the data is actually orphaned instead of destroyed (although orphaned commits are periodically deleted).

If you don't think you're destroying data, then stay away from --force... bad things might happen.

This is why --force-with-lease is somewhat safer.

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

how to get the selected index of a drop down

You can also use :checked for <select> elements

e.g.,

document.querySelector('select option:checked')
document.querySelector('select option:checked').getAttribute('value')

You don't even have to get the index and then reference the element by its sibling index.

What is git fast-forwarding?

In Git, to "fast forward" means to update the HEAD pointer in such a way that its new value is a direct descendant of the prior value. In other words, the prior value is a parent, or grandparent, or grandgrandparent, ...

Fast forwarding is not possible when the new HEAD is in a diverged state relative to the stream you want to integrate. For instance, you are on master and have local commits, and git fetch has brought new upstream commits into origin/master. The branch now diverges from its upstream and cannot be fast forwarded: your master HEAD commit is not an ancestor of origin/master HEAD. To simply reset master to the value of origin/master would discard your local commits. The situation requires a rebase or merge.

If your local master has no changes, then it can be fast-forwarded: simply updated to point to the same commit as the latestorigin/master. Usually, no special steps are needed to do fast-forwarding; it is done by merge or rebase in the situation when there are no local commits.

Is it ok to assume that fast-forward means all commits are replayed on the target branch and the HEAD is set to the last commit on that branch?

No, that is called rebasing, of which fast-forwarding is a special case when there are no commits to be replayed (and the target branch has new commits, and the history of the target branch has not been rewritten, so that all the commits on the target branch have the current one as their ancestor.)

Change tab bar item selected color in a storyboard

This elegant solution works great on SWIFT 3.0, SWIFT 4.2 and SWIFT 5.1:

On the Storyboard:

  1. Select your Tab Bar
  2. Set a Runtime Attibute called tintColor for the desired color of the Selected Icon on the tab bar
  3. Set a Runtime Attibute called unselectedItemTintColor for the desired color of the Unselected Icon on the tab bar

enter image description here

Edit: Working with Xcode 8/10, for iOS 10/12 and above.

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Setting focus to a textbox control

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    TextBox1.Select()
End Sub

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

Get the value in an input text box

Try this. It will work for sure.

var userInput = $('#txt_name').attr('value')

Selenium Webdriver submit() vs click()

The submit() function is there to make life easier. You can use it on any element inside of form tags to submit that form.

You can also search for the submit button and use click().

So the only difference is click() has to be done on the submit button and submit() can be done on any form element.

It's up to you.

http://docs.seleniumhq.org/docs/03_webdriver.jsp#user-input-filling-in-forms

Converting from IEnumerable to List

In case you're working with a regular old System.Collections.IEnumerable instead of IEnumerable<T> you can use enumerable.Cast<object>().ToList()

Is there a way to create interfaces in ES6 / Node 4?

Given that ECMA is a 'class-free' language, implementing classical composition doesn't - in my eyes - make a lot of sense. The danger is that, in so doing, you are effectively attempting to re-engineer the language (and, if one feels strongly about that, there are excellent holistic solutions such as the aforementioned TypeScript that mitigate reinventing the wheel)

Now that isn't to say that composition is out of the question however in Plain Old JS. I researched this at length some time ago. The strongest candidate I have seen for handling composition within the object prototypal paradigm is stampit, which I now use across a wide range of projects. And, importantly, it adheres to a well articulated specification.

more information on stamps here

How can I change default dialog button text color in android 5

Here is how you do it: Simple way

// Initializing a new alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.message);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        doAction();
    }
});
builder.setNegativeButton(R.string.cancel, null);

// Create the alert dialog and change Buttons colour
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface arg0) {
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.red));
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.blue));
        //dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(getResources().getColor(R.color.black));
    }
});
dialog.show();

Unable to create Genymotion Virtual Device

Solved!!

I am using OS X 10.9 (Mavericks), Genymotion v1.3.1

While adding the device, instead of adding Nexus, I added Galaxy S4/HTC One/Xperia Z - 4.2.2 with Google Apps.

This one just worked.

How do I upload a file with metadata using a REST web service?

One way to approach the problem is to make the upload a two phase process. First, you would upload the file itself using a POST, where the server returns some identifier back to the client (an identifier might be the SHA1 of the file contents). Then, a second request associates the metadata with the file data:

{
    "Name": "Test",
    "Latitude": 12.59817,
    "Longitude": 52.12873,
    "ContentID": "7a788f56fa49ae0ba5ebde780efe4d6a89b5db47"
}

Including the file data base64 encoded into the JSON request itself will increase the size of the data transferred by 33%. This may or may not be important depending on the overall size of the file.

Another approach might be to use a POST of the raw file data, but include any metadata in the HTTP request header. However, this falls a bit outside basic REST operations and may be more awkward for some HTTP client libraries.

What are alternatives to document.write?

I fail to see the problem with document.write. If you are using it before the onload event fires, as you presumably are, to build elements from structured data for instance, it is the appropriate tool to use. There is no performance advantage to using insertAdjacentHTML or explicitly adding nodes to the DOM after it has been built. I just tested it three different ways with an old script I once used to schedule incoming modem calls for a 24/7 service on a bank of 4 modems.

By the time it is finished this script creates over 3000 DOM nodes, mostly table cells. On a 7 year old PC running Firefox on Vista, this little exercise takes less than 2 seconds using document.write from a local 12kb source file and three 1px GIFs which are re-used about 2000 times. The page just pops into existence fully formed, ready to handle events.

Using insertAdjacentHTML is not a direct substitute as the browser closes tags which the script requires remain open, and takes twice as long to ultimately create a mangled page. Writing all the pieces to a string and then passing it to insertAdjacentHTML takes even longer, but at least you get the page as designed. Other options (like manually re-building the DOM one node at a time) are so ridiculous that I'm not even going there.

Sometimes document.write is the thing to use. The fact that it is one of the oldest methods in JavaScript is not a point against it, but a point in its favor - it is highly optimized code which does exactly what it was intended to do and has been doing since its inception.

It's nice to know that there are alternative post-load methods available, but it must be understood that these are intended for a different purpose entirely; namely modifying the DOM after it has been created and memory allocated to it. It is inherently more resource-intensive to use these methods if your script is intended to write the HTML from which the browser creates the DOM in the first place.

Just write it and let the browser and interpreter do the work. That's what they are there for.

PS: I just tested using an onload param in the body tag and even at this point the document is still open and document.write() functions as intended. Also, there is no perceivable performance difference between the various methods in the latest version of Firefox. Of course there is a ton of caching probably going on somewhere in the hardware/software stack, but that's the point really - let the machine do the work. It may make a difference on a cheap smartphone though. Cheers!

setOnItemClickListener on custom ListView

Sample Code:

ListView list = (ListView) findViewById(R.id.listview);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      Object listItem = list.getItemAtPosition(position);
   } 
});

In the sample code above, the listItem should contain the selected data for the textView.

How to display raw JSON data on a HTML page

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

You have to decide if:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.

If you give more details about your stack, it's easier to provide examples or resources.

EDIT: For client side JS highlighting you can try higlight.js, for instance.

Case insensitive comparison NSString

NSMutableArray *arrSearchData;  
NSArray *data=[arrNearByData objectAtIndex:i];
NSString *strValue=[NSString stringWithFormat:@"%@", [data valueForKey:@"restName"]];
NSRange r = [strValue rangeOfString:key options:NSCaseInsensitiveSearch];

if(r.location != NSNotFound)
{
     [arrSearchData addObject:data];
}

MySQL - How to select data by string length

You are looking for CHAR_LENGTH() to get the number of characters in a string.

For multi-byte charsets LENGTH() will give you the number of bytes the string occupies, while CHAR_LENGTH() will return the number of characters.

Creating multiple objects with different names in a loop to store in an array list

ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
    //get a customerName
    //get an amount
    custArr.add(new Customer(customerName, amount);
}

For this to work... you'll have to fix your constructor...


Assuming your Customer class has variables called name and sale, your constructor should look like this:

public Customer(String customerName, double amount) {
    name = customerName;
    sale = amount;
}

Change your Store class to something more like this:

public class Store {

    private ArrayList<Customer> custArr;

    public new Store() {
        custArr = new ArrayList<Customer>();
    }

    public void addSale(String customerName, double amount) {
        custArr.add(new Customer(customerName, amount));
    }

    public Customer getSaleAtIndex(int index) {
        return custArr.get(index);
    }

    //or if you want the entire ArrayList:
    public ArrayList getCustArr() {
        return custArr;
    }
}

How to make pylab.savefig() save image for 'maximized' window instead of default size

I did the same search time ago, it seems that he exact solution depends on the backend.

I have read a bunch of sources and probably the most useful was the answer by Pythonio here How to maximize a plt.show() window using Python I adjusted the code and ended up with the function below. It works decently for me on windows, I mostly use Qt, where I use it quite often, while it is minimally tested with other backends.

Basically it consists in identifying the backend and calling the appropriate function. Note that I added a pause afterwards because I was having issues with some windows getting maximized and others not, it seems this solved for me.

def maximize(backend=None,fullscreen=False):
    """Maximize window independently on backend.
    Fullscreen sets fullscreen mode, that is same as maximized, but it doesn't have title bar (press key F to toggle full screen mode)."""
    if backend is None:
        backend=matplotlib.get_backend()
    mng = plt.get_current_fig_manager()

    if fullscreen:
        mng.full_screen_toggle()
    else:
        if backend == 'wxAgg':
            mng.frame.Maximize(True)
        elif backend == 'Qt4Agg' or backend == 'Qt5Agg':
            mng.window.showMaximized()
        elif backend == 'TkAgg':
            mng.window.state('zoomed') #works fine on Windows!
        else:
            print ("Unrecognized backend: ",backend) #not tested on different backends (only Qt)
    plt.show()

    plt.pause(0.1) #this is needed to make sure following processing gets applied (e.g. tight_layout)

Redirect to external URL with return in laravel

For Laravel 5.x we can redirect with just

return redirect()->to($url);

Should I use encodeURI or encodeURIComponent for encoding URLs?

Difference between encodeURI and encodeURIComponent:

encodeURIComponent(value) is mainly used to encode queryString parameter values, and it encodes every applicable character in value. encodeURI ignores protocol prefix (http://) and domain name.


In very, very rare cases, when you want to implement manual encoding to encode additional characters (though they don't need to be encoded in typical cases) like: ! * , then you might use:

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

(source)

SQL set values of one column equal to values of another column in the same table

UPDATE YourTable
SET ColumnB=ColumnA
WHERE
ColumnB IS NULL 
AND ColumnA IS NOT NULL

How to grep (search) committed code in the Git history

Adding more to the answers already present. If you know the file in which you might have made do this:

git log --follow -p -S 'search-string' <file-path>

--follow: lists the history of a file

Parse JSON String into List<string>

Seems like a bad way to do it (creating two correlated lists) but I'm assuming you have your reasons.

I'd parse the JSON string (which has a typo in your example, it's missing a comma between the two objects) into a strongly-typed object and then use a couple of LINQ queries to get the two lists.

void Main()
{
    string json = "{\"People\":[{\"FirstName\":\"Hans\",\"LastName\":\"Olo\"},{\"FirstName\":\"Jimmy\",\"LastName\":\"Crackedcorn\"}]}";

    var result = JsonConvert.DeserializeObject<RootObject>(json);

    var firstNames = result.People.Select (p => p.FirstName).ToList();
    var lastNames = result.People.Select (p => p.LastName).ToList();
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class RootObject
{
    public List<Person> People { get; set; }
}

Effect of NOLOCK hint in SELECT statements

  • The answer is Yes if the query is run multiple times at once, because each transaction won't need to wait for the others to complete. However, If the query is run once on its own then the answer is No.

  • Yes. There's a significant probability that careful use of WITH(NOLOCK) will speed up your database overall. It means that other transactions won't have to wait for this SELECT statement to finish, but on the other hand, other transactions will slow down as they're now sharing their processing time with a new transaction.

Be careful to only use WITH (NOLOCK) in SELECT statements on tables that have a clustered index.

WITH(NOLOCK) is often exploited as a magic way to speed up database read transactions.

The result set can contain rows that have not yet been committed, that are often later rolled back.

If WITH(NOLOCK) is applied to a table that has a non-clustered index then row-indexes can be changed by other transactions as the row data is being streamed into the result-table. This means that the result-set can be missing rows or display the same row multiple times.

READ COMMITTED adds an additional issue where data is corrupted within a single column where multiple users change the same cell simultaneously.

Is it possible to write to the console in colour in .NET?

Yes, it's easy and possible. Define first default colors.

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();

Console.Clear() it's important in order to set new console colors. If you don't make this step you can see combined colors when ask for values with Console.ReadLine().

Then you can change the colors on each print:

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Red text over black.");

When finish your program, remember reset console colors on finish:

Console.ResetColor();
Console.Clear();

Now with netcore we have another problem if you want to "preserve" the User experience because terminal have different colors on each Operative System.

I'm making a library that solves this problem with Text Format: colors, alignment and lot more. Feel free to use and contribute.

https://github.com/deinsoftware/colorify/ and also available as NuGet package

Colors for Windows/Linux (Dark):
enter image description here

Colors for MacOS (Light):
enter image description here

Append values to a set in Python

This question is the first one that shows up on Google when one looks up "Python how to add elements to set", so it's worth noting explicitly that, if you want to add a whole string to a set, it should be added with .add(), not .update().

Say you have a string foo_str whose contents are 'this is a sentence', and you have some set bar_set equal to set().

If you do bar_set.update(foo_str), the contents of your set will be {'t', 'a', ' ', 'e', 's', 'n', 'h', 'c', 'i'}.

If you do bar_set.add(foo_str), the contents of your set will be {'this is a sentence'}.

Newline in markdown table?

Use <br/> . For example:

Change log, upgrade version

Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`

URL: https://github.com/donhuvy/lsb/wiki

How to concat two ArrayLists?

ArrayList<String> resultList = new ArrayList<String>();
resultList.addAll(arrayList1);
resultList.addAll(arrayList2);

MySQL: Quick breakdown of the types of joins

I have 2 tables like this:

> SELECT * FROM table_a;
+------+------+
| id   | name |
+------+------+
|    1 | row1 |
|    2 | row2 |
+------+------+

> SELECT * FROM table_b;
+------+------+------+
| id   | name | aid  |
+------+------+------+
|    3 | row3 |    1 |
|    4 | row4 |    1 |
|    5 | row5 | NULL |
+------+------+------+

INNER JOIN cares about both tables

INNER JOIN cares about both tables, so you only get a row if both tables have one. If there is more than one matching pair, you get multiple rows.

> SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
+------+------+------+------+------+

It makes no difference to INNER JOIN if you reverse the order, because it cares about both tables:

> SELECT * FROM table_b b INNER JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
+------+------+------+------+------+

You get the same rows, but the columns are in a different order because we mentioned the tables in a different order.

LEFT JOIN only cares about the first table

LEFT JOIN cares about the first table you give it, and doesn't care much about the second, so you always get the rows from the first table, even if there is no corresponding row in the second:

> SELECT * FROM table_a a LEFT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
|    2 | row2 | NULL | NULL | NULL |
+------+------+------+------+------+

Above you can see all rows of table_a even though some of them do not match with anything in table b, but not all rows of table_b - only ones that match something in table_a.

If we reverse the order of the tables, LEFT JOIN behaves differently:

> SELECT * FROM table_b b LEFT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
|    5 | row5 | NULL | NULL | NULL |
+------+------+------+------+------+

Now we get all rows of table_b, but only matching rows of table_a.

RIGHT JOIN only cares about the second table

a RIGHT JOIN b gets you exactly the same rows as b LEFT JOIN a. The only difference is the default order of the columns.

> SELECT * FROM table_a a RIGHT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
| NULL | NULL |    5 | row5 | NULL |
+------+------+------+------+------+

This is the same rows as table_b LEFT JOIN table_a, which we saw in the LEFT JOIN section.

Similarly:

> SELECT * FROM table_b b RIGHT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
| NULL | NULL | NULL |    2 | row2 |
+------+------+------+------+------+

Is the same rows as table_a LEFT JOIN table_b.

No join at all gives you copies of everything

If you write your tables with no JOIN clause at all, just separated by commas, you get every row of the first table written next to every row of the second table, in every possible combination:

> SELECT * FROM table_b b, table_a;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    3 | row3 | 1    |    2 | row2 |
|    4 | row4 | 1    |    1 | row1 |
|    4 | row4 | 1    |    2 | row2 |
|    5 | row5 | NULL |    1 | row1 |
|    5 | row5 | NULL |    2 | row2 |
+------+------+------+------+------+

(This is from my blog post Examples of SQL join types)

Problems with local variable scope. How to solve it?

Firstly, we just CAN'T make the variable final as its state may be changing during the run of the program and our decisions within the inner class override may depend on its current state.

Secondly, good object-oriented programming practice suggests using only variables/constants that are vital to the class definition as class members. This means that if the variable we are referencing within the anonymous inner class override is just a utility variable, then it should not be listed amongst the class members.

But – as of Java 8 – we have a third option, described here :

https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html

Starting in Java SE 8, if you declare the local class in a method, it can access the method's parameters.

So now we can simply put the code containing the new inner class & its method override into a private method whose parameters include the variable we call from inside the override. This static method is then called after the btnInsert declaration statement :-

 . . . .
 . . . .

 Statement statement = null;                                 

 . . . .
 . . . .

 Button btnInsert = new Button(shell, SWT.NONE);
 addMouseListener(Button btnInsert, Statement statement);    // Call new private method

 . . . 
 . . .
 . . . 

 private static void addMouseListener(Button btn, Statement st) // New private method giving access to statement 
 {
    btn.addMouseListener(new MouseAdapter() 
    {
      @Override
      public void mouseDown(MouseEvent e) 
      {
        String name = text.getText();
        String from = text_1.getText();
        String to = text_2.getText();
        String price = text_3.getText();
        String query = "INSERT INTO booking (name, fromst, tost,price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
        try 
        {
            st.executeUpdate(query);
        } 
        catch (SQLException e1) 
        {
            e1.printStackTrace();                                    // TODO Auto-generated catch block
        }
    }
  });
  return;
}

 . . . .
 . . . .
 . . . .

disabling spring security in spring boot app

For me only excluding the following classes worked:

import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class}) {
  // ... 
}

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

@Nickparsa … you have 2 issues:

1). mysql -uroot -p should be typed in bash (also known as your terminal) not in MySQL command-line. You fix this error by typing

exit

in your MySQL command-line. Now you are back in your bash/terminal command-line.

2). You have a syntax error:

mysql -uroot -p; 

the semicolon in front of -p needs to go. The correct syntax is:

mysql -uroot -p

type the correct syntax in your bash commandline. Enter a password if you have one set up; else just hit the enter button. You should get a response that is similar to this: enter image description here

Hope this helps!

center aligning a fixed position div

Center it horizontally:

display: fixed;
top: 0; 
left: 0;
transform: translate(calc(50vw - 50%));

Center it horizontally and vertically:

display: fixed;
top: 0; 
left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));

No side effect: It will not limit element's width when using margins in flexbox

Rounded table corners CSS only

This is css3, only recent non-IE<9 browser will support it.

Check out here, it derives the round property for all available browsers

How to save a plot into a PDF file without a large margin around

It seems to me that all approaches (file exchange solutions unconsidered) here are lacking the essential step, or finally leading to it via some blurry workarounds.

The figure size needs to equal the paper size and the white margins are gone.

A = hgload('myFigure.fig');

% set desired output size
set(A, 'Units','centimeters')
height = 15;
width = 19;

% the last two parameters of 'Position' define the figure size
set(A, 'Position',[25 5 width height],...
       'PaperSize',[width height],...
       'PaperPositionMode','auto',...
       'InvertHardcopy', 'off',...
       'Renderer','painters'...     %recommended if there are no alphamaps
   );

saveas(A,'printout','pdf')

Will give you a pdf output as your figure appears, in exactly the size you want. If you want to get it even tighter you can combine this solution with the answer of b3.

Regex match digits, comma and semicolon?

You almost have it, you just left out 0 and forgot the quantifier.

word.matches("^[0-9,;]+$")

How can I maintain fragment state when added to the back stack?

My problem was similar but I overcame me without keeping the fragment alive. Suppose you have an activity that has 2 fragments - F1 and F2. F1 is started initially and lets say in contains some user info and then upon some condition F2 pops on asking user to fill in additional attribute - their phone number. Next, you want that phone number to pop back to F1 and complete signup but you realize all previous user info is lost and you don't have their previous data. The fragment is recreated from scratch and even if you saved this information in onSaveInstanceState the bundle comes back null in onActivityCreated.

Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Bundle args = getArguments();

    // this will be null the first time F1 is created. 
    // it will be populated once you replace fragment and provide bundle data
    if (args != null) {
        if (args.get("your_info") != null) {
            // do what you want with restored information
        }
    }
}

So following on with my example: before I display F2 I save user data in the instance variable using a callback. Then I start F2, user fills in phone number and presses save. I use another callback in activity, collect this information and replace my fragment F1, this time it has bundle data that I can use.

@Override
public void onPhoneAdded(String phone) {
        //replace fragment
        F1 f1 = new F1 ();
        Bundle args = new Bundle();
        yourInfo.setPhone(phone);
        args.putSerializable("you_info", yourInfo);
        f1.setArguments(args);

        getFragmentManager().beginTransaction()
                .replace(R.id.fragmentContainer, f1).addToBackStack(null).commit();

    }
}

More information about callbacks can be found here: https://developer.android.com/training/basics/fragments/communicating.html

How to pass multiple values to single parameter in stored procedure

USE THIS

I have had this exact issue for almost 2 weeks, extremely frustrating but I FINALLY found this site and it was a clear walk-through of what to do.

http://blog.summitcloud.com/2010/01/multivalue-parameters-with-stored-procedures-in-ssrs-sql/

I hope this helps people because it was exactly what I was looking for

Export/import jobs in Jenkins

Thanks to Larry Cai's answer I managed to create a script to backup all my Jenkins jobs. I created a job that runs this every week. In case someone finds it useful, here it is:

#!/bin/bash
#IFS for jobs with spaces.
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for i in $(java -jar /run/jenkins/war/WEB-INF/jenkins-cli.jar -s http://server:8080/ list-jobs); 
do 
  java -jar /run/jenkins/war/WEB-INF/jenkins-cli.jar -s http://server:8080/ get-job ${i} > ${i}.xml;
done
IFS=$SAVEIFS
mkdir deploy
tar cvfj "jenkins-jobs.tar.bz2" ./*.xml

What is sharding and why is it important?

Is sharding mostly important in very large scale applications or does it apply to smaller scale ones?

Sharding is a concern if and only if your needs scale past what can be served by a single database server. It's a swell tool if you have shardable data and you have incredibly high scalability and performance requirements. I would guess that in my entire 12 years I've been a software professional, I've encountered one situation that could have benefited from sharding. It's an advanced technique with very limited applicability.

Besides, the future is probably going to be something fun and exciting like a massive object "cloud" that erases all potential performance limitations, right? :)

Java String encoding (UTF-8)

This could be complicated way of doing

String newString = new String(oldString);

This shortens the String is the underlying char[] used is much longer.

However more specifically it will be checking that every character can be UTF-8 encoded.

There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?

Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'

String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));

prints

false

Adding a caption to an equation in LaTeX

You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat

I say this because captions are usually applied to floats.

Straight ahead equations (those written with $ ... $, $$ ... $$, begin{equation}...) are in-line objects that do not support \caption.

This can be done using the following snippet just before \begin{document}

\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}

\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
  \let\ORIGINALcaption\caption
  \def\caption{%
    \addtocounter{equation}{-1}%
    \ORIGINALcaption
  }%
  \ORGeqfloat
}

and when adding an equation use something like

\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}

Bootstrap Carousel image doesn't align properly

The solution is to put this CSS code into your custom CSS file:

.carousel-inner > .item > img {
  margin: 0 auto;
}

Access-Control-Allow-Origin: * in tomcat

The issue arose because of not including jar file as part of the project. I was just including it in tomcat lib. Using the below in web.xml works now:

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>
        org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
</filter>

 <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>

    <init-param>
        <param-name>cors.allowOrigin</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportsCredentials</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedHeaders</param-name>
        <param-value>accept, authorization, origin</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedMethods</param-name>
        <param-value>GET, POST, HEAD, OPTIONS</param-value>
    </init-param>
</filter>


<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

And the below in your project dependency:

<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>1.3.2</version>
</dependency>

How to set environment variable or system property in spring tests?

The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource annotation.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
    ...    
}

See @TestPropertySource in the Spring docs and Javadocs.

Remove part of a string

Here the strsplit solution for a dataframe using dplyr package

col1 = c("TGAS_1121", "MGAS_1432", "ATGAS_1121") 
col2 = c("T", "M", "A") 
df = data.frame(col1, col2)
df
        col1 col2
1  TGAS_1121    T
2  MGAS_1432    M
3 ATGAS_1121    A

df<-mutate(df,col1=as.character(col1))
df2<-mutate(df,col1=sapply(strsplit(df$col1, split='_', fixed=TRUE),function(x) (x[2])))
df2

  col1 col2
1 1121    T
2 1432    M
3 1121    A

Regular Expression Match to test for a valid year

Building on @r92 answer, for years 1970-2019:

(19[789]\d|20[01]\d)

Calculate the execution time of a method

StopWatch will use the high-resolution counter

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

If you're measuring IO then your figures will likely be impacted by external events, and I would worry so much re. exactness (as you've indicated above). Instead I'd take a range of measurements and consider the mean and distribution of those figures.

"’" showing on page instead of " ' "

So what's the problem,

It's a (RIGHT SINGLE QUOTATION MARK - U+2019) character which is being decoded as CP-1252 instead of UTF-8. If you check the encodings table, then you see that this character is in UTF-8 composed of bytes 0xE2, 0x80 and 0x99. If you check the CP-1252 code page layout, then you'll see that each of those bytes stand for the individual characters â, and .


and how can I fix it?

Use UTF-8 instead of CP-1252 to read, write, store, and display the characters.


I have the Content-Type set to UTF-8 in both my <head> tag and my HTTP headers:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

This only instructs the client which encoding to use to interpret and display the characters. This doesn't instruct your own program which encoding to use to read, write, store, and display the characters in. The exact answer depends on the server side platform / database / programming language used. Do note that the one set in HTTP response header has precedence over the HTML meta tag. The HTML meta tag would only be used when the page is opened from local disk file system instead of from HTTP.


In addition, my browser is set to Unicode (UTF-8):

This only forces the client which encoding to use to interpret and display the characters. But the actual problem is that you're already sending ’ (encoded in UTF-8) to the client instead of . The client is correctly displaying ’ using the UTF-8 encoding. If the client was misinstructed to use, for example ISO-8859-1, you would likely have seen ââ¬â¢ instead.


I am using ASP.NET 2.0 with a database.

This is most likely where your problem lies. You need to verify with an independent database tool what the data looks like.

If the character is there, then you aren't connecting to the database correctly. You need to tell the database connector to use UTF-8.

If your database contains ’, then it's your database that's messed up. Most probably the tables aren't configured to use UTF-8. Instead, they use the database's default encoding, which varies depending on the configuration. If this is your issue, then usually just altering the table to use UTF-8 is sufficient. If your database doesn't support that, you'll need to recreate the tables. It is good practice to set the encoding of the table when you create it.

You're most likely using SQL Server, but here is some MySQL code (copied from this article):

CREATE DATABASE db_name CHARACTER SET utf8;
CREATE TABLE tbl_name (...) CHARACTER SET utf8;

If your table is however already UTF-8, then you need to take a step back. Who or what put the data there. That's where the problem is. One example would be HTML form submitted values which are incorrectly encoded/decoded.


Here are some more links to learn more about the problem:

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Using the AWS Management Console

  • Go to "Volumes" and create a Snapshot of your instance's volume.
  • Go to "Snapshots" and select "Create Image from Snapshot".
  • Go to "AMIs" and select "Launch Instance" and choose your "Instance Type" etc.

PHP Create and Save a txt file to root directory

If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT. This means that the path is dynamic, and can be moved between servers without messing about with the code.

<?php
  $fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
  $file = fopen($fileLocation,"w");
  $content = "Your text here";
  fwrite($file,$content);
  fclose($file);
?>

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I lowercase a string in C?

It's in the standard library, and that's the most straight forward way I can see to implement such a function. So yes, just loop through the string and convert each character to lowercase.

Something trivial like this:

#include <ctype.h>

for(int i = 0; str[i]; i++){
  str[i] = tolower(str[i]);
}

or if you prefer one liners, then you can use this one by J.F. Sebastian:

for ( ; *p; ++p) *p = tolower(*p);

Swapping pointers in C (char, int)

This example does not swap two int pointers. It swaps the value of the integers that pa and pb are pointing to. Here's an example of what's going on when you call this:

void Swap1 (int *pa, int *pb){
    int temp = *pa;
    *pa = *pb;
    *pb = temp;
}
int main()
{
    int a = 42;
    int b = 17;


    int *pa = &a;
    int *pb = &b;

    printf("--------Swap1---------\n");
    printf("a = %d\n b = %d\n", a, b);
    swap1(pa, pb);
    printf("a = %d\n = %d\n", a, a);
    printf("pb address =  %p\n", pa);
    printf("pa address =  %p\n", pb);
}

The output here is:

a = 42
b = 17
pa address =  0x7fffdf933228
pb address =  0x7fffdf93322c
--------Swap---------
pa = 17
pb = 42
a = 17
b = 42
pa address =  0x7fffdf933228
pb address =  0x7fffdf93322c

Note that the values swapped, but the pointer's addresses did not swap!

In order to swap addresses we need to do this:

void swap2 (int **pa, int **pb){
    int temp = *pa;
    *pa = *pb;
    *pb = temp;
}

and in main call the function like swap2(&pa, &pb);

Now the addresses are swapped, as well as the values for the pointers. a and b have the same values that the are initialized with The integers a and b did not swap because it swap2 swaps the addresses being being pointed to by the pointers!:

a = 42
b = 17
pa address =  0x7fffddaa9c98
pb address =  0x7fffddaa9c9c
--------Swap---------
pa = 17
pb = 42
a = 42
b = 17
pa address =  0x7fffddaa9c9c
pb address =  0x7fffddaa9c98

Since Strings in C are char pointers, and you want to swap Strings, you are really swapping a char pointer. As in the examples with an int, you need a double pointer to swap addresses.

The values of integers can be swapped even if the address isn't, but Strings are by definition a character pointer. You could swap one char with single pointers as the parameter, but a character pointer needs to be a double pointer in order to swap the strings.

How can I include all JavaScript files in a directory via JavaScript file?

You can't do that in JavaScript, since JS is executed in the browser, not in the server, so it didn't know anything about directories or other server resources.

The best option is using a server side script like the one posted by jellyfishtree.

How do I view the list of functions a Linux shared library is exporting?

On a MAC, you need to use nm *.o | c++filt, as there is no -C option in nm.

REST API using POST instead of GET

In REST, each HTTP verbs has its place and meaning.

For example,

  • GET is to get the 'resource(s)' that is pointed to in the URL.

  • POST is to instructure the backend to 'create' a resource of the 'type' pointed to in the URL. You can supplement the POST operation with parameters or additional data in the body of the POST call.

In you case, since you are interested in 'getting' the info using query, thus it should be a GET operation instead of a POST operation.

This wiki may help to further clarify things.

Hope this help!

Change color of PNG image via CSS?

To literally change the color, you could incorporate a CSS transition with a -webkit-filter where when something happens you would invoke the -webkit-filter of your choice. For example:

img {
    -webkit-filter:grayscale(0%);
    transition: -webkit-filter .3s linear;
    }
img:hover 
    {
    -webkit-filter:grayscale(75%);
    }

How to add a list item to an existing unordered list?

This is another one

$("#header ul li").last().html('<li> Menu 5 </li>');

OPTION (RECOMPILE) is Always Faster; Why?

To add to the excellent list (given by @CodeCowboyOrg) of situations where OPTION(RECOMPILE) can be very helpful,

  1. Table Variables. When you are using table variables, there will not be any pre-built statistics for the table variable, often leading to large differences between estimated and actual rows in the query plan. Using OPTION(RECOMPILE) on queries with table variables allows generation of a query plan that has a much better estimate of the row numbers involved. I had a particularly critical use of a table variable that was unusable, and which I was going to abandon, until I added OPTION(RECOMPILE). The run time went from hours to just a few minutes. That is probably unusual, but in any case, if you are using table variables and working on optimizing, it's well worth seeing whether OPTION(RECOMPILE) makes a difference.

Where is database .bak file saved from SQL Server Management Studio?

I dont think default backup location is stored within the SQL server itself. The settings are stored in Registry. Look for "BackupDirectory" key and you'll find the default backup.

The "msdb.dbo.backupset" table consists of list of backups taken, if no backup is taken for a database, it won't show you anything

Find all CSV files in a directory using Python

from os import listdir

def find_csv_filenames( path_to_dir, suffix=".csv" ):
    filenames = listdir(path_to_dir)
    return [ filename for filename in filenames if filename.endswith( suffix ) ]

The function find_csv_filenames() returns a list of filenames as strings, that reside in the directory path_to_dir with the given suffix (by default, ".csv").

Addendum

How to print the filenames:

filenames = find_csv_filenames("my/directory")
for name in filenames:
  print name

Trusting all certificates using HttpClient over HTTPS

work with all https

httpClient = new DefaultHttpClient();

SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
    public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

    public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
};

ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, ssf));

How to find substring from string?

If you are utilizing arrays too much then you should include cstring.h because it has too many functions including finding substrings.

How to detect if a string contains at least a number?

  1. You could use CLR based UDFs or do a CONTAINS query using all the digits on the search column.

Replace a newline in TSQL

If you have have open procedure with using sp_helptext then just copy all text in new sql query and press ctrl+h button use regular expression to replace and put ^\n in find field replace with blank . for more detail check image.enter image description here

<ng-container> vs <template>

Edit : Now it is documented

<ng-container> to the rescue

The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

(...)

The <ng-container> is a syntax element recognized by the Angular parser. It's not a directive, component, class, or interface. It's more like the curly braces in a JavaScript if-block:

  if (someCondition) {
      statement1; 
      statement2;
      statement3;
     }

Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The <ng-container> satisfies a similar need in Angular templates.

Original answer:

According to this pull request :

<ng-container> is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.

<ng-container> is rendered as an HTML comment.

so this angular template :

<div>
    <ng-container>foo</ng-container>
<div>

will produce this kind of output :

<div>
    <!--template bindings={}-->foo
<div>

So ng-container is useful when you want to conditionaly append a group of elements (ie using *ngIf="foo") in your application but don't want to wrap them with another element.

<div>
    <ng-container *ngIf="true">
        <h2>Title</h2>
        <div>Content</div>
    </ng-container>
</div>

will then produce :

<div>
    <h2>Title</h2>
    <div>Content</div>
</div>

How to generate java classes from WSDL file

i founded a great toool to auto parse and connect to web services

http://www.wsdl2code.com

http://www.wsdl2code.com/pages/Example.aspx

 SampleService srv1 = new SampleService();
     req = new Request();                     
     req.companyId = "1";
     req.userName = "userName";                                     
     req.password = "pas";
     Response response =    srv1.ServiceSample(req);

image.onload event and browser cache

As you're generating the image dynamically, set the onload property before the src.

var img = new Image();
img.onload = function () {
   alert("image is loaded");
}
img.src = "img.jpg";

Fiddle - tested on latest Firefox and Chrome releases.

You can also use the answer in this post, which I adapted for a single dynamically generated image:

var img = new Image();
// 'load' event
$(img).on('load', function() {
  alert("image is loaded");
});
img.src = "img.jpg";

Fiddle

The remote server returned an error: (403) Forbidden

Add the following line:

request.UseDefaultCredentials = true;

This will let the application use the credentials of the logged in user to access the site. If it's returning 403, clearly it's expecting authentication.

It's also possible that you (now?) have an authenticating proxy in between you and the remote site. In which case, try:

request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

Hope this helps.

How to add the JDBC mysql driver to an Eclipse project?

Try to insert this:

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

before getting the JDBC Connection.

MVC Calling a view from a different controller

It is explained pretty well here: Display a view from another controller in ASP.NET MVC

To quote @Womp:
By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\, but after that, if it doesn't find the view, it checks in \Views\Shared.

ASP MVC's idea is "convention over configuration" which means moving the view to the shared folder is the way to go in such cases.

MS Access VBA: Sending an email through Outlook

Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.

Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")

Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing


End Sub

Compare every item to every other item in ArrayList

for (int i = 0; i < list.size(); i++) {
  for (int j = i+1; j < list.size(); j++) {
    // compare list.get(i) and list.get(j)
  }
}

Multiprocessing a for loop?

You can use multiprocessing.Pool:

from multiprocessing import Pool
class Engine(object):
    def __init__(self, parameters):
        self.parameters = parameters
    def __call__(self, filename):
        sci = fits.open(filename + '.fits')
        manipulated = manipulate_image(sci, self.parameters)
        return manipulated

try:
    pool = Pool(8) # on 8 processors
    engine = Engine(my_parameters)
    data_outputs = pool.map(engine, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen
    pool.close()
    pool.join()

How do I create an Android Spinner as a popup?

android:spinnerMode="dialog"

// Creating adapter for spinner

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, categories);

// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);

How to make lists contain only distinct element in Python?

The simplest is to convert to a set then back to a list:

my_list = list(set(my_list))

One disadvantage with this is that it won't preserve the order. You may also want to consider if a set would be a better data structure to use in the first place, instead of a list.

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

In my case, I was importing a new database, and I wasnt able to connect again after that. Finally I realized that was a space problem.

So you can delete the last database and expand you hard drive or what I did, restored a snapshot of my virtual machine.

Just in case someone thinks that is useful

How can I make all images of different height and width the same via CSS?

Go to your CSS file and resize all your images as follows

img {
  width:  100px;
  height: 100px;
}

Display encoded html with razor

Try this:

<div class='content'>    
   @Html.Raw(HttpUtility.HtmlDecode(Model.Content))
</div>

How do I generate a random int number?

Every time you do new Random() it is initialized . This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.

//Function to get random number
private static readonly Random getrandom = new Random();

public static int GetRandomNumber(int min, int max)
{
    lock(getrandom) // synchronize
    {
        return getrandom.Next(min, max);
    }
}

Convert MFC CString to integer

CString s="143";
int x=atoi(s);

or

CString s=_T("143");
int x=_toti(s);

atoi will work, if you want to convert CString to int.

Freemarker iterating over hashmap keys

Iterating Objects

If your map keys is an object and not an string, you can iterate it using Freemarker.

1) Convert the map into a list in the controller:

List<Map.Entry<myObjectKey, myObjectValue>> convertedMap  = new ArrayList(originalMap.entrySet());

2) Iterate the map in the Freemarker template, accessing to the object in the Key and the Object in the Value:

<#list convertedMap as item>
    <#assign myObjectKey = item.getKey()/>
    <#assign myObjectValue = item.getValue()/>
    [...]
</#list>

How to set timeout on python's socket recv method?

As mentioned in previous replies, you can use something like: .settimeout() For example:

import socket

s = socket.socket()

s.settimeout(1) # Sets the socket to timeout after 1 second of no activity

host, port = "somehost", 4444
s.connect((host, port))

s.send("Hello World!\r\n")

try:
    rec = s.recv(100) # try to receive 100 bytes
except socket.timeout: # fail after 1 second of no activity
    print("Didn't receive data! [Timeout]")
finally:
    s.close()

I hope this helps!!

How to add new column to MYSQL table?

Something like:

$db = mysqli_connect("localhost", "user", "password", "database");
$name = $db->mysqli_real_escape_string($name);
$query = 'ALTER TABLE assesment ADD ' . $name . ' TINYINT NOT NULL DEFAULT \'0\'';
if($db->query($query)) {
    echo "It worked";
}

Haven't tested it but should work.

How to do encryption using AES in Openssl

I am trying to write a sample program to do AES encryption using Openssl.

This answer is kind of popular, so I'm going to offer something more up-to-date since OpenSSL added some modes of operation that will probably help you.

First, don't use AES_encrypt and AES_decrypt. They are low level and harder to use. Additionally, it's a software-only routine, and it will never use hardware acceleration, like AES-NI. Finally, its subject to endianess issues on some obscure platforms.

Instead, use the EVP_* interfaces. The EVP_* functions use hardware acceleration, like AES-NI, if available. And it does not suffer endianess issues on obscure platforms.

Second, you can use a mode like CBC, but the ciphertext will lack integrity and authenticity assurances. So you usually want a mode like EAX, CCM, or GCM. (Or you manually have to apply a HMAC after the encryption under a separate key.)

Third, OpenSSL has a wiki page that will probably interest you: EVP Authenticated Encryption and Decryption. It uses GCM mode.

Finally, here's the program to encrypt using AES/GCM. The OpenSSL wiki example is based on it.

#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include <string.h>   

int main(int arc, char *argv[])
{
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();     

    /* Set up the key and iv. Do I need to say to not hard code these in a real application? :-) */

    /* A 256 bit key */
    static const unsigned char key[] = "01234567890123456789012345678901";

    /* A 128 bit IV */
    static const unsigned char iv[] = "0123456789012345";

    /* Message to be encrypted */
    unsigned char plaintext[] = "The quick brown fox jumps over the lazy dog";

    /* Some additional data to be authenticated */
    static const unsigned char aad[] = "Some AAD data";

    /* Buffer for ciphertext. Ensure the buffer is long enough for the
     * ciphertext which may be longer than the plaintext, dependant on the
     * algorithm and mode
     */
    unsigned char ciphertext[128];

    /* Buffer for the decrypted text */
    unsigned char decryptedtext[128];

    /* Buffer for the tag */
    unsigned char tag[16];

    int decryptedtext_len = 0, ciphertext_len = 0;

    /* Encrypt the plaintext */
    ciphertext_len = encrypt(plaintext, strlen(plaintext), aad, strlen(aad), key, iv, ciphertext, tag);

    /* Do something useful with the ciphertext here */
    printf("Ciphertext is:\n");
    BIO_dump_fp(stdout, ciphertext, ciphertext_len);
    printf("Tag is:\n");
    BIO_dump_fp(stdout, tag, 14);

    /* Mess with stuff */
    /* ciphertext[0] ^= 1; */
    /* tag[0] ^= 1; */

    /* Decrypt the ciphertext */
    decryptedtext_len = decrypt(ciphertext, ciphertext_len, aad, strlen(aad), tag, key, iv, decryptedtext);

    if(decryptedtext_len < 0)
    {
        /* Verify error */
        printf("Decrypted text failed to verify\n");
    }
    else
    {
        /* Add a NULL terminator. We are expecting printable text */
        decryptedtext[decryptedtext_len] = '\0';

        /* Show the decrypted text */
        printf("Decrypted text is:\n");
        printf("%s\n", decryptedtext);
    }

    /* Remove error strings */
    ERR_free_strings();

    return 0;
}

void handleErrors(void)
{
    unsigned long errCode;

    printf("An error occurred\n");
    while(errCode = ERR_get_error())
    {
        char *err = ERR_error_string(errCode, NULL);
        printf("%s\n", err);
    }
    abort();
}

int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *aad,
            int aad_len, unsigned char *key, unsigned char *iv,
            unsigned char *ciphertext, unsigned char *tag)
{
    EVP_CIPHER_CTX *ctx = NULL;
    int len = 0, ciphertext_len = 0;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

    /* Initialise the encryption operation. */
    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
        handleErrors();

    /* Set IV length if default 12 bytes (96 bits) is not appropriate */
    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
        handleErrors();

    /* Initialise key and IV */
    if(1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();

    /* Provide any AAD data. This can be called zero or more times as
     * required
     */
    if(aad && aad_len > 0)
    {
        if(1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len))
            handleErrors();
    }

    /* Provide the message to be encrypted, and obtain the encrypted output.
     * EVP_EncryptUpdate can be called multiple times if necessary
     */
    if(plaintext)
    {
        if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
            handleErrors();

        ciphertext_len = len;
    }

    /* Finalise the encryption. Normally ciphertext bytes may be written at
     * this stage, but this does not occur in GCM mode
     */
    if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
    ciphertext_len += len;

    /* Get the tag */
    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag))
        handleErrors();

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    return ciphertext_len;
}

int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad,
            int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv,
            unsigned char *plaintext)
{
    EVP_CIPHER_CTX *ctx = NULL;
    int len = 0, plaintext_len = 0, ret;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

    /* Initialise the decryption operation. */
    if(!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
        handleErrors();

    /* Set IV length. Not necessary if this is 12 bytes (96 bits) */
    if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
        handleErrors();

    /* Initialise key and IV */
    if(!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();

    /* Provide any AAD data. This can be called zero or more times as
     * required
     */
    if(aad && aad_len > 0)
    {
        if(!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len))
            handleErrors();
    }

    /* Provide the message to be decrypted, and obtain the plaintext output.
     * EVP_DecryptUpdate can be called multiple times if necessary
     */
    if(ciphertext)
    {
        if(!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
            handleErrors();

        plaintext_len = len;
    }

    /* Set expected tag value. Works in OpenSSL 1.0.1d and later */
    if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tag))
        handleErrors();

    /* Finalise the decryption. A positive return value indicates success,
     * anything else is a failure - the plaintext is not trustworthy.
     */
    ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    if(ret > 0)
    {
        /* Success */
        plaintext_len += len;
        return plaintext_len;
    }
    else
    {
        /* Verify failed */
        return -1;
    }
}

Calling startActivity() from outside of an Activity?

In my case I have used context for startActivity, after changing that with ActivityName.this . it solves. I'm using method from util class so this happens.

Hope it help some one.

How does Go update third-party packages?

Go to path and type

go get -u ./..

It will update all require packages.

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

On the Mac you can store the passphrase for your private ssh key in your Keychain, which makes the use of it transparent. If you're logged in, it is available, when you are logged out your root user cannot use it. Removing the passphrase is a bad idea because anyone with the file can use it.

ssh-keygen -K

Add this to ~/.ssh/config

UseKeychain yes

Date Comparison using Java

This is one of the ways:

String toDate = "05/11/2010";

if (new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime() / (1000 * 60 * 60 * 24) >= System.currentTimeMillis() / (1000 * 60 * 60 * 24)) {
    System.out.println("Display report.");
} else {
    System.out.println("Don't display report.");
}

A bit more easy interpretable:

String toDateAsString = "05/11/2010";
Date toDate = new SimpleDateFormat("MM/dd/yyyy").parse(toDateAsString);
long toDateAsTimestamp = toDate.getTime();
long currentTimestamp = System.currentTimeMillis();
long getRidOfTime = 1000 * 60 * 60 * 24;
long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;
long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;

if (toDateAsTimestampWithoutTime >= currentTimestampWithoutTime) {
    System.out.println("Display report.");
} else {
    System.out.println("Don't display report.");
}

Oh, as a bonus, the JodaTime's variant:

String toDateAsString = "05/11/2010";
DateTime toDate = DateTimeFormat.forPattern("MM/dd/yyyy").parseDateTime(toDateAsString);
DateTime now = new DateTime();

if (!toDate.toLocalDate().isBefore(now.toLocalDate())) {
    System.out.println("Display report.");
} else {
    System.out.println("Don't display report.");
}

How to check whether a pandas DataFrame is empty?

I prefer going the long route. These are the checks I follow to avoid using a try-except clause -

  1. check if variable is not None
  2. then check if its a dataframe and
  3. make sure its not empty

Here, DATA is the suspect variable -

DATA is not None and isinstance(DATA, pd.DataFrame) and not DATA.empty

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

Can't ping a local VM from the host

I know this is an old post, but I ran into this same issue with my VMs. Log into the VM and go to Control Panel > System and Security > Windows Firewall > Allowed Apps. Then check all of the boxes next to "File and Printer Sharing" to enable file sharing. This should allow you to ping the VM. The screenshot below is from a 2016 Windows Server but the same method will work on older ones.

enter image description here

How to increase the vertical split window size in Vim

This is what I am using as of now:

nnoremap <silent> <Leader>= :exe "resize " . (winheight(0) * 3/2)<CR>
nnoremap <silent> <Leader>- :exe "resize " . (winheight(0) * 2/3)<CR>
nnoremap <silent> <Leader>0 :exe "vertical resize " . (winwidth(0) * 3/2)<CR>
nnoremap <silent> <Leader>9 :exe "vertical resize " . (winwidth(0) * 2/3)<CR>

Search for "does-not-contain" on a DataFrame in pandas

I was having trouble with the not (~) symbol as well, so here's another way from another StackOverflow thread:

df[df["col"].str.contains('this|that')==False]

Python conditional assignment operator

I think what you are looking for, if you are looking for something in a dictionary, is the setdefault method:

(Pdb) we=dict()
(Pdb) we.setdefault('e',14)
14
(Pdb) we['e']
14
(Pdb) we['r']="p"
(Pdb) we.setdefault('r','jeff')
'p'
(Pdb) we['r']
'p'
(Pdb) we[e]
*** NameError: name 'e' is not defined
(Pdb) we['e']
14
(Pdb) we['q2']

*** KeyError: 'q2' (Pdb)

The important thing to note in my example is that the setdefault method changes the dictionary if and only if the key that the setdefault method refers to is not present.

Scroll to element on click in Angular 4

You can achieve that by using the reference to an angular DOM element as follows:

Here is the example in stackblitz

the component template:

<div class="other-content">
      Other content
      <button (click)="element.scrollIntoView({ behavior: 'smooth', block: 'center' })">
        Click to scroll
      </button>
    </div>
    <div id="content" #element>
      Some text to scroll
</div>

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

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

it's very simple getting a name:

$('[name=elementname]');

Resource:

http://www.electrictoolbox.com/jquery-form-elements-by-name/ (google search: get element by name jQuery - first result)

Get the last element of a std::string

You could write a function template back that delegates to the member function for ordinary containers and a normal function that implements the missing functionality for strings:

template <typename C>
typename C::reference back(C& container)
{
    return container.back();
}

template <typename C>
typename C::const_reference back(const C& container)
{
    return container.back();
}

char& back(std::string& str)
{
    return *(str.end() - 1);
}

char back(const std::string& str)
{
    return *(str.end() - 1);
}

Then you can just say back(foo) without worrying whether foo is a string or a vector.

python: how to get information about a function?

In python: help(my_list.append) for example, will give you the docstring of the function.

>>> my_list = []
>>> help(my_list.append)

    Help on built-in function append:

    append(...)
        L.append(object) -- append object to end

Searching multiple files for multiple words

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to Search > Find in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (test1|test2)
  • Filters = *.txt
  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.
  • Search mode = Regular Expression