Programs & Examples On #Trinidad

Trinidad is a JSF component library. It is a subproject of Apache MyFaces. The codebase was born as Oracle ADF Faces and was later donated to Apache by Oracle. The codebase is of high quality and supports features as partial page rendering (ajax), integrated clientside validation, Section 508 accessibility, LTR languages, etc.

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

In SQL*Plus putting SET DEFINE ? at the top of the script will normally solve this. Might work for Oracle SQL Developer as well.

Get total number of items on Json object?

That's an Object and you want to count the properties of it.



Angular 2 optional route parameter

rerezz's answer is pretty nice but it has one serious flaw. It causes User component to re-run the ngOnInit method.

It might be problematic when you do some heavy stuff there and don't want it to be re-run when you switch from the non-parametric route to the parametric one. Though those two routes are meant to imitate an optional url parameter, not become 2 separate routes.

Here's what I suggest to solve the problem:

const routes = [
    path: '/user',
    component: User,
    children: [
      { path: ':id', component: UserWithParam, name: 'Usernew' }

Then you can move the logic responsible for handling the param to the UserWithParam component and leave the base logic in the User component. Whatever you do in User::ngOnInit won't be run again when you navigate from /user to /user/123.

Don't forget to put the <router-outlet></router-outlet> in the User's template.

Use LIKE %..% with field values in MySQL

  SELECT t1.a, t2.b
  FROM t1
  JOIN t2 ON t1.a LIKE '%'+t2.b +'%'

because the last answer not work

PHP Get all subdirectories of a given directory

Find all the files and folders under a specified directory.

function scanDirAndSubdir($dir, &$fullDir = array()){
    $currentDir = scandir($dir);

    foreach ($currentDir as $key => $val) {
        $realpath = realpath($dir . DIRECTORY_SEPARATOR . $val);
        if (!is_dir($realpath) && $filename != "." && $filename != "..") {
            scanDirAndSubdir($realpath, $fullDir);
            $fullDir[] = $realpath;

    return $fullDir;


Sample :

array (size=4)
  0 => string 'C:/web2.0/config/' (length=17)
  1 => string 'C:/web2.0/js/' (length=13)
  2 => string 'C:/web2.0/mydir/' (length=16)
  3 => string 'C:/web2.0/myfile/' (length=17)

Getting the parameters of a running JVM

Alternatively, you can use jinfo

jinfo -flags <vmid> 
jinfo -sysprops <vmid>

How to get jQuery dropdown value onchange event

Add try this code .. Its working grt.......

 if (isset($_POST['nav'])) {_x000D_
   header("Location: $_POST[nav]");_x000D_
<form id="page-changer" action="" method="post">_x000D_
    <select name="nav">_x000D_
        <option value="">Go to page...</option>_x000D_
        <option value="">CSS-Tricks</option>_x000D_
        <option value="">Digging Into WordPress</option>_x000D_
        <option value="">Quotes on Design</option>_x000D_
    <input type="submit" value="Go" id="submit" />_x000D_
<script type="text/javascript" src="//"></script>_x000D_
$(function() {_x000D_
    $("#page-changer select").change(function() {_x000D_
        window.location = $("#page-changer select option:selected").val();_x000D_

tsc throws `TS2307: Cannot find module` for a local file

I was in trouble to import an Enum in typescript

error TS2307: Cannot find module...

What I did to make it work was migrate the enum to another file and make this change:

export enum MyEnum{


export enum MyEnum{
    VALUE = 1

In Python, how do I index a list with another list?

L= {'a':'a','d':'d', 'h':'h'}
index= ['a','d','h'] 
for keys in index:

I would use a Dict add desired keys to index

How do I check if a Sql server string is null or empty

    COALESCE(listing.OfferText, 'company.OfferText') AS Offer_Text,         
    tbl_directorylisting listing  
    INNER JOIN tbl_companymaster company ON listing.company_id= company.company_id

Where do I configure log4j in a JUnit test class?

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

TypeError: 'module' object is not callable

Add to the main in YourClassParentDir, e.g.:

from .YourClass import YourClass

Then, you will have an instance of your class ready when you import it into another script:

from YourClassParentDir import YourClass

Measuring function execution time in R

The package "tictoc" gives you a very simple way of measuring execution time. The documentation is in:


To save the elapsed time into a variable you can do:

exectime <- toc()
exectime <- exectime$toc - exectime$tic

Reading in double values with scanf in c

Format specifier in printf should be %f for doubl datatypes since float datatyles eventually convert to double datatypes inside printf.

There is no provision to print float data. Please find the discussion here : Correct format specifier for double in printf

jQuery - select all text from a textarea

Selecting text in an element (akin to highlighting with your mouse)


Using the accepted answer on that post, you can call the function like this:

$(function() {
  $('#textareaId').click(function() {

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

The Provider piece must be Provider=Microsoft.ACE.OLEDB.12.0 if your target database is ACCDB format. Provider=Microsoft.Jet.OLEDB.4.0 only works for the older MDB format.

You shouldn't even need Access installed if you're running 32 bit Windows. Jet 4 is included as part of the operating system. If you're using 64 bit Windows, Jet 4 is not included, but you still wouldn't need Access itself installed. You can install the Microsoft Access Database Engine 2010 Redistributable. Make sure to download the matching version (AccessDatabaseEngine.exe for 32 bit Windows, or AccessDatabaseEngine_x64.exe for 64 bit).

You can avoid the issue about which ADO version reference by using late binding, which doesn't require any reference.

Dim conn As Object
Set conn = CreateObject("ADODB.Connection")

Then assign your ConnectionString property to the conn object. Here is a quick example which runs from a code module in Excel 2003 and displays a message box with the row count for MyTable. It uses late binding for the ADO connection and recordset objects, so doesn't require setting a reference.

Public Sub foo()
    Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\Access\webforums\whiteboard2003.mdb"
    strSql = "SELECT Count(*) FROM MyTable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.fields(0) & " rows in MyTable"
    Set rs = Nothing
    Set cn = Nothing
End Sub

If this answer doesn't resolve the problem, edit your question to show us the full connection string you're trying to use and the exact error message you get in response for that connection string.

Random shuffling of an array

Using ArrayList<Integer> can help you solving the problem of shuffling without applying much of logic and consuming less time. Here is what I suggest:

ArrayList<Integer> x = new ArrayList<Integer>();
for(int i=1; i<=add.length(); i++)

Image re-size to 50% of original size in HTML

We can do this by css3 too. Try this:

.halfsize {

<img class="halfsize" src="image4.jpg">
  • subjected to browser compatibility

Removing spaces from a variable input using PowerShell 4.0

You also have the Trim, TrimEnd and TrimStart methods of the System.String class. The trim method will strip whitespace (with a couple of Unicode quirks) from the leading and trailing portion of the string while allowing you to optionally specify the characters to remove.

#Note there are spaces at the beginning and end
Write-Host " ! This is a test string !%^ "
 ! This is a test string !%^
#Strips standard whitespace
Write-Host " ! This is a test string !%^ ".Trim()
! This is a test string !%^
#Strips the characters I specified
Write-Host " ! This is a test string !%^ ".Trim('!',' ')
This is a test string !%^
#Now removing ^ as well
Write-Host " ! This is a test string !%^ ".Trim('!',' ','^')
This is a test string !%
Write-Host " ! This is a test string !%^ ".Trim('!',' ','^','%')
This is a test string
#Powershell even casts strings to character arrays for you
Write-Host " ! This is a test string !%^ ".Trim('! ^%')
This is a test string

TrimStart and TrimEnd work the same way just only trimming the start or end of the string.

git am error: "patch does not apply"

I had the same problem. I had used

git format-patch <commit_hash>

to create the patch. My main problem was patch was failing due to some conflicts, but I could not see any merge conflict in the file content. I had used git am --3way <patch_file_path> to apply the patch.

The correct command to apply the patch should be:

git am --3way --ignore-space-change <patch_file_path>

If you execute the above command for patching, it will create a merge conflict if patch apply fails. Then you can fix the conflict in your files, like the same way merge conflicts are resolved for git merge

Setting the correct encoding when piping stdout in Python

I could "automate" it with a call to:

def __fix_io_encoding(last_resort_default='UTF-8'):
  import sys
  if [x for x in (sys.stdin,sys.stdout,sys.stderr) if x.encoding is None] :
      import os
      defEnc = None
      if defEnc is None :
          import locale
          defEnc = locale.getpreferredencoding()
        except: pass
      if defEnc is None :
        try: defEnc = sys.getfilesystemencoding()
        except: pass
      if defEnc is None :
        try: defEnc = sys.stdin.encoding
        except: pass
      if defEnc is None :
        defEnc = last_resort_default
      os.environ['PYTHONIOENCODING'] = os.environ.get("PYTHONIOENCODING",defEnc)
__fix_io_encoding() ; del __fix_io_encoding

Yes, it's possible to get an infinite loop here if this "setenv" fails.

Arithmetic overflow error converting numeric to data type numeric

Use TRY_CAST function in exact same way of CAST function. TRY_CAST takes a string and tries to cast it to a data type specified after the AS keyword. If the conversion fails, TRY_CAST returns a NULL instead of failing.

bootstrap button shows blue outline when clicked

May be your properties are getting overridden. Try attaching !important to your code along with the :active .

.btn:focus,.btn:active {
   outline: none !important;
   box-shadow: none;

Also add box-shadow because otherwise you will still see the shadow around button.

Although this isn't a good practise to use !important I suggest you use more specific class and then try applying the css with the use of !important...

How to pass data from Javascript to PHP and vice versa?

There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.

<script language="javascript" type="text/javascript">
 function _vals(target, value){

Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.

I'm sure there's probably more methods which are better, but these are just a few that spring to mind.

EDIT: Building on this from what others have said using the above method you would have an anchor tag like

<a onclick="_vals('name', 'val')" href="#">My Link</a>

And then in your PHP you can get form data using

$val = $_POST['value'];

So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

Google Play app description formatting

Experimentally, I've discovered that you can provide:

  • Single line breaks are ignored; double line breaks open a new paragraph.
  • Single line breaks can be enforced by ending a line with two spaces (similar to Markdown).
  • A limited set of HTML tags (optionally nested), specifically:
    • <b>…</b> for boldface,
    • <i>…</i> for italics,
    • <u>…</u> for underline,
    • <br /> to enforce a single line break,
    • I could not find any way to get strikethrough working (neither HTML or Markdown style).
  • A fully-formatted URL such as; this appears as a hyperlink.
    (Beware that trying to use an HTML <a> tag for a custom description does not work and breaks the formatting.)
  • HTML character entities are supported, such as &rarr; (→), &trade; (™) and &reg; (®); consult this W3 reference for the exhaustive list.
  • UTF-8 encoded characters are supported, such as é, €, £, ‘, ’, ? and ?.
  • Indentation isn't strictly possible, but using a bullet and em space character looks reasonable (&#8226;&#8195; yields "• ").
  • Emoji are also supported (though on the website depends on the user's OS & browser).

Special notes concerning only Google Play app:

  • Some HTML tags only work in the app:
    • <blockquote>…</blockquote> to indent a paragraph of text,
    • <small>…</small> for slightly smaller text,
    • <big>…</big> for slightly larger text,
    • <sup>…</sup> and <sub>…</sub> for super- and subscripts.
    • <font color="#a32345">…</font> for setting font colors in HEX code.
  • Some symbols do not appear correctly, such as ‣.
  • All these notes also apply to the app's "What's New" section.

Special notes concerning only Google Play website:

  • All HTML formatting appears as plain text in the website's "What's New" section (i.e. users will see the HTML source).

How to detect if JavaScript is disabled?

In some cases, doing it backwards could be sufficient. Add a class using javascript:

// Jquery

/* CSS */
.menu-mobile {display:none;}
body.js-enabled .menu-mobile {display:block;}

This could create maintenance issues on anything complex, but it's a simple fix for some things. Rather than trying to detect when it's not loaded, just style according to when it is loaded.

ASP.NET MVC 3 - redirect to another action

return RedirectToAction("ActionName", "ControllerName");

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

try this....

DECLARE @strsql VARCHAR(300)

SELECT @tname = (SELECT TOP 1 [name] FROM sys.objects WHERE [type] = 'U' and [name] like N'TableName%' ORDER BY [name])

    SELECT @strsql = 'DROP TABLE [dbo].[' + RTRIM(@tname) +']'
    EXEC (@strsql)
    PRINT 'Dropped Table : ' + @tname
    SELECT @tname = (SELECT TOP 1 [name] FROM sys.objects WHERE [type] = 'U' AND [name] like N'TableName%'  AND [name] > @tname ORDER BY [name])

get list of packages installed in Anaconda

For script creation at Windows cmd or powershell prompt:

C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3
conda list
pip list

PostgreSQL return result set as JSON array?


SELECT json_agg(t) FROM t

for a JSON array of objects, and

        'a', json_agg(t.a),
        'b', json_agg(t.b)

for a JSON object of arrays.

List of objects

This section describes how to generate a JSON array of objects, with each row being converted to a single object. The result looks like this:


9.3 and up

The json_agg function produces this result out of the box. It automatically figures out how to convert its input into JSON and aggregates it into an array.

SELECT json_agg(t) FROM t

There is no jsonb (introduced in 9.4) version of json_agg. You can either aggregate the rows into an array and then convert them:

SELECT to_jsonb(array_agg(t)) FROM t

or combine json_agg with a cast:

SELECT json_agg(t)::jsonb FROM t

My testing suggests that aggregating them into an array first is a little faster. I suspect that this is because the cast has to parse the entire JSON result.


9.2 does not have the json_agg or to_json functions, so you need to use the older array_to_json:

SELECT array_to_json(array_agg(t)) FROM t

You can optionally include a row_to_json call in the query:

SELECT array_to_json(array_agg(row_to_json(t))) FROM t

This converts each row to a JSON object, aggregates the JSON objects as an array, and then converts the array to a JSON array.

I wasn't able to discern any significant performance difference between the two.

Object of lists

This section describes how to generate a JSON object, with each key being a column in the table and each value being an array of the values of the column. It's the result that looks like this:

{"a":[1,2,3], "b":["value1","value2","value3"]}

9.5 and up

We can leverage the json_build_object function:

        'a', json_agg(t.a),
        'b', json_agg(t.b)

You can also aggregate the columns, creating a single row, and then convert that into an object:

SELECT to_json(r)
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r

Note that aliasing the arrays is absolutely required to ensure that the object has the desired names.

Which one is clearer is a matter of opinion. If using the json_build_object function, I highly recommend putting one key/value pair on a line to improve readability.

You could also use array_agg in place of json_agg, but my testing indicates that json_agg is slightly faster.

There is no jsonb version of the json_build_object function. You can aggregate into a single row and convert:

SELECT to_jsonb(r)
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

Unlike the other queries for this kind of result, array_agg seems to be a little faster when using to_jsonb. I suspect this is due to overhead parsing and validating the JSON result of json_agg.

Or you can use an explicit cast:

        'a', json_agg(t.a),
        'b', json_agg(t.b)

The to_jsonb version allows you to avoid the cast and is faster, according to my testing; again, I suspect this is due to overhead of parsing and validating the result.

9.4 and 9.3

The json_build_object function was new to 9.5, so you have to aggregate and convert to an object in previous versions:

SELECT to_json(r)
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r


SELECT to_jsonb(r)
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

depending on whether you want json or jsonb.

(9.3 does not have jsonb.)


In 9.2, not even to_json exists. You must use row_to_json:

SELECT row_to_json(r)
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r


Find the documentation for the JSON functions in JSON functions.

json_agg is on the aggregate functions page.


If performance is important, ensure you benchmark your queries against your own schema and data, rather than trust my testing.

Whether it's a good design or not really depends on your specific application. In terms of maintainability, I don't see any particular problem. It simplifies your app code and means there's less to maintain in that portion of the app. If PG can give you exactly the result you need out of the box, the only reason I can think of to not use it would be performance considerations. Don't reinvent the wheel and all.


Aggregate functions typically give back NULL when they operate over zero rows. If this is a possibility, you might want to use COALESCE to avoid them. A couple of examples:

SELECT COALESCE(json_agg(t), '[]'::json) FROM t


SELECT to_jsonb(COALESCE(array_agg(t), ARRAY[]::t[])) FROM t

Credit to Hannes Landeholm for pointing this out

Calling functions in a DLL from C++

Might be useful:

For the example above with "GetWelcomeMessage" you might need to specify "__stdcall" in the typedef field before the function name if getting error after calling imported function.

How to vertically align a html radio button to it's label?

Something like this should work


input {
    float: left;
    clear: left;
    width: 50px;
    line-height: 20px;

label {
    float: left;
    vertical-align: middle;

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

We can use ng-src but when ng-src's value became null, '' or undefined, ng-src will not work. So just use ng-if for this case:

<div ng-app>
    <div ng-controller="AppCtrl"> 
        <a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
        <button ng-click="changeLink()">Change Image</button>

C# Threading - How to start and stop a thread

This is how I do it...

public class ThreadA {
    public ThreadA(object[] args) {
    public void Run() {
        while (true) {
            Thread.sleep(1000); // wait 1 second for something to happen.
            if(conditionToExitReceived) // what im waiting for...
        //perform cleanup if there is any...

Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)

private void FireThread(){
    Thread thread = new Thread(new ThreadStart(this.startThread));
private void (startThread){
    new ThreadA(args).Run();

The thread is created by calling "FireThread()"

The newly created thread will run until its condition to stop is met, then it dies...

You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...

Best to read through : This MSDN Article

How to playback MKV video in web browser?

<video controls width=800 autoplay>
    <source src="file path here">

This will display the video (.mkv) using Google Chrome browser only.

regular expression for anything but an empty string

Assertions are not necessary for this. \S should work by itself as it matches any non-whitespace.

Remove property for all objects in array

For my opinion this is the simplest variant{good}) => ({good}))

Set title background color

I have done this by changing style color values in "res" -> "values" -> "colors.xml" enter image description here

This will change colors for entire project which is fine with me.

enter image description here

Do we need type="text/css" for <link> in HTML5

The HTML5 spec says that the type attribute is purely advisory and explains in detail how browsers should act if it's omitted (too much to quote here). It doesn't explicitly say that an omitted type attribute is either valid or invalid, but you can safely omit it knowing that browsers will still react as you expect.

Error:(23, 17) Failed to resolve: junit:junit:4.12

Go to File -> Project Structure. Following window will open:

enter image description here

From there:

  1. remove the junit library (select junit and press "-" button below ) and
  2. add it again (select "+" button below, select "library dep.", search for "junit", press OK ). Press OK to apply changes. After around 30 seconds your gradle sync should work fine.

Hope it works for you too :D

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

MacPorts is another package manager for OS X:.

Installation instructions are at The MacPorts Project -- Download & Installation after which one issues sudo port install pythonXX, where XX is 27 or 35.

What is Persistence Context?

While @pritam kumar gives a good overview the 5th point is not true.

Persistence Context can be either Transaction Scoped-- the Persistence Context 'lives' for the length of the transaction, or Extended-- the Persistence Context spans multiple transactions.

JPA's EntityManager and Hibernate's Session offer an extended Persistence Context.

Listing only directories using ls in Bash?

To show folder lists without /:

ls -d */|sed 's|[/]||g'

How to convert DataTable to class Object?

Initialize DataTable:

DataTable dt = new DataTable(); 
dt.Columns.Add("id", typeof(String)); 
dt.Columns.Add("name", typeof(String)); 
for (int i = 0; i < 5; i++)
    string index = i.ToString();
    dt.Rows.Add(new object[] { index, "name" + index });

Query itself:

IList<Class1> items = dt.AsEnumerable().Select(row => 
    new Class1
            id = row.Field<string>("id"),
            name = row.Field<string>("name")

Avoid line break between html elements

In some cases (e.g. html generated and inserted by JavaScript) you also may want to try to insert a zero width joiner:

  width: 290px;   _x000D_
  white-space: no-wrap;_x000D_
  overflow:auto; _x000D_
  border: 1px solid gray;_x000D_
  display: inline;_x000D_
  white-space: no-wrap;_x000D_
.no-break-before {_x000D_
  padding-left: 10px;_x000D_
<div class="wrapper">_x000D_
<span class="breakable-text">Lorem dorem tralalalala LAST_WORDS</span>&#8205;<span class="no-break-before">TOGETHER</span>_x000D_

How the single threaded non blocking IO model works in Node.js

The function c.query() has two argument

c.query("Fetch Data", "Post-Processing of Data")

The operation "Fetch Data" in this case is a DB-Query, now this may be handled by Node.js by spawning off a worker thread and giving it this task of performing the DB-Query. (Remember Node.js can create thread internally). This enables the function to return instantaneously without any delay

The second argument "Post-Processing of Data" is a callback function, the node framework registers this callback and is called by the event loop.

Thus the statement c.query (paramenter1, parameter2) will return instantaneously, enabling node to cater for another request.

P.S: I have just started to understand node, actually I wanted to write this as comment to @Philip but since didn't have enough reputation points so wrote it as an answer.

MySQL Workbench Edit Table Data is read only

This is the Known limitation in MySQLWorkbench (you can't edit table w/o PK):

To Edit the Table:

Method 1: (method not working in somecases)
right-click on a table within the Object Browser and choose the Edit Table Data option from there.

Method 2:
I would rather suggest you to add Primary Key Instead:

ALTER TABLE `your_table_name` ADD PRIMARY KEY (`column_name`);

and you might want to remove the existing rows first:

Truncate table your_table_name

How to set menu to Toolbar in Android

Don't use setSupportActionBar(toolbar)

I don't know why but this works for me.

toolbar = (Toolbar) findViewById(;
toolbar.setSubtitle("Test Subtitle");

For menu item click do this

toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

        public boolean onMenuItemClick(MenuItem item) {

                // do something
            else if(item.getItemId()==
               // do something
               // do something

            return false;

Will update the 'why' part of this answer when I find a proper explanation.
Happy to help anyway :) Peace.

Custom CSS Scrollbar for Firefox

May I offer an alternative?

No scripting whatsoever, only standardized css styles and a little bit of creativity. Short answer - masking parts of the existing browser scrollbar, which means you retain all of it's functionality.

.scroll_content {
    position: relative;
    width: 400px;
    height: 414px;
    top: -17px;
    padding: 20px 10px 20px 10px;
    overflow-y: auto;

For demo and a little bit more in-depth explanation, check here...

Using Java generics for JPA findAll() query with WHERE clause

you can also use a namedQuery named findAll for all your entities and call it in your generic FindAll with


How do I change the font color in an html table?

<select name="test" style="color: red;">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>

Excel Create Collapsible Indented Row Hierarchies

A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

Floating point comparison functions for C#

Here's how I solved it, with nullable double extension method.

    public static bool NearlyEquals(this double? value1, double? value2, double unimportantDifference = 0.0001)
        if (value1 != value2)
            if(value1 == null || value2 == null)
                return false;

            return Math.Abs(value1.Value - value2.Value) < unimportantDifference;

        return true;


        double? value1 = 100;
        value1.NearlyEquals(100.01); // will return false
        value1.NearlyEquals(100.000001); // will return true
        value1.NearlyEquals(100.01, 0.1); // will return true

Difference between database and schema

Schema in SQL Server is an object that conceptually holds definitions for other database objects such as tables,views,stored procedures etc.

What is the Sign Off feature in Git for?

Sign-off is a requirement for getting patches into the Linux kernel and a few other projects, but most projects don't actually use it.

It was introduced in the wake of the SCO lawsuit, (and other accusations of copyright infringement from SCO, most of which they never actually took to court), as a Developers Certificate of Origin. It is used to say that you certify that you have created the patch in question, or that you certify that to the best of your knowledge, it was created under an appropriate open-source license, or that it has been provided to you by someone else under those terms. This can help establish a chain of people who take responsibility for the copyright status of the code in question, to help ensure that copyrighted code not released under an appropriate free software (open source) license is not included in the kernel.

How to reload a page using JavaScript

I was looking for some information regarding reloads on pages retrieved with POST requests, such as after submitting a method="post" form.

To reload the page keeping the POST data, use:


To reload the page discarding the POST data (perform a GET request), use:

window.location.href = window.location.href;

Hopefully this can help others looking for the same information.

How to resize html canvas element?

You didn't publish your code, and I suspect you do something wrong. it is possible to change the size by assigning width and height attributes using numbers:

canvasNode.width  = 200; // in pixels
canvasNode.height = 100; // in pixels

At least it works for me. Make sure you don't assign strings (e.g., "2cm", "3in", or "2.5px"), and don't mess with styles.

Actually this is a publicly available knowledge — you can read all about it in the HTML canvas spec — it is very small and unusually informative. This is the whole DOM interface:

interface HTMLCanvasElement : HTMLElement {
           attribute unsigned long width;
           attribute unsigned long height;

  DOMString toDataURL();
  DOMString toDataURL(in DOMString type, [Variadic] in any args);

  DOMObject getContext(in DOMString contextId);

As you can see it defines 2 attributes width and height, and both of them are unsigned long.

Mocking HttpClient in unit tests

Perhaps there would be some code to change in your current project but for new projects you should absolutely consider using Flurl.

It is a HTTP client library for .NET with a fluent interface that specifically enables testability for code that uses it to make HTTP requests.

There are plenty of code samples on the website but in a nutshell you use it like this in your code.

Add the usings.

using Flurl;
using Flurl.Http;

Send a get request and read the response.

public async Task SendGetRequest()
   var response = await "".GetAsync();
   // ...

In the unit tests Flurl acts as a mock that can be configured to behave as desired and also to verify the calls that were done.

using (var httpTest = new HttpTest())
   // Arrange
   httpTest.RespondWith("OK", 200);

   // Act
   await sut.SendGetRequest();

   // Assert

ScrollTo function in AngularJS

Another suggestion. One directive with selector.


<button type="button" scroll-to="#catalogSection">Scroll To</button>


app.directive('scrollTo', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click', function () {

                var target = $(attrs.scrollTo);
                if (target.length > 0) {
                    $('html, body').animate({
                        scrollTop: target.offset().top

Also notice $anchorScroll

JQuery $.ajax() post - data in a java servlet

Simple method to sending data using java script and ajex call.

First right your form like this

<form id="frm_details" method="post" name="frm_details">
<input  id="email" name="email" placeholder="Your Email id" type="text" />
    <button class="subscribe-box__btn" type="submit">Need Assistance</button>

javascript logic target on form id #frm_details after sumbit

        $("#frm_details").on("submit", function(event) {

            var formData = {
                'email': $('input[name=email]').val() //for get email 

                url: "/tsmisc/api/subscribe-newsletter",
                type: "post",
                data: formData,
                success: function(d) {

Request URL:
Request Method:POST
Status Code:200 
Remote Address:

From Data
email:[email protected]

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

First, check that your origin is set by running

git remote -v

This should show you all of the push / fetch remotes for the project.

If this returns with no output, skip to last code block.

Verify remote name / address

If this returns showing that you have remotes set, check that the name of the remote matches the remote you are using in your commands.

$git remote -v
myOrigin ssh://[email protected]:1234/myRepo.git (fetch)
myOrigin ssh://[email protected]:1234/myRepo.git (push)

# this will fail because `origin` is not set
$git push origin master

# you need to use
$git push myOrigin master

If you want to rename the remote or change the remote's URL, you'll want to first remove the old remote, and then add the correct one.

Remove the old remote

$git remote remove myOrigin

Add missing remote

You can then add in the proper remote using

$git remote add origin ssh://[email protected]:1234/myRepo.git

# this will now work as expected
$git push origin master

Which characters need to be escaped in HTML?

Basically, there are three main characters which should be always escaped in your HTML and XML files, so they don't interact with the rest of the markups, so as you probably expect, two of them gonna be the syntax wrappers, which are <>, they are listed as below:

 1)  &lt; (<)
 2)  &gt; (>)
 3)  &amp; (&)

Also we may use double-quote (") as " and the single quote (') as &apos

Avoid putting dynamic content in <script> and <style>.These rules are not for applied for them. For example, if you have to include JSON in a , replace < with \x3c, the U+2028 character with \u2028, and U+2029 with \u2029 after JSON serialisation.)

HTML Escape Characters: Complete List:

So you need to escape <, or & when followed by anything that could begin a character reference. Also The rule on ampersands is the only such rule for quoted attributes, as the matching quotation mark is the only thing that will terminate one. But if you don’t want to terminate the attribute value there, escape the quotation mark.

Changing to UTF-8 means re-saving your file:

Using the character encoding UTF-8 for your page means that you can avoid the need for most escapes and just work with characters. Note, however, that to change the encoding of your document, it is not enough to just change the encoding declaration at the top of the page or on the server. You need to re-save your document in that encoding. For help understanding how to do that with your application read Setting encoding in web authoring applications.

Invisible or ambiguous characters:

A particularly useful role for escapes is to represent characters that are invisible or ambiguous in presentation.

One example would be Unicode character U+200F RIGHT-TO-LEFT MARK. This character can be used to clarify directionality in bidirectional text (eg. when using the Arabic or Hebrew scripts). It has no graphic form, however, so it is difficult to see where these characters are in the text, and if they are lost or forgotten they could create unexpected results during later editing. Using ? (or its numeric character reference equivalent ?) instead makes it very easy to spot these characters.

An example of an ambiguous character is U+00A0 NO-BREAK SPACE. This type of space prevents line breaking, but it looks just like any other space when used as a character. Using   makes it quite clear where such spaces appear in the text.

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

Try this for check current device is iPhone or iPad:

Swift 5

struct Device {
    static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad
    static let IS_IPHONE = UIDevice.current.userInterfaceIdiom == .phone


    // device is iPhone
    // device is iPad (or a Mac running under macOS Catalyst)
    // other

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

Even though this question is answered, providing an example as to what "theirs" and "ours" means in the case of git rebase vs merge. See this link

Git Rebase
theirs is actually the current branch in the case of rebase. So the below set of commands are actually accepting your current branch changes over the remote branch.

# see current branch
$ git branch
* branch-a
# rebase preferring current branch changes during conflicts
$ git rebase -X theirs branch-b

Git Merge
For merge, the meaning of theirs and ours is reversed. So, to get the same effect during a merge, i.e., keep your current branch changes (ours) over the remote branch being merged (theirs).

# assuming branch-a is our current version
$ git merge -X ours branch-b  # <- ours: branch-a, theirs: branch-b

Convert a string to datetime in PowerShell

ParseExact is told the format of the date it is expected to parse, not the format you wish to get out.

$invoice = '01-Jul-16'
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null)

If you then wish to output a date string:

[datetime]::parseexact($invoice, 'dd-MMM-yy', $null).ToString('yyyy-MM-dd')


Best way to remove duplicate entries from a data table

In order to distinct all datatable columns, you can easily retrieve the names of the columns in a string array

public static DataTable RemoveDuplicateRows(this DataTable dataTable)
    List<string> columnNames = new List<string>();
    foreach (DataColumn col in dataTable.Columns)
    return dataTable.DefaultView.ToTable(true, columnNames.Select(c => c.ToString()).ToArray());

As you can notice, I thought of using it as an extension to DataTable class

Bad Request - Invalid Hostname IIS7

For Visual Studio 2017 and Visual Studio 2015, IIS Express settings is stored in the hidden .vs directory and the path is something like this .vs\config\applicationhost.config, add binding like below will work

    <binding protocol="http" bindingInformation="*:8802:localhost" />
    <binding protocol="http" bindingInformation="*:8802:" />


Multiple Java versions running concurrently under Windows

We can install multiple versions of Java Development kits on the same machine using SDKMan.

Some points about SDKMan are as following:

  1. SDKMan is free to use and it is developed by the open source community.
  2. SDKMan is written in bash and it only requires curl and zip/unzip programs to be present on your system.
  3. SDKMan can install around 29 Software Development Kits for the JVM such as Java, Groovy, Scala, Kotlin and Ceylon. Ant, Gradle, Grails, Maven, SBT, Spark, Spring Boot, Vert.x.
  4. We do not need to worry about setting the _HOME and PATH environment variables because SDKMan handles it automatically.

SDKMan can run on any UNIX based platforms such as Mac OSX, Linux, Cygwin, Solaris and FreeBSD and we can install it using following commands:

$ curl -s "" | bash  
$ source "$HOME/.sdkman/bin/" 

Because SDKMan is written in bash and only requires curl and zip/unzip to be present on your system. You can install SDKMan on windows as well either by first installing Cygwin or Git Bash for Windows environment and then running above commands.

Command sdk list java will give us a list of java versions which we can install using SDKMan.

Installing Java 8

$ sdk install java 8.0.201-oracle

Installing Java 9

$ sdk install java 9.0.4-open 

Installing Java 11

$ sdk install java 11.0.2-open

Uninstalling a Java version

In case you want to uninstall any JDK version e.g., 11.0.2-open you can do that as follows:

$ sdk uninstall java 11.0.2-open

Switching current Java version

If you want to activate one version of JDK for all terminals and applications, you can use the command

sdk default java <your-java_version>

Above commands will also update the PATH and JAVA_HOME variables automatically. You can read more on my article How to Install Multiple Versions of Java on the Same Machine.

Check existence of input argument in a Bash shell script

As a small reminder, the numeric test operators in Bash only work on integers (-eq, -lt, -ge, etc.)

I like to ensure my $vars are ints by

var=$(( var + 0 ))

before I test them, just to defend against the "[: integer arg required" error.

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

You use RAISE_APPLICATION_ERROR in order to create an Oracle style exception/error that is specific to your code/needs. Good use of these help to produce code that is clearer, more maintainable, and easier to debug.

For example, if I have an application calling a stored procedure that adds a user and that user already exists, you'll usually get back an error like:

ORA-00001: unique constraint (USERS.PK_USER_KEY) violated

Obviously this error and associated message are not unique to the task you were trying to do. Creating your own Oracle application errors allow you to be clearer on the intent of the action and the cause of the issue.

raise_application_error(-20101, 'User ' || in_user || ' already exists!');

Now your application code can write an exception handler in order to process this specific error condition. Think of it as a way to make Oracle communicate error conditions that your application expects in a "language" (for lack of a better term) that you have defined and is more meaningful to your application's problem domain.

Note that user defined errors must be in the range between -20000 and -20999.

The following link provides lots of good information on this topic and Oracle exceptions in general.

How do I specify the platform for MSBuild?

When you define different build configurations in your visual studio solution for your projects using a tool like ConfigurationTransform, you may want your Teamcity build, to build you a specified build configuration. You may have build configurations e.g., Debug, Release, Dev, UAT, Prod etc defined. This means, you will have MSBuild Configuration transformation setup for the different configurations. These different configurations are usually used when you have different configurations, e.g. different database connection strings, for the different environment. This is very common because you would have a different database for your production environment from your playground development environment.

They say a picture is worth a thousand words, please see the image below how you would specify multiple build configurations in Teamcity.

In the commandline input text box, specify as below


Here, I have specified two commandline build configurations/arguments OutputPath and build Configuration with values Publish and Dev respectively, but it could have been, UAT or Prod configuration. If you want more, simply separate them by semi-colon,;

Teamcity MSBuild Commandline build configuration screenshot

How does @synchronized lock/unlock in Objective-C?


  @synchronized(self) {
    return [[myString retain] autorelease];

transforms directly into:

// needs #import <objc/objc-sync.h>
    id retVal = [[myString retain] autorelease];
  return retVal;

This API available since iOS 2.0 and imported using...

#import <objc/objc-sync.h>

How to do case insensitive search in Vim

As others suggested:

:set ic

But the cool stuff is You can toggle such modes with:

:set ic!

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

The emulator tries to find a numeric keypad on the mac, but this is not found (MacBook Pro, MacBook Air and "normal/small" keyboard do not have it). You can deselect the option Connect Hardware Keyboard or just ignore the error message, it will have no negative effect on application.

shuffling/permutating a DataFrame in pandas

Sampling randomizes, so just sample the entire data frame.


How to show progress bar while loading, using ajax

I did it like this


html {
    -webkit-transition: background-color 1s;
    transition: background-color 1s;
html, body {
    /* For the loading indicator to be vertically centered ensure */
    /* the html and body elements take up the full viewport */
    min-height: 100%;
html.loading {
    /* Replace #333 with the background-color of your choice */
    /* Replace loading.gif with the loading image of your choice */
    background: #333 url('/Images/loading.gif') no-repeat 50% 50%;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: background-color 0;
    transition: background-color 0;
body {
    -webkit-transition: opacity 1s ease-in;
    transition: opacity 1s ease-in;
html.loading body {
    /* Make the contents of the body opaque during loading */
    opacity: 0;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: opacity 0;
    transition: opacity 0;


$(document).ready(function () {
   $(document).ajaxStart(function () {     
    $(document).ajaxStop(function () {        
    $(document).ajaxError(function () {       

What does the exclamation mark do before the function?

! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.

Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.

Instead, use the closing parenthesis and the BANG (!) if needed.

// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.

(function(){ return false; }());
=> false

!(function(){ return false; }());
=> true

!!(function(){ return false; }());
=> false

!!!(function(){ return false; }());
=> true

Other Operators that work...

+(function(){ return false; }());
=> 0

-(function(){ return false; }());
=> -0

~(function(){ return false; }());
=> -1

Combined Operators...

+!(function(){ return false; }());
=> 1

-!(function(){ return false; }());
=> -1

!+(function(){ return false; }());
=> true

!-(function(){ return false; }());
=> true

~!(function(){ return false; }());
=> -2

~!!(function(){ return false; }());
=> -1

+~(function(){ return false; }());
+> -1

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;

.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    </table>    _x000D_
  <div class="box">_x000D_
    </table>    _x000D_
  <div class="box">_x000D_
    </table>    _x000D_

Get HTML5 localStorage keys

in ES2017 you can use:


Origin http://localhost is not allowed by Access-Control-Allow-Origin

This approach resolved my issue to allow multiple domain

app.use(function(req, res, next) {
      var allowedOrigins = ['', 'http://localhost:8020', '', 'http://localhost:9000'];
      var origin = req.headers.origin;
      if(allowedOrigins.indexOf(origin) > -1){
           res.setHeader('Access-Control-Allow-Origin', origin);
      //res.header('Access-Control-Allow-Origin', '');
      res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.header('Access-Control-Allow-Credentials', true);
      return next();

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

My personal experience to build website with html, css en javascript is just to stick with plain text editors with ftp support. I am using Espresso or/and Coda on my mac. But Textmate with Cyberduck(ftp client) is also a great combination, imo. For developing in Windows I recommend notepad++.

"Press Any Key to Continue" function in C

You can try more system indeppended method: system("pause");

Convert Python dictionary to JSON array

If you use Python 2, don't forget to add the UTF-8 file encoding comment on the first line of your script.

# -*- coding: UTF-8 -*-

This will fix some Unicode problems and make your life easier.

How to determine the screen width in terms of dp or dip at runtime in Android?

If you just want to know about your screen width, you can just search for "smallest screen width" in your developer options. You can even edit it.

What does EntityManager.flush do and why do I need to use it?

A call to EntityManager.flush(); will force the data to be persist in the database immediately as EntityManager.persist() will not (depending on how the EntityManager is configured : FlushModeType (AUTO or COMMIT) by default it's set to AUTO and a flush will be done automatically by if it's set to COMMIT the persitence of the data to the underlying database will be delayed when the transaction is commited).

HTML Input="file" Accept Attribute File Type (CSV)

After my test, on ?macOS 10.15.7 Catalina?, the answer of ?Dom / Rikin Patel? cannot recognize the [.xlsx] file normally.

I personally summarized the practice of most of the existing answers and passed personal tests. Sum up the following answers:

accept=".csv, .xls, .xlsx, text/csv, application/csv,
text/comma-separated-values, application/csv, application/excel,
application/vnd.msexcel, text/anytext, application/vnd. ms-excel,

Elasticsearch query to return all records

A simple solution using the python package elasticsearch-dsl:

from elasticsearch_dsl import Search
from elasticsearch_dsl import connections


s = Search(index="foo")
response = s.scan()

count = 0
for hit in response:
    # print(hit.to_dict())  # be careful, it will printout every hit in your index
    count += 1


See also .

getting the error: expected identifier or ‘(’ before ‘{’ token

you need to place the opening brace after main , not before it

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)

How to make sure you don't get WCF Faulted state exception?

If the transfer mode is Buffered then make sure that the values of MaxReceivedMessageSize and MaxBufferSize is same. I just resolved the faulted state issue this way after grappling with it for hours and thought i'll post it here if it helps someone.

How to print the ld(linker) search path

The most compatible command I've found for gcc and clang on Linux (thanks to armando.sano):

$ gcc -m64 -Xlinker --verbose  2>/dev/null | grep SEARCH | sed 's/SEARCH_DIR("=\?\([^"]\+\)"); */\1\n/g'  | grep -vE '^$'

if you give -m32, it will output the correct library directories.

Examples on my machine:

for g++ -m64:


for g++ -m32:


Alternative to a goto statement in Java

StephenC writes:

There are two constructs that allow you to do some of the things you can do with a classic goto.

One more...

Matt Wolfe writes:

People always talk about never using a goto, but I think there is a really good real world use case which is pretty well known and used.. That is, making sure to execute some code before a return from a function.. Usually its releasing locks or what not, but in my case I'd love to be able to jump to a break right before the return so I can do required mandatory cleanup.

try {
    // do stuff
    return result;  // or break, etc.
finally {
    // clean up before actually returning, even though the order looks wrong.

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

The silly interview question associated with finally is: If you return from a try{} block, but have a return in your finally{} too, which value is returned?

Wampserver icon not going green fully, mysql services not starting up?

  1. Click on wamp (Yellow) icon

  2. Go Apache-> Service-> Test port 80. If port is available to use then go to Apache->Service-> Install Service

  3. then click on Restart All Services.

how to calculate percentage in python

I know I am late, but if you want to know the easiest way, you could do a code like this:

number = 100
right_questions = 1
control = 100
c = control / number
cc = right_questions * c
print float(cc)

You can change up the number score, and right_questions. It will tell you the percent.

Import txt file and having each line as a list

Create a list of lists:

with open("/path/to/file") as file:
    lines = []
    for line in file:
        # The rstrip method gets rid of the "\n" at the end of each line

CMake: How to build external projects and include their targets

I was searching for similar solution. The replies here and the Tutorial on top is informative. I studied posts/blogs referred here to build mine successful. I am posting complete CMakeLists.txt worked for me. I guess, this would be helpful as a basic template for beginners.


cmake_minimum_required(VERSION 3.10.2)

# Target Project
project (ClientProgram)

# Begin: Including Sources and Headers
file (GLOB SOURCES "src/*.c")
# End: Including Sources and Headers

# Begin: Generate executables
add_executable (ClientProgram ${SOURCES})
# End: Generate executables

# This Project Depends on External Project(s) 
include (ExternalProject)

# Begin: External Third Party Library
set (libTLS ThirdPartyTlsLibrary)
ExternalProject_Add (${libTLS}
# Begin: Download Archive from Web Server
URL_HASH        SHA1=<expected_sha1sum_of_above_tgz_file>
# End: Download Archive from Web Server

# Begin: Download Source from GIT Repository
#    GIT_REPOSITORY<project>.git
#    GIT_TAG         <Refer releases -> Tags>
# End: Download Source from GIT Repository

# Begin: CMAKE Comamnd Argiments
# End: CMAKE Comamnd Argiments    

# The above ExternalProject_Add(...) construct wil take care of \
# 1. Downloading sources
# 2. Building Object files
# 3. Install under DCMAKE_INSTALL_PREFIX Directory

# Acquire Installation Directory of 
ExternalProject_Get_Property (${libTLS} install_dir)

# Begin: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# Include PATH that has headers required by Target Project
include_directories (${install_dir}/include)

# Import librarues from External Project required by Target Project
add_library (lmytls SHARED IMPORTED)
set_target_properties (lmytls PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/
add_library (lmyxdot509 SHARED IMPORTED)
set_target_properties(lmyxdot509 PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/

# End: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# End: External Third Party Library

# Begin: Target Project depends on Third Party Component
add_dependencies(ClientProgram ${libTLS})
# End: Target Project depends on Third Party Component

# Refer libraries added above used by Target Project
target_link_libraries (ClientProgram lmytls lmyxdot509)

Java: get all variable names in a class

Field[] fields = YourClassName.class.getFields();

returns an array of all public variables of the class.

getFields() return the fields in the whole class-heirarcy. If you want to have the fields defined only in the class in question, and not its superclasses, use getDeclaredFields(), and filter the public ones with the following Modifier approach:


The YourClassName.class literal actually represents an object of type java.lang.Class. Check its docs for more interesting reflection methods.

The Field class above is java.lang.reflect.Field. You may take a look at the whole java.lang.reflect package.

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
    // Do things

void Bar()
    int anInt = 1;
    Foo(anInt, 2.0);

Here i and f are the parameters, and anInt and 2.0 are the arguments.

What are the differences between C, C# and C++ in terms of real-world applications?

Bear in mind that I speak ASFAC++B. :) I've put the most important differentiating factor first.

Garbage Collection

Garbage Collection (GC) is the single most important factor in differentiating between these languages.

While C and C++ can be used with GC, it is a bolted-on afterthought and cannot be made to work as well (the best known is here) - it has to be "conservative" which means that it cannot collect all unused memory.

C# is designed from the ground up to work on a GC platform, with standard libraries also designed that way. It makes an absolutely fundamental difference to developer productivity that has to be experienced to be believed.

There is a belief widespread among C/C++ users that GC equates with "bad performance". But this is out-of-date folklore (even the Boehm collector on C/C++ performs much better than most people expect it to). The typical fear is of "long pauses" where the program stops so the GC can do some work. But in reality these long pauses happen with non-GC programs, because they run on top of a virtual memory system, which occasionally interrupts to move data between physical memory and disk.

There is also widespread belief that GC can be replaced with shared_ptr, but it can't; the irony is that in a multi-threaded program, shared_ptr is slower than a GC-based system.

There are environments that are so frugal that GC isn't practical - but these are increasingly rare. Cell phones typically have GC. The CLR's GC that C# typically runs on appears to be state-of-the-art.

Since adopting C# about 18 months ago I've gone through several phases of pure performance tuning with a profiler, and the GC is so efficient that it is practically invisible during the operation of the program.

GC is not a panacea, it doesn't solve all programming problems, it only really cleans up memory allocation, if you're allocating very large memory blocks then you will still need to take some care, and it is still possible to have what amounts to a memory leak in a sufficiently complex program - and yet, the effect of GC on productivity makes it a pretty close approximation to a panacea!

Undefined Behaviour

C++ is founded on the notion of undefined behaviour. That is, the language specification defines the outcome of certain narrowly defined usages of language features, and describes all other usages as causing undefined behaviour, meaning in principle that the operation could have any outcome at all (in practice this means hard-to-diagnose bugs involving apparently non-deterministic corruption of data).

Almost everything about C++ touches on undefined behaviour. Even very nice forthcoming features like lambda expressions can easily be used as convenient way to corrupt the stack (capture a local by reference, allow the lambda instance to outlive the local).

C# is founded on the principle that all possible operations should have defined behaviour. The worst that can happen is an exception is thrown. This completely changes the experience of software construction.

(There's unsafe mode, which has pointers and therefore undefined behaviour, but that is strongly discouraged for general use - think of it as analogous to embedded assembly language.)


In terms of complexity, C++ has to be singled out, especially if we consider the very-soon-to-be standardized new version. C++ does absolutely everything it can to make itself effective, short of assuming GC, and as a result it has an awesome learning curve. The language designers excuse much of this by saying "Those features are only for library authors, not ordinary users" - but to be truly effective in any language, you need to build your code as reusable libraries. So you can't escape.

On the positive side, C++ is so complex, it's like a playground for nerds! I can assure you that you would have a lot of fun learning how it all fits together. But I can't seriously recommend it as a basis for productive new work (oh, the wasted years...) on mainstream platforms.

C keeps the language simple (simple in the sense of "the compiler is easy to write"), but this makes the coding techniques more arcane.

Note that not all new language features equate with added complexity. Some language features are described as "syntactic sugar", because they are shorthand that the compiler expands for you. This is a good way to think of a great deal of the enhancements to C# over recent years. The language standard even specifies some features by giving the translation to longhand, e.g. using statement expands into try/finally.

At one point, it was possible to think of C++ templates in the same way. But they've since become so powerful that they are now form the basis of a whole separate dimension of the language, with its own enthusiastic user communities and idioms.


The strangest thing about C and C++ is that they don't have a standard interchangeable form of pre-compiled library. Integrating someone else's code into your project is always a little fiddly, with obscure decisions to be made about how you'll be linking to it.

Also, the standard library is extremely basic - C++ has a complete set of data structures and a way of representing strings (std::string), but that's still minimal. Is there a standard way of finding a list of files in a directory? Amazingly, no! Is there standard library support for parsing or generating XML? No. What about accessing databases? Be serious! Writing a web site back-end? Are you crazy? etc.

So you have to go hunting further afield. For XML, try Xerces. But does it use std::string to represent strings? Of course not!

And do all these third-party libraries have their own bizarre customs for naming classes and functions? You betcha!

The situation in C# couldn't be more different; the fundamentals were in place from the start, so everything inter-operates beautifully (and because the fundamentals are supplied by the CLR, there is cross-language support).

It's not all perfect; generics should have been in place from the start but wasn't, which does leave a visible scar on some older libraries; but it is usually trivial to fix this externally. Also a number of popular libraries are ported from Java, which isn't as good a fit as it first appears.

Closures (Anonymous Methods with Local Variable Capture)

Java and C are practically the last remaining mainstream languages to lack closures, and libraries can be designed and used much more neatly with them than without (this is one reason why ported Java libraries sometimes seem clunky to a C# user).

The amusing thing about C++ is that its standard library was designed as if closures were available in the language (container types, <algorithm>, <functional>). Then ten years went by, and now they're finally being added! They will have a huge impact (although, as noted above, they leak underfined behaviour).

C# and JavaScript are the most widely used languages in which closures are "idiomatically established". (The major difference between those languages being that C# is statically typed while JavaScript is dynamically typed).

Platform Support

I've put this last only because it doesn't appear to differentiate these languages as much as you might think. All these languages can run on multiple OSes and machine architectures. C is the most widely-supported, then C++, and finally C# (although C# can be used on most major platforms thanks to an open source implementation called Mono).

My experience of porting C++ programs between Windows and various Unix flavours was unpleasant. I've never tried porting anything very complex in C# to Mono, so I can't comment on that.

Drop data frame columns by name

Out of interest, this flags up one of R's weird multiple syntax inconsistencies. For example given a two-column data frame:

df <- data.frame(x=1, y=2)

This gives a data frame

subset(df, select=-y)

but this gives a vector


This is all explained in ?[ but it's not exactly expected behaviour. Well at least not to me...

TimePicker Dialog from clicking EditText

Why not write in a re-usable way ?

Create SetTime class:

class SetTime implements OnFocusChangeListener, OnTimeSetListener {   

       private EditText editText;
       private Calendar myCalendar;

       public SetTime(EditText editText, Context ctx){
           this.editText = editText;
           this.myCalendar = Calendar.getInstance();


        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
                int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
                int minute = myCalendar.get(Calendar.MINUTE);
                new TimePickerDialog(ctx, this, hour, minute, true).show();

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // TODO Auto-generated method stub
            this.editText.setText( hourOfDay + ":" + minute);


Then call it from onCreate function:

    EditText editTextFromTime = (EditText) findViewById(;
    SetTime fromTime = new SetTime(editTextFromTime, this);

Adding a library/JAR to an Eclipse Android project

Go to build path in eclipse, then click order and export, then check the library/jar, and then click the up button to move it to the top of the list to compile it first.

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Fabrício's answer is spot on; but I wanted to complement his answer with something less technical, which focusses on an analogy to help explain the concept of asynchronicity.

An Analogy...

Yesterday, the work I was doing required some information from a colleague. I rang him up; here's how the conversation went:

Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim wants a report on it, and you're the only one who knows the details about it.

Bob: Sure thing, but it'll take me around 30 minutes?

Me: That's great Bob. Give me a ring back when you've got the information!

At this point, I hung up the phone. Since I needed information from Bob to complete my report, I left the report and went for a coffee instead, then I caught up on some email. 40 minutes later (Bob is slow), Bob called back and gave me the information I needed. At this point, I resumed my work with my report, as I had all the information I needed.

Imagine if the conversation had gone like this instead;

Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim want's a report on it, and you're the only one who knows the details about it.

Bob: Sure thing, but it'll take me around 30 minutes?

Me: That's great Bob. I'll wait.

And I sat there and waited. And waited. And waited. For 40 minutes. Doing nothing but waiting. Eventually, Bob gave me the information, we hung up, and I completed my report. But I'd lost 40 minutes of productivity.

This is asynchronous vs. synchronous behavior

This is exactly what is happening in all the examples in our question. Loading an image, loading a file off disk, and requesting a page via AJAX are all slow operations (in the context of modern computing).

Rather than waiting for these slow operations to complete, JavaScript lets you register a callback function which will be executed when the slow operation has completed. In the meantime, however, JavaScript will continue to execute other code. The fact that JavaScript executes other code whilst waiting for the slow operation to complete makes the behaviorasynchronous. Had JavaScript waited around for the operation to complete before executing any other code, this would have been synchronous behavior.

var outerScopeVar;    
var img = document.createElement('img');

// Here we register the callback function.
img.onload = function() {
    // Code within this function will be executed once the image has loaded.
    outerScopeVar = this.width;

// But, while the image is loading, JavaScript continues executing, and
// processes the following lines of JavaScript.
img.src = 'lolcat.png';

In the code above, we're asking JavaScript to load lolcat.png, which is a sloooow operation. The callback function will be executed once this slow operation has done, but in the meantime, JavaScript will keep processing the next lines of code; i.e. alert(outerScopeVar).

This is why we see the alert showing undefined; since the alert() is processed immediately, rather than after the image has been loaded.

In order to fix our code, all we have to do is move the alert(outerScopeVar) code into the callback function. As a consequence of this, we no longer need the outerScopeVar variable declared as a global variable.

var img = document.createElement('img');

img.onload = function() {
    var localScopeVar = this.width;

img.src = 'lolcat.png';

You'll always see a callback is specified as a function, because that's the only* way in JavaScript to define some code, but not execute it until later.

Therefore, in all of our examples, the function() { /* Do something */ } is the callback; to fix all the examples, all we have to do is move the code which needs the response of the operation into there!

* Technically you can use eval() as well, but eval() is evil for this purpose

How do I keep my caller waiting?

You might currently have some code similar to this;

function getWidthOfImage(src) {
    var outerScopeVar;

    var img = document.createElement('img');
    img.onload = function() {
        outerScopeVar = this.width;
    img.src = src;
    return outerScopeVar;

var width = getWidthOfImage('lolcat.png');

However, we now know that the return outerScopeVar happens immediately; before the onload callback function has updated the variable. This leads to getWidthOfImage() returning undefined, and undefined being alerted.

To fix this, we need to allow the function calling getWidthOfImage() to register a callback, then move the alert'ing of the width to be within that callback;

function getWidthOfImage(src, cb) {     
    var img = document.createElement('img');
    img.onload = function() {
    img.src = src;

getWidthOfImage('lolcat.png', function (width) {

... as before, note that we've been able to remove the global variables (in this case width).

Getting current directory in VBScript

You can use CurrentDirectory property.

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

How do I write a correct micro-benchmark in Java?

Should the benchmark measure time/iteration or iterations/time, and why?

It depends on what you are trying to test.

If you are interested in latency, use time/iteration and if you are interested in throughput, use iterations/time.

Do I need to close() both FileReader and BufferedReader?

Starting from Java 7 you can use try-with-resources Statement

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();

Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly. So you don't need to close it yourself in the finally statement. (This is also the case with nested resource statements)

This is the recomanded way to work with resources, see the documentation for more detailed information

using where and inner join in mysql

Try this:

SELECT Locations.Name, Schools.Name
FROM Locations
INNER JOIN School_Locations ON School_Locations.Locations_Id = Locations.Id
INNER JOIN Schools ON School.Id = Schools_Locations.School_Id
WHERE Locations.Type = "coun"

You can join Locations to School_Locations and then School_Locations to School. This forms a set of all related Locations and Schools, which you can then widdle down using the WHERE clause to those whose Location is of type "coun."

What are the rules about using an underscore in a C++ identifier?

The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).

Personal rule

Because I did not want to deal with cases, and wanted a simple rule, I have designed a personal one that is both simple and correct:

When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:

  • never start a symbol with an underscore
  • never name a symbol with two consecutive underscores inside.

Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros)

Some examples

(I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name)

#define _WRONG
#define __WRONG_AGAIN
#define RIGHT_
#define WRONG__WRONG
#define RIGHT_x_RIGHT

Extracts from C++0x draft

From the n3242.pdf file (I expect the final standard text to be similar): Global names [global.names]

Certain sets of names and function signatures are always reserved to the implementation:

— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.

— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

But also: User-defined literal suffixes [usrlit.suffix]

Literal suffix identifiers that do not start with an underscore are reserved for future standardization.

This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if not defined in the global namespace...

Adding Http Headers to HttpClient

Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri(""),
    Method = HttpMethod.Get,
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        var jsonObject = jsonTask.Result;

How to print values separated by spaces instead of new lines in Python 2.7

First of all print isn't a function in Python 2, it is a statement.

To suppress the automatic newline add a trailing ,(comma). Now a space will be used instead of a newline.


print 1,
print 2


1 2

Or use Python 3's print() function:

from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'

As you can clearly see print() function is much more powerful as we can specify any string to be used as end rather a fixed space.

Select a Column in SQL not in Group By

Thing I like to do is to wrap addition columns in aggregate function, like max(). It works very good when you don't expect duplicate values.

Select MAX(cpe.createdon) As MaxDate, cpe.fmgcms_cpeclaimid, MAX(cpe.fmgcms_claimid) As fmgcms_claimid 
from Filteredfmgcms_claimpaymentestimate cpe
where cpe.createdon < 'reportstartdate'
group by cpe.fmgcms_cpeclaimid

successful/fail message pop up box after submit?

Instead of using a submit button, try using a <button type="button">Submit</button>

You can then call a javascript function in the button, and after the alert popup is confirmed, you can manually submit the form with document.getElementById("form").submit(); ... so you'll need to name and id your form for that to work.

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

add your file android/app/build.gradle

 defaultConfig {
        applicationId "com.ubicacion"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        multiDexEnabled true // ?
        missingDimensionStrategy 'react-native-camera', 'general'

Setting a checkbox as checked with Vue.js

I experienced this issue and couldn't figure out a fix for a few hours, until I realised I had incorrectly prevented native events from occurring with:

<input type="checkbox" @click.prevent="toggleConfirmedStatus(render.uuid)"
    :checked="confirmed.indexOf(render.uuid) > -1"

removing the .prevent from the @click handler fixed my issue.

Convert Iterable to Stream using Java 8 JDK

You can easily create a Stream out of an Iterable or Iterator:

public static <T> Stream<T> stream(Iterable<T> iterable) {

Remove a file from the list that will be committed

You have to reset that file to the original state and commit it again using --amend. This is done easiest using git checkout HEAD^.

Prepare demo:

$ git init
$ date >file-a
$ date >file-b
$ git add .
$ git commit -m "Initial commit"
$ date >file-a
$ date >file-b
$ git commit -a -m "the change which should only be file-a"

State before:

$ git show --stat
commit 4aa38f84e04d40a1cb40a5207ccd1a3cb3a4a317 (HEAD -> master)
Date:   Wed Feb 7 17:24:45 2018 +0100

    the change which should only be file-a

 file-a | 2 +-
 file-b | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

Here it comes: restore the previous version

$ git checkout HEAD^ file-b

commit it:

$ git commit --amend file-b
[master 9ef8b8b] the change which should only be file-a
 Date: Wed Feb 7 17:24:45 2018 +0100
 1 file changed, 1 insertion(+), 1 deletion(-)

State after:

$ git show --stat
commit 9ef8b8bab224c4d117f515fc9537255941b75885 (HEAD -> master)
Date:   Wed Feb 7 17:24:45 2018 +0100

    the change which should only be file-a

 file-a | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

How to set the title text color of UIButton?

set title color

btnGere.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)

AngularJS - Access to child scope

Using $emit and $broadcast, (as mentioned by walv in the comments above)

To fire an event upwards (from child to parent)

$scope.$emit('myTestEvent', 'Data to send');

To fire an event downwards (from parent to child)

$scope.$broadcast('myTestEvent', {
  someProp: 'Sending you some data'

and finally to listen

$scope.$on('myTestEvent', function (event, data) {

For more details :-

Enjoy :)

String contains - ignore case

Try this

public static void main(String[] args)

    String original = "ABCDEFGHIJKLMNOPQ";
    String tobeChecked = "GHi";

    System.out.println(containsString(original, tobeChecked, true));        
    System.out.println(containsString(original, tobeChecked, false));


public static boolean containsString(String original, String tobeChecked, boolean caseSensitive)
    if (caseSensitive)
        return original.contains(tobeChecked);

        return original.toLowerCase().contains(tobeChecked.toLowerCase());


MySQL CONCAT returns NULL if any field contain NULL

convert the NULL values with empty string by wrapping it in COALESCE

SELECT CONCAT(COALESCE(`affiliate_name`,''),'-',COALESCE(`model`,''),'-',COALESCE(`ip`,''),'-',COALESCE(`os_type`,''),'-',COALESCE(`os_version`,'')) AS device_name
FROM devices

error LNK2005, already defined?

The linker tells you that you have the variable k defined multiple times. Indeed, you have a definition in A.cpp and another in B.cpp. Both compilation units produce a corresponding object file that the linker uses to create your program. The problem is that in your case the linker does not know whic definition of k to use. In C++ you can have only one defintion of the same construct (variable, type, function).

To fix it, you will have to decide what your goal is

  • If you want to have two variables, both named k, you can use an anonymous namespace in both .cpp files, then refer to k as you are doing now:


namespace {
  int k;
  • You can rename one of the ks to something else, thus avoiding the duplicate defintion.
  • If you want to have only once definition of k and use that in both .cpp files, you need to declare in one as extern int k;, and leave it as it is in the other. This will tell the linker to use the one definition (the unchanged version) in both cases -- extern implies that the variable is defined in another compilation unit.

Get client IP address via third party web service

Checking your linked site, you may include a script tag passing a ?var=desiredVarName parameter which will be set as a global variable containing the IP address:

<script type="text/javascript" src=""></script>
                                                      <!-- ^^^^ -->


I believe I don't have to say that this can be easily spoofed (through either use of proxies or spoofed request headers), but it is worth noting in any case.

HTTPS support

In case your page is served using the https protocol, most browsers will block content in the same page served using the http protocol (that includes scripts and images), so the options are rather limited. If you have < 5k hits/day, the Smart IP API can be used. For instance:

var myip;
function ip_callback(o) {
    myip =;
<script src=""></script>


Edit: Apparently, this https service's certificate has expired so the user would have to add an exception manually. Open its API directly to check the certificate state:

With back-end logic

The most resilient and simple way, in case you have back-end server logic, would be to simply output the requester's IP inside a <script> tag, this way you don't need to rely on external resources. For example:


<script>var myip = '<?php echo $_SERVER['REMOTE_ADDR']; ?>';</script>

There's also a more sturdy PHP solution (accounting for headers that are sometimes set by proxies) in this related answer.


<script>var myip = '<%= Request.UserHostAddress %>';</script>

Windows Application has stopped working :: Event Name CLR20r3

Make sure the client computer has the same or higher version of the .NET framework that you built your program to.

Add missing dates to pandas dataframe

You could use Series.reindex:

import pandas as pd

idx = pd.date_range('09-01-2013', '09-30-2013')

s = pd.Series({'09-02-2013': 2,
               '09-03-2013': 10,
               '09-06-2013': 5,
               '09-07-2013': 1})
s.index = pd.DatetimeIndex(s.index)

s = s.reindex(idx, fill_value=0)


2013-09-01     0
2013-09-02     2
2013-09-03    10
2013-09-04     0
2013-09-05     0
2013-09-06     5
2013-09-07     1
2013-09-08     0

Get webpage contents with Python?

If you ask me. try this one

import urllib2
resp = urllib2.urlopen('')

and read the normal way ie

page =

Good luck though

How to programmatically tell if a Bluetooth device is connected?

Big thanks to Skylarsutton for his answer. I'm posting this as a response to his, but because I'm posting code I can't reply as a comment. I already upvoted his answer so am not looking for any points. Just paying it forward.

For some reason BluetoothAdapter.ACTION_ACL_CONNECTED could not be resolved by Android Studio. Perhaps it was deprecated in Android 4.2.2? Here is a modification of his code. The registration code is the same; the receiver code differs slightly. I use this in a service which updates a Bluetooth-connected flag that other parts of the app reference.

    public void onCreate() {
        IntentFilter filter = new IntentFilter();
        this.registerReceiver(BTReceiver, filter);

    //The BroadcastReceiver that listens for bluetooth broadcasts
    private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            //Do something if connected
            Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            //Do something if disconnected
            Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
        //else if...

error: Libtool library used but 'LIBTOOL' is undefined

For mac it's simple:

brew install libtool

Laravel requires the Mcrypt PHP extension

For ubuntu try these steps if others are not working :

  1. cd ~
  2. sudo apt-get remove php5-mcrypt
  3. sudo apt-get install php5-mcrypt
  4. sudo php5enmod mcrypt
  5. sudo service apache2 restart

Hope that will help. Thanks !

How to join a slice of strings into a single string?

This is still relevant in 2018.

To String

import strings
stringFiles := strings.Join(fileSlice[:], ",")

Back to Slice again

import strings
fileSlice := strings.Split(stringFiles, ",")

"Undefined reference to" template class constructor

This link explains where you're going wrong:

[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?

Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.

This offers another solution:

How can I avoid linker errors with my template functions?

However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.

Compiler error: "initializer element is not a compile-time constant"

The reason is that your are defining your imageSegment outside of a function in your source code (static variable).

In such cases, the initialization cannot include execution of code, like calling a function or allocation a class. Initializer must be a constant whose value is known at compile time.

You can then initialize your static variable inside of your init method (if you postpone its declaration to init).

click or change event on radio using jquery

This code worked for me:




Using Google Translate in C#

Google Translate Kit, an open source library

Translator gt = new Translator();
/*using cache*/
DemoWriter dw = new DemoWriter();
gt.KeyGen = new SimpleKeyGen();
gt.CacheManager = new SimleCacheManager();
gt.Writer = dw;
Translator.TranslatedPost post = gt.GetTranslatedPost("Hello world", LanguageConst.ENGLISH, LanguageConst.CHINESE);
Translator.TranslatedPost post2 = gt.GetTranslatedPost("I'm Jeff", LanguageConst.ENGLISH, LanguageConst.CHINESE);
this.result.InnerHtml = "<p>" + post.text +post2.text+ "</p>";

App not setup: This app is still in development mode

I had the same problem and it took me around one hour to figure out where i went wrong only to note that i had used a wrong app id....just go to your code and used a correct id here

window.fbAsyncInit = function() {
        appId      : '1740077446229063',//your app id
        cookie     : true,  // enable cookies to allow the server to access
        // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5

Switching the order of block elements with CSS

I known this is old, but I found a easier solution and it works on ie10, firefox and chrome:

<div id="wrapper">
  <div id="one">One</div>
  <div id="two">Two</div>
  <div id="three">Three</div>

This is the css:

#wrapper {display:table;}
#one {display:table-footer-group;}
#three {display:table-header-group;}

And the result:


I found it here.

How can I make space between two buttons in same div?

Put them inside btn-toolbar or some other container, not btn-group. btn-group joins them together. More info on Bootstrap documentation.

Edit: The original question was for Bootstrap 2.x, but the same is still valid for Bootstrap 3 and Bootstrap 4.

In Bootstrap 4 you will need to add appropriate margin to your groups using utility classes, such as mx-2.

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

Update Collation of all fields in database on the fly

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:


How to URL encode a string in Ruby

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a".force_encoding('ASCII-8BIT')
puts CGI.escape str

=> "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

git: diff between file in local repo and origin

If [remote-path] and [local-path] are the same, you can do

$ git fetch origin master
$ git diff origin/master -- [local-path]

Note 1: The second command above will compare against the locally stored remote tracking branch. The fetch command is required to update the remote tracking branch to be in sync with the contents of the remote server. Alternatively, you can just do

$ git diff master:<path-or-file-name>

Note 2: master can be replaced in the above examples with any branch name

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

if you have lower version and getting problem importing project with high gradle version and want to run the project without updating gradle than

open your gradle file(Project) and do the small change

  dependencies {
           /*Higher Gradle version*/
//        classpath ''

        /*Add this line and remove the Higher one*/
        classpath ''

[2.3.3 is stand for your gradle version]

in your case change version to 3.2 or 3.2.0 something like that

How can I get table names from an MS Access Database?

To build on Ilya's answer try the following query:

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name 

(this one works without modification with an MDB)

ACCDB users may need to do something like this

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6))
        AND ((MSysObjects.Flags)=0))
order by MSysObjects.Name 

As there is an extra table is included that appears to be a system table of some sort.

C# Creating an array of arrays

The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.

int[,] list = new int[4,4] {

You could also do

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[,] lists = new int[4,4] {

Inserting a value into all possible locations in a list

Coming from JavaScript, this was something I was used to having "built-in" via Array.prototype.splice(), so I made a Python function that does the same:

def list_splice(target, start, delete_count=None, *items):
    """Remove existing elements and/or add new elements to a list.

    target        the target list (will be changed)
    start         index of starting position
    delete_count  number of items to remove (default: len(target) - start)
    *items        items to insert at start index

    Returns a new list of removed items (or an empty list)
    if delete_count == None:
        delete_count = len(target) - start

    # store removed range in a separate list and replace with *items
    total = start + delete_count
    removed = target[start:total]
    target[start:total] = items

    return removed

Failed to find 'ANDROID_HOME' environment variable

I would like to share an answer that also demonstrates approach using the Android SDK provided by the Ubuntu repository:

Install Android SDK

sudo apt-get install android-sdk

Export environmental variables

export ANDROID_HOME="/usr/lib/android-sdk/"
export PATH="${PATH}:${ANDROID_HOME}tools/:${ANDROID_HOME}platform-tools/"

What is the difference between And and AndAlso in VB.NET?

A simple way to think about it is using even plainer English

If Bool1 And Bool2 Then
If [both are true] Then

If Bool1 AndAlso Bool2 Then
If [first is true then evaluate the second] Then

How do I use JDK 7 on Mac OSX?

Java 9, 10, 11

Years ago, Apple joined the OpenJDK project, transferring their formerly proprietary macOS-specific JVM code as free-of-cost open-source. Apple ceased distribution of their own branded JVM/JDK, relying on Oracle’s branded releases to include a version for macOS.

Oracle has recently announced their intention to bring their Oracle-branded JVM release to feature parity with the OpenJDK project, with virtually the same code base. The company even donated their previously commercial tools, Flight Recorder & Mission Control, to the OpenJDK project. This is part of the shift to a new rapid “release train” plan for predictably scheduled versioning of Java and OpenJDK. Notably, the periods for free-of-cost public updates is now shortened. See this 2017-09 announcement and this posting by Mark Reinhold.

As a result of all this, macOS users of Java have a choice of vendors for a Java implementation. At this point, at least three sources are based on OpenJDK for macOS:

  • Oracle releases of the JDK and JRE, with optional paid support.
  • Azul Systems releasing:
    • Zulu line of free-of-cost JVMs with optional paid support.
    • Zing line of commercial JVMs with special features such as an alternate garbage-collector.
  • OpenJDK source code, roll-your-own compilation & installation (perhaps not practical for most of us).

Meanwhile, IBM donated code for a JVM to the Eclipse Foundation, now housed in the OpenJ9 project. I wonder if they might support a macOS release as well, though it is too soon to tell.

Personally, I am currently using the Zulu release of Java 10.0.1 from Azul on macOS High Sierra successfully with IntelliJ 2018.2 to produce Java-backed web apps with Vaadin.


Both Oracle and Azul provide utterly easy-to-use installers to install the JVM/JDK on your Mac. Verify your installation by using the (or equivalent) to type and run:

java -version

You will find the Java installations in this folder at the root level of your drive (not in your home folder):


Each version from each vendor is found there, in a labeled nested folder. You can delete any installation simply by deleting the nested folder for that version and providing your system password when prompted.

Java 8

You can download the Java Development Kit (JDK) for Java 8 for the supported versions of Mac OS X:

  • Mountain Lion (10.8.3+)
  • Mavericks (10.9)
  • Yosemite (10.10)
  • El Capitan (10.11)

Each version of JVM you install can be found here:


For more instructions and FAQ, see this Oracle Guide.

Java 7

For every release of Java 7 since Update 4, a Mac version has been ready alongside the other platforms. Runs on Macs with 64-bit hardware on Lion (10.7.3+), Mountain Lion (10.8.3+), and Mavericks (10.9.x).

Oracle announced the official release of the JDK for Java SE 7 Update 4 on Mac OS X (Lion), as of 2012-04-26. No more need for the tricks discussed on this page.

Installation is simple per these instructions:

  1. Download from the usual place on the Oracle web site.
  2. Mount the DMG.
  3. Run the installer.

This release has a few limitations, most notably the lack of support for Java Web Start and the Java Plugin for web browsers. That support is expected later this year.

After installing, read the JDK for Mac ReadMe. Most importantly, if you want Java 7 to be the default, drag it to the top of the list in the Java Preferences app found in your Utilities folder.

Mac OS X easily supports multiple JVMs simultaneously. Each is now found here:


Congratulations to the Apple & Oracle teams for their achievement. This geek gets a thrill seeing Mac OS X listed as a "Certified System Configuration".

Tip: To start Eclipse on a Mac with only Java 7 installed, open the alias file named eclipse rather than the file named

Java 6

Apple continues to supply an up-to-date implementation of Java 6 for all versions of Mac OS X up through Mountain Lion.

If you do something that requires Java, such as type "java -version" in, a dialog appears offering to install Java for you. If you accept, installation happens automatically similar to other "Software Updates" from Apple.

You will find Java installed in this location, different than Java 7 & 8:


Java 6 has reached end-of-life with Oracle as of 2013-02 (unless you have a commercial support agreement with Oracle). So you should be moving to Java 7 or 8.

Testing New Version

In, type java -version to verify which version is the current default.

Deleting Old Versions

After installing a fresh version, you may want to visit the folder described above to delete old versions. Move the folder to the Trash, and provide your System password complete the move.

By the way, Apple provides a mailing list for developers’ technical issues related to Java on OS X.

How to install sklearn?

I would recommend you look at getting the anaconda package, it will install and configure Sklearn and its dependencies.

How to list active / open connections in Oracle?

Select count(1) From V$session
where status='ACTIVE'

How do I wait for a promise to finish before returning the variable of a function?

You're not actually using promises here. Parse lets you use callbacks or promises; your choice.

To use promises, do the following:

query.find().then(function() {
}, function() {

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. So far this would be exactly the same as regular callbacks.

To actually make good use of promises is when you chain them, like this:

query.find().then(function() {

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");

MVC Razor Hidden input and passing values

If you are using Razor, you cannot access the field directly, but you can manage its value.

The idea is that the first Microsoft approach drive the developers away from Web Development and make it easy for Desktop programmers (for example) to make web applications.

Meanwhile, the web developers, did not understand this tricky strange way of ASP.NET.

Actually this hidden input is rendered on client-side, and the ASP has no access to it (it never had). However, in time you will see its a piratical way and you may rely on it, when you get use with it. The web development differs from the Desktop or Mobile.

The model is your logical unit, and the hidden field (and the whole view page) is just a representative view of the data. So you can dedicate your work on the application or domain logic and the view simply just serves it to the consumer - which means you need no detailed access and "brainstorming" functionality in the view.

The controller actually does work you need for manage the hidden or general setup. The model serves specific logical unit properties and functionality and the view just renders it to the end user, simply said. Read more about MVC.


public class MyClassModel
    public int Id { get; set; }
    public string Name { get; set; }
    public string MyPropertyForHidden { get; set; }

This is the controller aciton

public ActionResult MyPageView()
    MyClassModel model = new MyClassModel(); // Single entity, strongly-typed
    // IList model = new List<MyClassModel>(); // or List, strongly-typed
    // ViewBag.MyHiddenInputValue = "Something to pass"; // ...or using ViewBag

    return View(model);

The view is below

//This will make a Model property of the View to be of MyClassModel
@model MyNamespace.Models.MyClassModel // strongly-typed view
// @model IList<MyNamespace.Models.MyClassModel> // list, strongly-typed view

// ... Some Other Code ...

@using(Html.BeginForm()) // Creates <form>
    // Renders hidden field for your model property (strongly-typed)
    // The field rendered to server your model property (Address, Phone, etc.)
    Html.HiddenFor(model => Model.MyPropertyForHidden); 

    // For list you may use foreach on Model
    // foreach(var item in Model) or foreach(MyClassModel item in Model)

// ... Some Other Code ...

The view with ViewBag:

// ... Some Other Code ...

@using(Html.BeginForm()) // Creates <form>
        new { @class = "hiddencss", maxlength = 255 /*, etc... */ }

// ... Some Other Code ...

We are using Html Helper to render the Hidden field or we could write it by hand - <input name=".." id=".." value="ViewBag.MyHiddenInputValue"> also.

The ViewBag is some sort of data carrier to the view. It does not restrict you with model - you can place whatever you like.

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

If you are using NodeJs for your server side, just add these to your route and you will be Ok

     res.header("Access-Control-Allow-Origin", "*");
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

Your route will then look somehow like this'/odin', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

    return res.json({Name:, Phone:});

Client side for Ajax call

 var sendingData = {
   name: "Odinfono Emmanuel",
   phone: "1234567890"


        url: '',            
        method: 'POST',
        type: 'json',
        data: sendingData,
        success: function (response) {
        error: function (error) {

You should have something like this in your browser console as response

{ name: "Odinfono Emmanuel", phone: "1234567890"}

Enjoy coding....

java get file size efficiently

Actually, I think the "ls" may be faster. There are definitely some issues in Java dealing with getting File info. Unfortunately there is no equivalent safe method of recursive ls for Windows. (cmd.exe's DIR /S can get confused and generate errors in infinite loops)

On XP, accessing a server on the LAN, it takes me 5 seconds in Windows to get the count of the files in a folder (33,000), and the total size.

When I iterate recursively through this in Java, it takes me over 5 minutes. I started measuring the time it takes to do file.length(), file.lastModified(), and file.toURI() and what I found is that 99% of my time is taken by those 3 calls. The 3 calls I actually need to do...

The difference for 1000 files is 15ms local versus 1800ms on server. The server path scanning in Java is ridiculously slow. If the native OS can be fast at scanning that same folder, why can't Java?

As a more complete test, I used WineMerge on XP to compare the modified date, and size of the files on the server versus the files locally. This was iterating over the entire directory tree of 33,000 files in each folder. Total time, 7 seconds. java: over 5 minutes.

So the original statement and question from the OP is true, and valid. Its less noticeable when dealing with a local file system. Doing a local compare of the folder with 33,000 items takes 3 seconds in WinMerge, and takes 32 seconds locally in Java. So again, java versus native is a 10x slowdown in these rudimentary tests.

Java 1.6.0_22 (latest), Gigabit LAN, and network connections, ping is less than 1ms (both in the same switch)

Java is slow.

Import Excel Spreadsheet Data to an EXISTING sql table?

You can copy-paste data from en excel-sheet to an SQL-table by doing so:

  • Select the data in Excel and press Ctrl + C
  • In SQL Server Management Studio right click the table and choose Edit Top 200 Rows
  • Scroll to the bottom and select the entire empty row by clicking on the row header
  • Paste the data by pressing Ctrl + V

Note: Often tables have a first column which is an ID-column with an auto generated/incremented ID. When you paste your data it will start inserting the leftmost selected column in Excel into the leftmost column in SSMS thus inserting data into the ID-column. To avoid that keep an empty column at the leftmost part of your selection in order to skip that column in SSMS. That will result in SSMS inserting the default data which is the auto generated ID.

Furthermore you can skip other columns by having empty columns at the same ordinal positions in the Excel sheet selection as those columns to be skipped. That will make SSMS insert the default value (or NULL where no default value is specified).

Hidden TextArea

but is the css style tag the correct way to get cross browser compatibility?

 <textarea style="display:none;" ></textarea>

or what I learned long ago....

     <textarea hidden ></textarea>

the global hidden element method:

    <textarea hidden="hidden" ></textarea>       

laravel 5.4 upload image

Use the following code:

$imageName = time().'.'.$request->input_img->getClientOriginalExtension();
$request->input_img->move(public_path('fotoupload'), $imageName);

new Date() is working in Chrome but not Firefox

Option 1 :

Suppose your timestring has a format that looks like this :

'2016-03-10 16:00:00.0'

In that case, you could do a simple regex to convert it to ISO 8601 :

'2016-03-10 16:00:00.0'.replace(/ /g,'T')

This would procude the following output :


This is the standard datetime format, and thus supported by all browsers :

document.body.innerHTML = new Date('2016-03-10T16:00:00.0') // THIS IS SAFE TO USE

Option 2 :

Suppose your timestring has a format that looks like this :

'02-24-2015 09:22:21 PM'

Here, you can do the following regex :

'02-24-2015 09:22:21 PM'.replace(/-/g,'/');

This, too, produces a format supported by all browsers :

document.body.innerHTML = new Date('02/24/2015 09:22:21 PM') // THIS IS SAFE TO USE

Option 3 :

Suppose you have a time string that isn't easy to adjust to one of the well-supported standards.

In that case, it's best to just split your time string into different pieces and use them as individual parameters for Date :

document.body.innerHTML = new Date(2016, 2, 26, 3, 24, 0); // THIS IS SAFE TO USE

How to convert ActiveRecord results into an array of hashes


You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name

tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json

# You can now add new records and return the result as json by calling `to_json`

tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }


You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example :

tasks_records = TaskStoreStatus.all

And if you want an ugly solution for Rails prior to v2.3

JSON.parse(tasks_records.to_json) # please don't do it

MySQL Workbench: How to keep the connection alive

I was getting this error 2013 and none of the above preference changes did anything to fix the problem. I restarted mysql service and the problem went away.

Sending email through Gmail SMTP server with C#

You can also connect via port 465, but due to some limitations of the System.Net.Mail namespace you may have to alter your code. This is because the namespace does not offer the ability to make implicit SSL connections. This is discussed at, and I have supplied an example of how to use the CDO (Collaborative Data Object) in another discussion (GMail SMTP via C# .Net errors on all ports).

Play audio with Python

In pydub we've recently opted to use ffplay (via subprocess) from the ffmpeg suite of tools, which internally uses SDL.

It works for our purposes – mainly just making it easier to test the results of pydub code in interactive mode – but it has it's downsides, like causing a new program to appear in the dock on mac.

I've linked the implementation above, but a simplified version follows:

import subprocess

def play(audio_file_path):["ffplay", "-nodisp", "-autoexit", audio_file_path])

The -nodisp flag stops ffplay from showing a new window, and the -autoexit flag causes ffplay to exit and return a status code when the audio file is done playing.

edit: pydub now uses pyaudio for playback when it's installed and falls back to ffplay to avoid the downsides I mentioned. The link above shows that implementation as well.

VBA module that runs other modules

Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule.

How to determine whether an object has a given property in JavaScript

Why not simply:

if (typeof myObject.myProperty == "undefined") alert("myProperty is not defined!");

Or if you expect a specific type:

if (typeof myObject.myProperty != "string") alert("myProperty has wrong type or does not exist!");

how to disable DIV element and everything inside

The following css statement disables click events


Could not resolve all dependencies for configuration ':classpath'

I try to modify the repositories and import the cer to java, but both failed, then I upgrade my jdk version from 1.8.0_66 to 1.8.0_74, gradle build success.

Difference between del, remove, and pop on lists

Since no-one else has mentioned it, note that del (unlike pop) allows the removal of a range of indexes because of list slicing:

>>> lst = [3, 2, 2, 1]
>>> del lst[1:]
>>> lst

This also allows avoidance of an IndexError if the index is not in the list:

>>> lst = [3, 2, 2, 1]
>>> del lst[10:]
>>> lst
[3, 2, 2, 1]

Preprocessor check if multiple defines are not defined

#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)

Bootstrap 3 Flush footer to bottom. not fixed

For people still struggling and the answered solution doesn't work quite as you want it to, here is the simplest solution I have found.

Wrap your main content and assign it a min view height. Adjust the 60 to whatever value your style needs.

<div id="content" style="min-height:60vh"></div>
<div id="footer"></div>

Thats it and it works pretty well.

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

I tried everything from unchecking offline work to matchingFallbacks. But nothing worked.

Then, in dependencies of app.gradle,

instead of

implementation project(':lib-name')

I used,

implementation project(path:':lib-name', configuration: 'default')

Eg: implementation project(path:':myService', configuration: 'default')

And it worked like a charm. :)

I was adding a dependency module with service and am not making a library as its a part of AOSP project.

Just in case, it helps someone.

Create Word Document using PHP in Linux

PHPWord can generate Word documents in docx format. It can also use an existing .docx file as a template - template variables can be added to the document in the format ${varname}

It has an LGPL license and the examples that came with the code worked nicely for me.

Get underlined text with Markdown

In GitHub markdown <ins>text</ins>works just fine.

Pythonic way to return list of every nth item in a larger list

Here is a better implementation of an "every 10th item" list comprehension, that does not use the list contents as part of the membership test:

>>> l = range(165)
>>> [ item for i,item in enumerate(l) if i%10==0 ]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]
>>> [ item for i,item in enumerate(l) if i%10==0 ]
['A', 'K', 'U']

But this is still far slower than just using list slicing.

T-SQL string replace in Update

The syntax for REPLACE:

REPLACE (string_expression,string_pattern,string_replacement)

So that the SQL you need should be:

UPDATE [DataTable] SET [ColumnValue] = REPLACE([ColumnValue], 'domain2', 'domain1')

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

I use typeof to determine if the variable I'm looking at is an object. If it is then I use instanceof to determine what kind it is

var type = typeof elem;
if (type == "number") {
    // do stuff
else if (type == "string") {
    // do stuff
else if (type == "object") { // either array or object
    if (elem instanceof Buffer) {
    // other stuff

Items in JSON object are out of order using "json.dumps"?

Both Python dict (before Python 3.7) and JSON object are unordered collections. You could pass sort_keys parameter, to sort the keys:

>>> import json
>>> json.dumps({'a': 1, 'b': 2})
'{"b": 2, "a": 1}'
>>> json.dumps({'a': 1, 'b': 2}, sort_keys=True)
'{"a": 1, "b": 2}'

If you need a particular order; you could use collections.OrderedDict:

>>> from collections import OrderedDict
>>> json.dumps(OrderedDict([("a", 1), ("b", 2)]))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict([("b", 2), ("a", 1)]))
'{"b": 2, "a": 1}'

Since Python 3.6, the keyword argument order is preserved and the above can be rewritten using a nicer syntax:

>>> json.dumps(OrderedDict(a=1, b=2))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict(b=2, a=1))
'{"b": 2, "a": 1}'

See PEP 468 – Preserving Keyword Argument Order.

If your input is given as JSON then to preserve the order (to get OrderedDict), you could pass object_pair_hook, as suggested by @Fred Yankowski:

>>> json.loads('{"a": 1, "b": 2}', object_pairs_hook=OrderedDict)
OrderedDict([('a', 1), ('b', 2)])
>>> json.loads('{"b": 2, "a": 1}', object_pairs_hook=OrderedDict)
OrderedDict([('b', 2), ('a', 1)])

Magento: Set LIMIT on collection

Order Collection Limit :

$orderCollection = Mage::getResourceModel('sales/order_collection'); 

foreach ($orderCollection->getItems() as $order) :
   $orderModel = Mage::getModel('sales/order');
   $order =   $orderModel->load($order['entity_id']);
   echo $order->getId().'<br>'; 

Twitter Bootstrap tabs not working: when I click on them nothing happens

Since i'm working with Bootstrap Javascript Modules instead of loading the entire Bootstrap Javascript, my tabs were not working because i forgot to load load/include/ the node_modules/bootstrap/js/tab.js file.

enter image description here

After including it, it worked...

Good Luck

Python float to int conversion

2.51 * 100 = 250.999999999997

The int() function simply truncates the number at the decimal point, giving 250. Use


to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.

How can I transform string to UTF-8 in C#?

Use the below code snippet to get bytes from csv file

protected byte[] GetCSVFileContent(string fileName)
        StringBuilder sb = new StringBuilder();
        using (StreamReader sr = new StreamReader(fileName, Encoding.Default, true))
            String line;
            // Read and display lines from the file until the end of 
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
        string allines = sb.ToString();

        UTF8Encoding utf8 = new UTF8Encoding();

        var preamble = utf8.GetPreamble();

        var data = utf8.GetBytes(allines);

        return data;

Call the below and save it as an attachment

           Encoding csvEncoding = Encoding.UTF8;
                   //byte[] csvFile = GetCSVFileContent(FileUpload1.PostedFile.FileName);
          byte[] csvFile = GetCSVFileContent("Your_CSV_File_NAme");

        string attachment = String.Format("attachment; filename={0}.csv", "uomEncoded");

        Response.ContentType = "text/csv";
        Response.ContentEncoding = csvEncoding;
        Response.AppendHeader("Content-Disposition", attachment);

querying WHERE condition to character length?

Sorry, I wasn't sure which SQL platform you're talking about:


$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");


$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");

The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.


I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.

So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():

    word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');

SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;

| word   | num_bytes | num_characters |
| ??    |         6 |              2 |
| happy  |         5 |              5 |
| hayir  |         6 |              5 |

Be careful if you're dealing with multi-byte characters.

How to send a GET request from PHP?

http_get should do the trick. The advantages of http_get over file_get_contents include the ability to view HTTP headers, access request details, and control the connection timeout.

$response = http_get("");

Assign command output to variable in batch file

This is work for me

@FOR /f "delims=" %i in ('reg query hklm\SOFTWARE\Macromedia\FlashPlayer\CurrentVersion') DO set var=%i
echo %var%

Getting an attribute value in xml element

How about:


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(new File("input.xml"));
        NodeList nodeList = document.getElementsByTagName("Item");
        for(int x=0,size= nodeList.getLength(); x<size; x++) {

AngularJS dynamic routing

Here is another solution that works good.

(function() {
    'use strict';

    route.$inject = ['$routeProvider'];

    function route($routeProvider) {

            .when('/:section', {
                templateUrl: buildPath
            .when('/:section/:page', {
                templateUrl: buildPath
            .when('/:section/:page/:task', {
                templateUrl: buildPath


    function buildPath(path) {

        var layout = 'layout';

        angular.forEach(path, function(value) {

            value = value.charAt(0).toUpperCase() + value.substring(1);
            layout += value;


        layout += '.tpl';

        return 'client/app/layouts/' + layout;



Javascript Equivalent to PHP Explode()

String.prototype.explode = function (separator, limit)
    const array = this.split(separator);
    if (limit !== undefined && array.length >= limit)
        array.push(array.splice(limit - 1).join(separator));
    return array;

Should mimic PHP's explode() function exactly.

'a'.explode('.', 2); // ['a']
'a.b'.explode('.', 2); // ['a', 'b']
'a.b.c'.explode('.', 2); // ['a', 'b.c']

How to keep a VMWare VM's clock in sync?

according to VMware's knowledge base, the actual solution depends on the Linux distro and release, in RHEL 5.3 I usually edit /etc/grub.conf and append this parameters to the kernel entry: divider=10 clocksource=acpi_pm

Then enable NTP, disable VMware time synchronization from vmware-toolbox and finally reboot the VM

A complete table with guidelines for each Linux distro can be found here:


RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

The RequestDispatcher interface allows you to do a server side forward/include whereas sendRedirect() does a client side redirect. In a client side redirect, the server will send back an HTTP status code of 302 (temporary redirect) which causes the web browser to issue a brand new HTTP GET request for the content at the redirected location. In contrast, when using the RequestDispatcher interface, the include/forward to the new resource is handled entirely on the server side.

Internet Explorer 11 detection

And how I implemented this

<script type="text/javascript">
  !(window.ActiveXObject) && "ActiveXObject"
  function isIE11(){
    return !!navigator.userAgent.match(/Trident.*rv[ :]*11\./);

How do I put variable values into a text string in MATLAB?

Here's how you convert numbers to strings, and join strings to other things (it's weird):

>> ['the number is ' num2str(15) '.']
ans =
the number is 15.

Tool to compare directories (Windows 7)

The tool that richardtz suggests is excellent.

Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.

You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge

How to add button in ActionBar(Android)?

An activity populates the ActionBar in its onCreateOptionsMenu() method.

Instead of using setcustomview(), just override onCreateOptionsMenu like this:

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

If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:

public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
      Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
      Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
  return true;

How To Show And Hide Input Fields Based On Radio Button Selection

***This will work.........
<!DOCTYPE html>
<script type="text/javascript">
 window.onload = function() {
    document.getElementById('ifYes').style.display = 'none';
    document.getElementById('ifNo').style.display = 'none';
function yesnoCheck() {
    if (document.getElementById('yesCheck').checked) {
        document.getElementById('ifYes').style.display = 'block';
        document.getElementById('ifNo').style.display = 'none';
        document.getElementById('redhat1').style.display = 'none';
        document.getElementById('aix1').style.display = 'none';
    else if(document.getElementById('noCheck').checked) {
        document.getElementById('ifNo').style.display = 'block';
        document.getElementById('ifYes').style.display = 'none';
        document.getElementById('redhat1').style.display = 'none';
        document.getElementById('aix1').style.display = 'none';
function yesnoCheck1() {
   if(document.getElementById('redhat').checked) {
       document.getElementById('redhat1').style.display = 'block';
       document.getElementById('aix1').style.display = 'none';
   if(document.getElementById('aix').checked) {
       document.getElementById('aix1').style.display = 'block';
       document.getElementById('redhat1').style.display = 'none';
Select os :<br>
<input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck"/>Unix
<input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"/>
<div id="ifYes" style="display:none">
Windows 2008<input type="radio" name="win" value="2008"/>
Windows 2012<input type="radio" name="win" value="2012"/>
<div id="ifNo" style="display:none">
Red Hat<input type="radio" name="unix" onclick="javascript:yesnoCheck1();"value="2008" 

AIX<input type="radio" name="unix" onclick="javascript:yesnoCheck1();"  
value="2012" id="aix"/>
<div id="redhat1" style="display:none">
Red Hat 6.0<input type="radio" name="redhat" value="2008" id="redhat6.0"/>
Red Hat 6.1<input type="radio" name="redhat" value="2012" id="redhat6.1"/>
<div id="aix1" style="display:none">
aix 6.0<input type="radio" name="aix" value="2008" id="aix6.0"/>
aix 6.1<input type="radio" name="aix" value="2012" id="aix6.1"/

Changing cursor to waiting in javascript/jquery

Here is something else interesting you can do. Define a function to call just before each ajax call. Also assign a function to call after each ajax call is complete. The first function will set the wait cursor and the second will clear it. They look like the following:

$(document).ajaxComplete(function(event, request, settings) {
    $('*').css('cursor', 'default');

function waitCursor() {
    $('*').css('cursor', 'progress');

MySQL my.cnf file - Found option without preceding group

it is because of letters or digit infront of [mysqld] just check the leeters or digit anything is not required before [mysqld]

it may be something like

0[mysqld] then this error will occur

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

I've modified the version above to run for all tables and support new SQL 2005 data types. It also retains the primary key names. Works only on SQL 2005 (using cross apply).

select  'create table [' + + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name  + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END
from    sysobjects so
cross apply
        '  ['+column_name+'] ' + 
        data_type + case data_type
            when 'sql_variant' then ''
            when 'text' then ''
            when 'ntext' then ''
            when 'xml' then ''
            when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
            else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' +
        case when exists ( 
        select id from syscolumns
        where object_name(id)
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1 
        ) then
        'IDENTITY(' + 
        cast(ident_seed( as varchar) + ',' + 
        cast(ident_incr( as varchar) + ')'
        else ''
        end + ' ' +
         (case when UPPER(IS_NULLABLE) = 'NO' then 'NOT ' else '' end ) + 'NULL ' + 
          case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', ' 

     from information_schema.columns where table_name =
     order by ordinal_position
    FOR XML PATH('')) o (list)
left join
    information_schema.table_constraints tc
on  tc.Table_name       = so.Name
AND tc.Constraint_Type  = 'PRIMARY KEY'
cross apply
    (select '[' + Column_Name + '], '
     FROM   information_schema.key_column_usage kcu
     WHERE  kcu.Constraint_Name = tc.Constraint_Name
     FOR XML PATH('')) j (list)
where   xtype = 'U'
AND name    NOT IN ('dtproperties')

Update: Added handling of the XML data type

Update 2: Fixed cases when 1) there is multiple tables with the same name but with different schemas, 2) there is multiple tables having PK constraint with the same name

Parse string to DateTime in C#

var dateStr = @"2011-03-21 13:26";
var dateTime = DateTime.ParseExact(dateStr, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture);

Check out this link for other format strings!

JSON Structure for List of Objects

As others mentioned, Justin's answer was close, but not quite right. I tested this using Visual Studio's "Paste JSON as C# Classes"

    "foos" : [

Python Pandas Replacing Header with Top Row

The best practice and Best OneLiner:


Notice the header value:

Header refer to the Row number(s) to use as the column names. Make no mistake, the row number is not the df but from the excel file(0 is the first row, 1 is the second and so on).

This way, you will get the column name you want and won't have to write additional codes or create new df.

Good thing is, it drops the replaced row.

Matching an empty input box using CSS

There is no selector in CSS which does this. Attribute selectors match attribute values, not computed values.

You would have to use JavaScript.

Shell Script: How to write a string to file and to stdout on console?

Use the tee command:

echo "hello" | tee logfile.txt